Skip to content

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

feat(orchestrator): answer on a pushback model after the person pushes back (#653)

Rufus3eb824263236
diff --git a/.env.example b/.env.example
index 0a88ad8c..de0878a3 100644
--- a/.env.example
+++ b/.env.example
@@ -97,6 +97,9 @@ OE_PUBLIC_DEPLOYMENT=
DEFAULT_MODEL=claude-sonnet-5-5
DEEP_REASONING_MODEL=claude-sonnet-5-5
ROUTING_MODEL=claude-haiku-5-5
+# The Executive's model for one answer after someone pushes back on the last
+# one (thumbs down, "that's not what I asked", the same ask again). Empty = off.
+PUSHBACK_MODEL=
# Data paths (defaults shown — relative to repo root, override with absolute paths if needed)
# VECTOR_STORE_PATH=./chroma_db
# COMPANY_PROFILE_PATH=./company/profile.yaml
diff --git a/docs/architecture.md b/docs/architecture.md
index 6f2d482d..b0eae1f0 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -568,6 +568,7 @@ All settings via environment variables (`.env` file in `packages/core/`).
| `DEFAULT_MODEL` | No | `claude-sonnet-4-6` | Model for Executive + most specialists |
| `DEEP_REASONING_MODEL` | No | `claude-sonnet-5-5` | Model for CSO, CFO, GC, Board |
| `ROUTING_MODEL` | No | `claude-haiku-5-5` | Model for intent routing and memory extraction |
+| `PUSHBACK_MODEL` | No | — (off) | The Executive's model for one answer after pushback on the last one |
| `VECTOR_STORE_PATH` | No | `./chroma_db` | ChromaDB persistence directory |
| `COMPANY_PROFILE_PATH` | No | `./company/profile.yaml` | Company profile location |
| `EPISODIC_DB_PATH` | No | `./episodic_memory.db` | SQLite for episodic memory, alerts, audit, scheduler |
diff --git a/packages/core/openexecutive/agents/overrides.py b/packages/core/openexecutive/agents/overrides.py
index 2ed599b9..60837891 100644
--- a/packages/core/openexecutive/agents/overrides.py
+++ b/packages/core/openexecutive/agents/overrides.py
@@ -40,6 +40,10 @@ class AgentOverride(BaseModel):
# so an admin can add guidance without freezing the agent on today's
# built-in prompt.
instructions: str | None = None
+ # The Executive's model for one answer after pushback
+ # (orchestrator.pushback): a model id, PUSHBACK_OFF to turn it off, or
+ # None to follow PUSHBACK_MODEL. Unused on the specialists.
+ pushback_model: str | None = None
updated_at: str | None = None
@@ -53,6 +57,7 @@ class AgentHistoryEntry(BaseModel):
voice_persona_slug: str | None = None
research_focus: str | None = None
instructions: str | None = None
+ pushback_model: str | None = None
created_at: str
@@ -100,6 +105,7 @@ def initialize_overrides_db(db_path: Path | None = None) -> None:
voice_persona_slug TEXT,
research_focus TEXT,
instructions TEXT,
+ pushback_model TEXT,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS agent_override_history (
@@ -112,6 +118,7 @@ def initialize_overrides_db(db_path: Path | None = None) -> None:
voice_persona_slug TEXT,
research_focus TEXT,
instructions TEXT,
+ pushback_model TEXT,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_override_history_agent
@@ -125,6 +132,8 @@ def initialize_overrides_db(db_path: Path | None = None) -> None:
_add_column_if_missing(conn, "agent_override_history", "research_focus")
_add_column_if_missing(conn, "agent_overrides", "instructions")
_add_column_if_missing(conn, "agent_override_history", "instructions")
+ _add_column_if_missing(conn, "agent_overrides", "pushback_model")
+ _add_column_if_missing(conn, "agent_override_history", "pushback_model")
def _row_to_override(row: Any) -> AgentOverride:
@@ -138,6 +147,7 @@ def _row_to_override(row: Any) -> AgentOverride:
voice_persona_slug=row["voice_persona_slug"],
research_focus=row["research_focus"],
instructions=row["instructions"],
+ pushback_model=row["pushback_model"],
updated_at=row["updated_at"],
)
@@ -193,6 +203,7 @@ def set_override(
voice_persona_slug: str | None = None,
research_focus: str | None = None,
instructions: str | None = None,
+ pushback_model: str | None = None,
prompt_set: bool = False,
model_set: bool = False,
deep_set: bool = False,
@@ -200,6 +211,7 @@ def set_override(
voice_persona_slug_set: bool = False,
research_focus_set: bool = False,
instructions_set: bool = False,
+ pushback_model_set: bool = False,
db_path: Path | None = None,
) -> AgentOverride:
"""Update one or more override fields for an agent.
@@ -223,8 +235,8 @@ def set_override(
conn.execute(
"INSERT INTO agent_override_history "
"(agent_id, prompt, model, use_deep_reasoning, role, voice_persona_slug, research_focus, "
- "instructions, created_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "instructions, pushback_model, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
agent_id,
existing_row["prompt"],
@@ -234,6 +246,7 @@ def set_override(
existing_row["voice_persona_slug"],
existing_row["research_focus"],
existing_row["instructions"],
+ existing_row["pushback_model"],
existing_row["updated_at"],
),
)
@@ -248,12 +261,16 @@ def set_override(
new_vp = voice_persona_slug if voice_persona_slug_set else existing_row["voice_persona_slug"]
new_rf = research_focus if research_focus_set else existing_row["research_focus"]
new_instr = instructions if instructions_set else existing_row["instructions"]
+ new_pm = pushback_model if pushback_model_set else existing_row["pushback_model"]
conn.execute(
"UPDATE agent_overrides SET prompt = ?, model = ?, "
"use_deep_reasoning = ?, role = ?, voice_persona_slug = ?, "
- "research_focus = ?, instructions = ?, updated_at = ? "
+ "research_focus = ?, instructions = ?, pushback_model = ?, updated_at = ? "
"WHERE agent_id = ?",
- (new_prompt, new_model, new_deep, new_role, new_vp, new_rf, new_instr, now, agent_id),
+ (
+ new_prompt, new_model, new_deep, new_role, new_vp, new_rf, new_instr,
+ new_pm, now, agent_id,
+ ),
)
else:
new_prompt = prompt if prompt_set else None
@@ -267,12 +284,16 @@ def set_override(
new_vp = voice_persona_slug if voice_persona_slug_set else None
new_rf = research_focus if research_focus_set else None
new_instr = instructions if instructions_set else None
+ new_pm = pushback_model if pushback_model_set else None
conn.execute(
"INSERT INTO agent_overrides "
"(agent_id, prompt, model, use_deep_reasoning, role, voice_persona_slug, research_focus, "
- "instructions, updated_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
- (agent_id, new_prompt, new_model, new_deep, new_role, new_vp, new_rf, new_instr, now),
+ "instructions, pushback_model, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ agent_id, new_prompt, new_model, new_deep, new_role, new_vp, new_rf, new_instr,
+ new_pm, now,
+ ),
)
invalidate_cache()
@@ -297,8 +318,8 @@ def clear_override(agent_id: str, db_path: Path | None = None) -> bool:
conn.execute(
"INSERT INTO agent_override_history "
"(agent_id, prompt, model, use_deep_reasoning, role, voice_persona_slug, research_focus, "
- "instructions, created_at) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "instructions, pushback_model, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
agent_id,
existing_row["prompt"],
@@ -308,6 +329,7 @@ def clear_override(agent_id: str, db_path: Path | None = None) -> bool:
existing_row["voice_persona_slug"],
existing_row["research_focus"],
existing_row["instructions"],
+ existing_row["pushback_model"],
existing_row["updated_at"],
),
)
@@ -343,6 +365,7 @@ def list_history(
voice_persona_slug=row["voice_persona_slug"],
research_focus=row["research_focus"],
instructions=row["instructions"],
+ pushback_model=row["pushback_model"],
created_at=row["created_at"],
)
)
@@ -373,6 +396,7 @@ def get_history_entry(
voice_persona_slug=row["voice_persona_slug"],
research_focus=row["research_focus"],
instructions=row["instructions"],
+ pushback_model=row["pushback_model"],
created_at=row["created_at"],
)
@@ -394,6 +418,7 @@ def rollback_to(
voice_persona_slug=entry.voice_persona_slug,
research_focus=entry.research_focus,
instructions=entry.instructions,
+ pushback_model=entry.pushback_model,
prompt_set=True,
model_set=True,
deep_set=True,
@@ -401,5 +426,6 @@ def rollback_to(
voice_persona_slug_set=True,
research_focus_set=True,
instructions_set=True,
+ pushback_model_set=True,
db_path=db_path,
)
diff --git a/packages/core/openexecutive/api/routes/agents.py b/packages/core/openexecutive/api/routes/agents.py
index fc26ff1d..f9204660 100644
--- a/packages/core/openexecutive/api/routes/agents.py
+++ b/packages/core/openexecutive/api/routes/agents.py
@@ -30,6 +30,7 @@ from openexecutive.agents.presets import (
writes_for,
)
from openexecutive.audit.usage import log_model_usage
+from openexecutive.orchestrator.pushback import PUSHBACK_OFF
logger = logging.getLogger(__name__)
@@ -92,6 +93,11 @@ class AgentDetail(BaseModel):
# Additional instructions appended after ``prompt`` (which stays the
# built-in prompt or its replacement, never the two joined).
instructions: str | None = None
+ # The Executive only: the model for one answer after pushback
+ # (orchestrator.pushback), and PUSHBACK_MODEL's. "off" or "" means
+ # answers stay on ``model``. null on the specialists.
+ pushback_model: str | None = None
+ pushback_model_default: str | None = None
# Additional instructions ride in every call to the agent (and in the
@@ -108,6 +114,8 @@ class AgentPatch(BaseModel):
voice_persona_slug: str | None = None
research_focus: str | None = None
instructions: str | None = Field(None, max_length=INSTRUCTIONS_MAX_CHARS)
+ # The Executive only: a model id, "off", or null to follow PUSHBACK_MODEL.
+ pushback_model: str | None = None
class AgentTestRequest(BaseModel):
@@ -242,6 +250,12 @@ class _ExecutiveDefaults:
return get_settings().default_model
+ @staticmethod
+ def pushback_model() -> str:
+ from openexecutive.config import get_settings
+
+ return (get_settings().pushback_model or "").strip()
+
@staticmethod
def prompt() -> str:
"""The built-in persona for this install's workspace mode, so the
@@ -294,7 +308,10 @@ def _build_executive_detail() -> AgentDetail:
overridden.append("voice_persona_slug")
if ov.instructions is not None:
overridden.append("instructions")
+ if ov.pushback_model is not None:
+ overridden.append("pushback_model")
role_default = _ExecutiveDefaults.role
+ pushback_default = _ExecutiveDefaults.pushback_model()
model_default = _ExecutiveDefaults.model()
prompt_default = _ExecutiveDefaults.prompt()
return AgentDetail(
@@ -317,6 +334,10 @@ def _build_executive_detail() -> AgentDetail:
updated_at=ov.updated_at if ov else None,
voice_persona_slug=ov.voice_persona_slug if ov else None,
instructions=ov.instructions if ov else None,
+ pushback_model=(
+ ov.pushback_model if ov and ov.pushback_model is not None else pushback_default
+ ),
+ pushback_model_default=pushback_default,
)
@@ -555,6 +576,19 @@ def patch_agent(agent_id: str, patch: AgentPatch) -> AgentDetail:
detail=f"Model {patch.model!r} is not in the allowed list",
)
+ if "pushback_model" in raw:
+ if agent_id != EXECUTIVE_ID:
+ raise HTTPException(
+ status_code=400, detail="Only the Executive has a pushback model"
+ )
+ if patch.pushback_model not in (None, PUSHBACK_OFF) and (
+ patch.pushback_model not in _allowed(agent_id)
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail=f"Model {patch.pushback_model!r} is not in the allowed list",
+ )
+
if "voice_persona_slug" in raw and patch.voice_persona_slug is not None:
from openexecutive.personas.loader import persona_exists
if not persona_exists(patch.voice_persona_slug):
@@ -584,6 +618,8 @@ def patch_agent(agent_id: str, patch: AgentPatch) -> AgentDetail:
voice_persona_slug_set="voice_persona_slug" in raw,
research_focus_set="research_focus" in raw,
instructions_set="instructions" in raw,
+ pushback_model=patch.pushback_model,
+ pushback_model_set="pushback_model" in raw,
)
return (
_build_executive_detail()
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index b141e0cb..aaa8ed45 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -5265,6 +5265,17 @@ chat:
debounces it and opens a message match with /?session=…&find=…, and
the chat starts on that message with previous/next and highlights
the words (CSS Custom Highlight API where the browser has it).
+ pushback_model: |
+ After pushback, a stronger model for one answer (orchestrator/pushback.py).
+ At turn start the Executive checks the message for pushback on the last
+ answer: a thumbs down on the last saved reply (or typed), words that say
+ it missed, the same ask again, or a claim_check row on the last reply.
+ Then this turn runs on the pushback model (Council Executive card
+ agent_overrides.pushback_model, else PUSHBACK_MODEL; empty or "off" =
+ off) and logs a pushback_model audit row; the next turn is back on the
+ normal model. No model call, fails open. Why: most misses were followed
+ by the person pushing back, and a stronger model on just those turns
+ costs far less than running every answer on it.
claim_check: |
Do what it says (orchestrator/claim_check.py). At the end of the
agent loop, a reply that uses a word able to claim a change (done,
diff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.json
index ce1ddbc4..ea44e9de 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>` (the shipped case studies, and under them the workspace's own lessons that match the call, `memory/lessons.py`), `<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. When to call it is spelled out in the persona's Domain Expertise section (\"Going deeper\") and in the tool's own description: any question that asks for judgment in a specialist's area (a decision, plan, analysis, negotiation, hire, contract term, pricing or fundraising move, board message, or a department's own targets and stance, since the specialist holds that department's memory) is consulted before the answer, several at once across areas; lookups in mail, calendar or documents, scheduling, status checks, routine drafting and questions about how the Executive works are answered without one. Chat eval scenarios hold this: `required_routing` names specialists the turn must consult and `no_routing: true` says it must consult none, and the runner fails a scenario that misses either (`evals.scenarios.routing_check`). Beside it the Executive carries two skill tools, `search_skills` and `load_skill` (skills are shown to users as **playbooks**, and every playbook belongs to a workflow: one that follows it, or its own Quick workflow). Chat finds and reads playbooks but never creates or changes one: work worth repeating is offered as a workflow through `draft_workflow`, with the method written into its steps, because workflows read playbooks at run time (approved scheduled ones included) and this loop also runs on inbound email and chat, so only a person 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, Quick ones included, 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 20 per turn; that turn's extraction pass then opens no second loop for the same owner. The owner is told once on their own channel when someone else assigns it, and the result's `notified` says how that went, so the Executive reports it rather than messaging them as well. 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, a channel whose adapter verified the sender itself (`Session.speaker_verified`, with the `caller_person_id` it resolved, never on a turn an email started), 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), each with what is remembered about them from the principal's own mail and meetings (`what_you_deal_with`, `topics`, `recent_activity`, from `people.contact_notes`) so the Executive can suggest who to ask, and their contact details (`details`: phones, links, address), both on that turn only — while `lookup_person` searches the team only. `ask_about_person` on one of the principal's contacts, on the principal's own turn, returns that contact note instead of peer memory (contacts never chat, so peer memory has nothing on them); otherwise it reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. A teammate's own mail with the Executive is theirs the same way: every mailbox call the model makes through the MCP gateway (Gmail or Outlook, by `call_tool`, from a script, or a workflow step run from chat) passes through `orchestrator.teammate_mail`. A search excludes every other teammate's address server-side, except on mail the reader is also on, and is filtered again entry by entry; any other call that names a message or thread (read, attachment, reply, forward, label) must use an id a filtered search returned to the same reader in this conversation (`Session.mail_ids_seen`) or the inbound email the turn answers; reads are filtered message by message, so a message naming another teammate is left out unless the reader is in its From / To / Cc; a reply that would quote such a thread, or an Outlook forward, reply or attachment read of such a message, is refused; and a conversation in which a teammate other than the principal was shown their own mail becomes theirs alone, as Act as me's do. Outside mail and the reader's own are untouched; an email turn reads as its sender only when Gmail authenticated it, and any other unverified reader sees no teammate's mail, a background run the model drives reads as the principal and a workflow step outside any session as nobody, an Outlook inbox rule that forwards or names another teammate is refused, and the poller and the brief, which read the mailbox themselves, are unaffected. Their own chats are theirs too: every audit row of a teammate's verified turn is theirs (`people_tools.teammate_turn_owner`, see Audit; the principal sees the actions, never the words), and a teammate's web chat or DM opens for them alone (`chat._session_access`), the principal included. 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 / OneDrive 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`: `load_mcp_server`, `list_saved_tools`, `run_python_job` and `run_script` — 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. A send or edit on a team member's turn also meets their department's authority first (`orchestrator.department_gate`, see Org), and so does one on a turn whose speaker is on no People entry: a signed-in web caller or a chat-channel sender, which in practice is Google Chat, since Slack, Telegram and Discord turn unmatched senders away. Google Chat names a matched sender to the gate alone (`gate_sender_person_id`), so the principal there is not held. Email turns are left to the mailbox's own gates. *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\n**Outside content** (`orchestrator.outside_content`). Once a turn has read text from outside the team (any gateway read, an attachment, a web search result, a synced Drive, OneDrive, Confluence or Notion excerpt, `read_document`, research, or an extension tool registered `reads_outside`), the rest of that turn refuses what the Act as me lockdown refuses, every `upsert_person` but a contact the speaker named in this message at an address they typed or one that sent the mail read (`lockdown.speaker_named_contact`; never on a turn answering mail from someone not in People, and a refused one points to an `add_contact` card), and every `call_tool` but a read: no mail, Docs, Sheets, Drive or calendar write. The company's own Drive is not outside: a Google read of one file, Doc, Sheet, deck or folder by id (`company_read_item`) is looked up first (`vet_reads`, once per id a turn), and when that item is owned by someone at the company, or kept on a shared drive only the company organizes, and shared with nobody outside it (`mcp_gateway._company_item`), the read marks the turn as a company read (`COMPANY`) instead. That still holds everything else, since anyone who can edit the file wrote its words, but when every read so far was of the company's own items, a rename or move (`update_drive_file` with only `file_id`, `name`, `add_parents`, `remove_parents`) goes through, so the turn can file what it read. Searches, mail, calendar and forms mark it as usual. A refused rename or move the person asked for can go on a `drive_files` approval card instead. A round that reads also holds that round's other such calls; the read itself runs. Scripts are checked call by call. The offered tools never change, so the cached prefix stays the same, and the hold ends with the turn. Mail from someone not in People (a contact or a stranger) counts as outside content from the start of its turn (`Session.sender_off_team`), so the whole turn is held, with no direct messages or watchlist removals either; it can still raise an alert, private to the principal, which is how that mail reaches them. Someone added to People in a turn (or given a new address or chat account) is not emailed, messaged, invited or shared with until the next one. What a turn held is remembered for the conversation's next turn (`note_held`, in process, for an hour). It is kept per conversation and speaker. When that speaker's next message is a go (a short yes such as \"go\" or \"yes, do it\", or one opening with go, go ahead, do it or proceed as its own clause: `GO_RE`), the first round that reads has its reads refused once (`defers_read`, with an error that names no tool and asks for nothing new), so the steps the person just approved run before a new read holds them again; from the next round reads run as usual. It runs only what the model calls in that turn, under every usual check. A shared chat, and a turn answering mail from someone not in People, remember nothing. In the web chat the go is a tap: while it waits, the reply carries **Approve** and **Not now** buttons naming the held steps in plain words (`pending_held`, `step_words`: only names it knows; any other gateway tool shows its app's generic label, since the model's tool name can be steered by what it read), and Approve sends \"Go ahead\" as the person's own next message. The refusal on a web turn (`approve_hint`, set from `Session.from_web_chat`) tells the model to point them at Approve rather than ask them to say go; other surfaces still ask for a typed go.\n\nHow much a read holds is the owner's **safety level**, \"When should I check with you?\" (`orchestrator.outside_mode`, one row in `outside_content_mode` holding the company's level and any channel set apart from it, changed only by the principal through `GET`/`PUT /executive/outside-content` on Settings → Your Executive), fixed per turn in `begin_turn` (`TurnOutside.mode`) from the turn's channel (`channel_of`: `web` for the web chat, else the session's `origin_channel` when it is one of `outside_mode.CHANNELS`; any other surface follows the company's level). Every outside read is checked at every level by `orchestrator.content_scan` (it flags only text written to an assistant or a system, never one person asking another to forward or share; a search of the owner's own mail is checked entry by entry with `scan_list`, so a flagged thread's subject and sender name are left out and the rest passes, and a thread the Executive itself sent (its own address, authenticated by Gmail or Exchange, under a subject of its own, not a reply's or forward's in any common language) is not checked; the flag notice never asks the model to mention it, and each flag is logged as `content_flagged`): one small-model call (the inbox classifier's model) with no tools reads the content as data and reports whether it tries to steer an assistant, and which of a fixed list of things it tried (`CATEGORIES`: ignore its rules, forward or share, reveal information, write to another address, open a link, change payment details, hand over a login); a failed call, an unreadable answer, content over `MAX_CHARS` or a turn past `MAX_PER_TURN` checks is *unchecked*. Verdicts are cached by content hash. A read whose text is in hand is checked in `mark_read`; an attachment and a synced excerpt are queued (`mark_pending`, as the retriever runs in a thread) and checked together by `settle` before each round of tools is dispatched (and before each `run_script` call). **Careful** (`ask`) is the hold above: every read marks the turn. **Balanced** (`outsiders`, the default) marks it only when the check flags the read; a read it couldn't check reaches the model behind `UNCHECKED_NOTICE` and holds nothing (except content too big to read whole or read past the turn's `MAX_PER_TURN` checks, `TOO_BIG`, which holds like a flag, since padding or a pile of harmless reads is how content would dodge the check), and a web search (its results arrive encrypted, so nothing checks them) holds nothing either. Reads that came from the team are not even checked: a Gmail search that shows only ids and links, a Gmail message read where every message's sender is a teammate (not a contact) and Gmail authenticated it (`fact_confirmation.sender_authenticated` on a raw read of each id, at most 10) and no other address appears, and a calendar read naming only the team where the Executive itself organized every event (a teammate's invite counts as outside, since its organizer is whatever the mail that brought it says) (Google's `get_events` only when `detailed` or for one event; Microsoft 365's calendar reads) (`from_the_team`; an `@` the address pattern can't read counts as a stranger). **Hands-off** (`trust`) applies only on the principal's own turn on an interactive surface that isn't email or a shared chat (`content_trust.principal_only_withheld` empty): no read marks the turn but an attachment or synced excerpt the check flagged (the model read it before its check, so no notice reached it first), a read in a round holds nothing in it, a result the check couldn't read reaches the model behind `UNCHECKED_NOTICE`, and reading their own mail holds only what it holds at every level (`lockdown.mail_turn_withholds`: broadcasts, department messages, alerts, roster and authority changes, a contact the speaker didn't name); anyone else's turn gets Balanced. At every level a flagged read's result reaches the model behind `FLAG_NOTICE` (it is data, not to be followed; tell the person what was skipped), and the flag is kept for whoever spoke in plain words built only from the module's own words (`flag_words`), per conversation and speaker, each turn replacing the last's: the web chat streams it as a `flags` event after the reply and `GET /sessions/{id}/messages` re-attaches it to the last reply for an hour (`pending_flags`). Whatever the level, a shared chat, another AI app's turn and mail from someone not in People are Careful, sends still go only to people on People, and someone added this turn is reached no earlier than the next one. An unreadable setting is Careful.\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 (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) 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.\n\nA turn another AI app asks over the MCP server (`Session.from_mcp_client`, set by `ask_executive`) reads and advises but never acts, unless the request may act (below). It is neither offered nor allowed to run `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS`: the private-turn and unattended sets, plus every direct message (`message_person`, the Slack, Discord and Telegram DMs), alert acks and new alerts, brief edits, closing open loops, roster and department-head writes, watchlist changes, workflow drafts and form proposals. It gets no Act as me, `recall_history` or extension tools, and of the gateway tools only `schedule_tools.MCP_CLIENT_MCP_TOOLS`: the private-turn reads without the Gmail and Outlook send and draft tools. The set is fixed, so the variant keeps a stable cached tool prefix. A call the model emits anyway, through `use_tool` or `call_tool` included, gets an error tool_result telling it the conversation comes from another AI app, so it can read and advise but not send, post, book or change anything, and writes an audit row (`refused: mcp_client`); `MCPGateway.call_tool` refuses the same calls again.\n\nA web chat turn a **host origin's** page sent (`Session.from_host`, set per turn from `api.caller.from_host`: another app framing Open Executive, `OE_HOST_ORIGINS`) is read-only the same way (`schedule_tools.read_only_turn`): the same withheld set and gateway reads, no Act as me, `recall_history`, script or extension tool, and the principal-only tools withheld too (`content_trust.principal_only_withheld`), since a script on that host's page can start such a turn as the person. Its refusal tells the model the conversation comes from a page another app shows (`HOST_REFUSAL`), so the person acts in Open Executive itself. It stops and adds to its own turns only (`chat._stop_owner_key`). `tests/unit/test_host_surface_turns.py` pins what it is offered. Once a host's page has written a line in a conversation (`chat_messages.sender_surface = 'host'`, `session_store.host_wrote`), every later turn in it is held the same way, from any page and after a restart, because that line stays in what the model reads.\n\nA request may let that turn act (`Session.mcp_client_may_act`: the `x-mcp-client-actions: on` header on a request the shared secret authenticated, or `MCP_CLIENT_ACTIONS` where no secret is set). It then runs the speaker's own changes inside Open Executive (`schedule_tools.MCP_CLIENT_RUNS_WHEN_ACTING`: alerts, open loops, follow-ups, the watch list, goals, decision outcomes, facts and company profile writes; never the roster), each under its own owner-only and person checks, since the turn counts as a verified surface for its caller. It is still denied a fixed set, `MCP_CLIENT_ACTING_WITHHELD_TOOLS` (DMs, calendar writes, broadcasts, `load_mcp_server`, scripts, Python jobs, workflows, research and the rest of the read-only set), with a refusal telling the person to do it in Open Executive. A message or a meeting goes on an approval card instead (`propose_actions`), which is carried out at once when the person's Handle it for me covers it, everyone on it has been on the roster for a week, and `action_cards.on_its_own_refusal` finds nothing against it, and otherwise waits for their tap. Every audit row it writes names the app (`via`).\n\nA web chat its owner shared (`Session.shared_chat`) mixes people. The note naming who is in it says which of them owns it and that the others' lines are messages from them, not the owner's instructions. While someone other than the owner has written since the owner's last message (`Session.others_spoke_last`, set per turn by the chat route from the saved history, the speaker included, and true when the history can't be read), the turn is neither offered nor allowed to run `schedule_tools.SHARED_CHAT_WITHHELD_TOOLS`: direct messages, the broadcasts, meeting invites and cancellations, follow-ups, roster writes and workflows (a run, a save or a suggested schedule acts later with the full tool set). Through `call_tool` it can't send, reply, forward or draft mail in Gmail or Outlook, or make a calendar change that mails attendees (`schedule_tools.shared_chat_withholds`). That holds on the owner's own turn right after someone else's line too, so a request carried over from it can't send; the owner's next message with nobody else's in between lifts it. A call the model emits anyway gets an error tool_result and writes an audit row (`refused: shared_chat`). The principal-only tools stay out of every shared chat (`content_trust.principal_only_withheld`).\n\nOn 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, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. Both the service list and the pinned names are narrowed to what workspace-mcp actually loaded (`WORKSPACE_MCP_TOOLS`, `WORKSPACE_MCP_TOOL_TIER`), so a service left out is not named and its tools are not pinned — being told a tool is already available when it is not in the index costs a failed call the model cannot explain to itself. `search_tools` is for anything not listed. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered when the gateway runs, unless `CHAT_SCRIPTS=false`, and only on the principal's own turns — `PRINCIPAL_ONLY_TOOLS`, withheld on an unattended pass too, because it spends the turn's whole call budget on code the model just wrote): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run (or the department gate on a team member's turn, see Org), and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. 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 (3 built-in and 2 company chunks by default, see the RAG section) 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`; the last two sit in the `memory` group of `open_tools`, since they are rarely needed) 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-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. 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-5`, `claude-sonnet-5`, `claude-haiku-5-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-5-5`, else `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**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). 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, from what they wrote plus any attached files and website pages, which reach it as untrusted content it may draw facts from but never take instructions from), `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\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by the picker in Settings → Executive (setup doesn't ask), which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\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**Goals without departments.** The goal tools (`orchestrator.department_tools`) no longer assume a department: `list_department_goals` with no `department_slug` lists every goal with its owner and department, `update_department_goal` names a goal by `goal_id` alone, and `create_goal` takes an optional `area` and `owner_person_id` (a team member). The org block renders goals with no department with their `goal_id`, and their action chips link to `/goals` (see Org).\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\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — and `my_calendar` their own calendar while Read my calendar is on, capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). Beside them, `save_my_email_attachment` copies one attached file, when the speaker asked in their own words, into a fixed folder of the Executive's own Drive or OneDrive and shares it with them alone, every call built in codeOne 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 mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). 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, or a team member once the owner lets them, 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. From the round that calls it until the turn ends, the dispatch guard refuses only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. That is Careful; on Balanced the rest lifts once every mail read so far was checked clean by `content_scan` (`outside_content.check_mail_read`, the round that reads still holding), and a read inside a script or workflow, flagged, too big or unchecked keeps it (`lockdown.mail_lock_holds`). A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), 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)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**). A meeting `create_calendar_event` proposes works the same way when the person chatting is the one who approves it: its chip carries the `decision_id` and the chat shows the meeting card (Approve, Edit, Dismiss) under the reply, while the briefing keeps it too. A tool result held for someone else's approval (`waiting_for_approval`, the department gate) gets a *Waiting for approval* chip, never a done one.\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). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). 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\n**Extensions** (`orchestrator.extensions`). An install can add chat tools and kinds of document without changing this code. `OPENEXECUTIVE_EXTENSIONS` names Python modules. The first turn, or the first Documents read, imports each one and calls its `register()`. A module that fails is logged and skipped. `register_tool` takes an `ExtraTool`: a definition, an async handler, an optional `tool_groups` group (new or existing) and an optional chip. It refuses a name the loop already knows (`executive.builtin_tool_names`). An extension tool is never in `_ALL_SKILL_TOOLS`, so reflection, research and the synthesis never see it. The chat loop adds it per turn, like the Act as me tools, but never on an unattended run, a turn private to the principal or to a speaker who isn't on the People list (mail from a stranger), and only where its own `offered(session)` says. A tool registered `known_caller=False` is the one exception to the People-list rule: it is asked on a turn with no verified caller too (a surface of the extension's own that names its user without proving who is speaking), so `register_tool` requires it to have an `offered` that checks who is asking; it is still never offered on an unattended, private, AI-app or replay turn. That predicate depends only on the kind of turn, so each kind of turn keeps one cached tool list. Act as me's lockdown refuses it once the turn has read the owner's mail, because it is unclassified and the lockdown fails closed, unless it was registered with `after_mail_read=True`: a tool that only reads the install's own data and carries nothing the model wrote anywhere outside. Its chip goes through `action_chips.summarize_action`, which applies the same no-chip rules for an error or refusal and keeps a link to a path inside the app. A `waiting_for_approval` result is the tool's own chip's to describe, never core's generic \"Waiting for approval\": the department gate never holds an extension tool. A tool may also name the chat's activity line while it runs (`activity_label`) and keep its dispatch audit row private (`private_row`: its input or result quotes the speaker's own data). `register_collection` adds a kind of document: a drafted artifact tagged `collection:<name>` carries that collection on its record. The Documents page gives each collection its own filter. The collection's `on_change` hears about archive, restore and delete before they happen; if it raises, the change does not happen. `draft_artifact(supersedes=…)` refuses a collection's document. The alert pipeline strips `collection:` tags, so only the extension's own code files a document in its collection. A module that fails partway through `register()` leaves nothing registered. A tool registered with `workflow=True` is also offered to workflow action steps as `oe__<name>` (see Workflows); `read_only=True` marks one that only reads. A step runs with nobody in the turn, so `offered` isn't asked: `extensions.in_workflow_step(name)` is True for that tool, during its call only, and the handler decides what an unattended call may do.\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. For questions about the product itself, the always-offered `read_user_guide` tool (`orchestrator/guide_tools.py`) returns any `guide/prebuilt/<id>.json` section; its description lists the section ids, fixed at import, so it never changes the cached tools prefix.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Personal as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve with a **Do this on its own next time** tick (`allow`), **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.\n\n**AI disclosure.** Nothing the Executive sends to people outside the web chat goes without saying it is an AI: plain code adds the line in the MCP gateway (mail) and at each chat send (Slack, Telegram, Discord, Google Chat replies, its DMs and room posts), never the prompt, so the persona and the cached system blocks are unchanged and a reply the model writes can't drop it. Replies the inbox watcher writes as a person carry their own line by that person's switches. See Integrations → **AI disclosure** and Act as me → **AI line on replies**.\n\n**App control from chat** (`orchestrator/app_control.py`, catalog in `orchestrator/app_control_catalog.py`). Three tools in the `app` tool group let the Executive do what the app's buttons do when the person asks (\"pin this\", \"delete that chat\", \"turn off Handle it for me\"): `find_in_app(kind, query)` lists what the speaker may change (their chats, topics, documents, workflow runs, settings; files, memory, departments, skills and workflows for the principal), `do_in_app(action, id, value)` does one action (`id: \"this\"` is the chat they are in), and `open_in_app(screen)` returns an in-app link. Each action calls the API route its button calls, as a function, with a request naming the turn's verified speaker (`correction_tools._speaker`; an email or unattended turn gets a refusal), so the route's own checks decide what this person may do. Actions whose route checks nothing about the caller (their page is the principal's) are `principal_only`. Deletes, shares, turning on Act as me, Handle it for me or Take the lead, removing a Take the lead rule, clearing every card and approving a workflow's waiting step never run in the turn: they become an `app_action` decision card, private to the speaker, shown under the reply; the tap runs the action with the tapper's own request through `POST /decisions/{id}/approve` (claimed once; a card older than a day is turned down). After a turn reads outside text or the speaker's mail, every action becomes a card. The tools are withheld from unattended and AI-app turns, and `do_in_app` from a shared chat someone else spoke in. Snoozing a card uses `ack_alert`'s trust rule: only ids the server showed or found this turn. Extensions add kinds, actions and screens with `register_kind` / `register_action` / `register_screen` at startup. The person's notes stay with `recall_history`; account, sign-in and billing stay on their screens.",
+ "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>` (the shipped case studies, and under them the workspace's own lessons that match the call, `memory/lessons.py`), `<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. When to call it is spelled out in the persona's Domain Expertise section (\"Going deeper\") and in the tool's own description: any question that asks for judgment in a specialist's area (a decision, plan, analysis, negotiation, hire, contract term, pricing or fundraising move, board message, or a department's own targets and stance, since the specialist holds that department's memory) is consulted before the answer, several at once across areas; lookups in mail, calendar or documents, scheduling, status checks, routine drafting and questions about how the Executive works are answered without one. Chat eval scenarios hold this: `required_routing` names specialists the turn must consult and `no_routing: true` says it must consult none, and the runner fails a scenario that misses either (`evals.scenarios.routing_check`). Beside it the Executive carries two skill tools, `search_skills` and `load_skill` (skills are shown to users as **playbooks**, and every playbook belongs to a workflow: one that follows it, or its own Quick workflow). Chat finds and reads playbooks but never creates or changes one: work worth repeating is offered as a workflow through `draft_workflow`, with the method written into its steps, because workflows read playbooks at run time (approved scheduled ones included) and this loop also runs on inbound email and chat, so only a person 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, Quick ones included, 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 20 per turn; that turn's extraction pass then opens no second loop for the same owner. The owner is told once on their own channel when someone else assigns it, and the result's `notified` says how that went, so the Executive reports it rather than messaging them as well. 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, a channel whose adapter verified the sender itself (`Session.speaker_verified`, with the `caller_person_id` it resolved, never on a turn an email started), 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), each with what is remembered about them from the principal's own mail and meetings (`what_you_deal_with`, `topics`, `recent_activity`, from `people.contact_notes`) so the Executive can suggest who to ask, and their contact details (`details`: phones, links, address), both on that turn only — while `lookup_person` searches the team only. `ask_about_person` on one of the principal's contacts, on the principal's own turn, returns that contact note instead of peer memory (contacts never chat, so peer memory has nothing on them); otherwise it reads a person's peer memory fully only on their own verified turn; anyone else's answers only to a verified principal or teammate, and only when that person turned on \"Share my work style with the team\", framed to how they work and never their view of a colleague, and otherwise returns the same \"hasn't chosen to share\" result whether or not anything is known. A teammate's own mail with the Executive is theirs the same way: every mailbox call the model makes through the MCP gateway (Gmail or Outlook, by `call_tool`, from a script, or a workflow step run from chat) passes through `orchestrator.teammate_mail`. A search excludes every other teammate's address server-side, except on mail the reader is also on, and is filtered again entry by entry; any other call that names a message or thread (read, attachment, reply, forward, label) must use an id a filtered search returned to the same reader in this conversation (`Session.mail_ids_seen`) or the inbound email the turn answers; reads are filtered message by message, so a message naming another teammate is left out unless the reader is in its From / To / Cc; a reply that would quote such a thread, or an Outlook forward, reply or attachment read of such a message, is refused; and a conversation in which a teammate other than the principal was shown their own mail becomes theirs alone, as Act as me's do. Outside mail and the reader's own are untouched; an email turn reads as its sender only when Gmail authenticated it, and any other unverified reader sees no teammate's mail, a background run the model drives reads as the principal and a workflow step outside any session as nobody, an Outlook inbox rule that forwards or names another teammate is refused, and the poller and the brief, which read the mailbox themselves, are unaffected. Their own chats are theirs too: every audit row of a teammate's verified turn is theirs (`people_tools.teammate_turn_owner`, see Audit; the principal sees the actions, never the words), and a teammate's web chat or DM opens for them alone (`chat._session_access`), the principal included. 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 / OneDrive 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`: `load_mcp_server`, `list_saved_tools`, `run_python_job` and `run_script` — 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. A send or edit on a team member's turn also meets their department's authority first (`orchestrator.department_gate`, see Org), and so does one on a turn whose speaker is on no People entry: a signed-in web caller or a chat-channel sender, which in practice is Google Chat, since Slack, Telegram and Discord turn unmatched senders away. Google Chat names a matched sender to the gate alone (`gate_sender_person_id`), so the principal there is not held. Email turns are left to the mailbox's own gates. *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\n**Outside content** (`orchestrator.outside_content`). Once a turn has read text from outside the team (any gateway read, an attachment, a web search result, a synced Drive, OneDrive, Confluence or Notion excerpt, `read_document`, research, or an extension tool registered `reads_outside`), the rest of that turn refuses what the Act as me lockdown refuses, every `upsert_person` but a contact the speaker named in this message at an address they typed or one that sent the mail read (`lockdown.speaker_named_contact`; never on a turn answering mail from someone not in People, and a refused one points to an `add_contact` card), and every `call_tool` but a read: no mail, Docs, Sheets, Drive or calendar write. The company's own Drive is not outside: a Google read of one file, Doc, Sheet, deck or folder by id (`company_read_item`) is looked up first (`vet_reads`, once per id a turn), and when that item is owned by someone at the company, or kept on a shared drive only the company organizes, and shared with nobody outside it (`mcp_gateway._company_item`), the read marks the turn as a company read (`COMPANY`) instead. That still holds everything else, since anyone who can edit the file wrote its words, but when every read so far was of the company's own items, a rename or move (`update_drive_file` with only `file_id`, `name`, `add_parents`, `remove_parents`) goes through, so the turn can file what it read. Searches, mail, calendar and forms mark it as usual. A refused rename or move the person asked for can go on a `drive_files` approval card instead. A round that reads also holds that round's other such calls; the read itself runs. Scripts are checked call by call. The offered tools never change, so the cached prefix stays the same, and the hold ends with the turn. Mail from someone not in People (a contact or a stranger) counts as outside content from the start of its turn (`Session.sender_off_team`), so the whole turn is held, with no direct messages or watchlist removals either; it can still raise an alert, private to the principal, which is how that mail reaches them. Someone added to People in a turn (or given a new address or chat account) is not emailed, messaged, invited or shared with until the next one. What a turn held is remembered for the conversation's next turn (`note_held`, in process, for an hour). It is kept per conversation and speaker. When that speaker's next message is a go (a short yes such as \"go\" or \"yes, do it\", or one opening with go, go ahead, do it or proceed as its own clause: `GO_RE`), the first round that reads has its reads refused once (`defers_read`, with an error that names no tool and asks for nothing new), so the steps the person just approved run before a new read holds them again; from the next round reads run as usual. It runs only what the model calls in that turn, under every usual check. A shared chat, and a turn answering mail from someone not in People, remember nothing. In the web chat the go is a tap: while it waits, the reply carries **Approve** and **Not now** buttons naming the held steps in plain words (`pending_held`, `step_words`: only names it knows; any other gateway tool shows its app's generic label, since the model's tool name can be steered by what it read), and Approve sends \"Go ahead\" as the person's own next message. The refusal on a web turn (`approve_hint`, set from `Session.from_web_chat`) tells the model to point them at Approve rather than ask them to say go; other surfaces still ask for a typed go.\n\nHow much a read holds is the owner's **safety level**, \"When should I check with you?\" (`orchestrator.outside_mode`, one row in `outside_content_mode` holding the company's level and any channel set apart from it, changed only by the principal through `GET`/`PUT /executive/outside-content` on Settings → Your Executive), fixed per turn in `begin_turn` (`TurnOutside.mode`) from the turn's channel (`channel_of`: `web` for the web chat, else the session's `origin_channel` when it is one of `outside_mode.CHANNELS`; any other surface follows the company's level). Every outside read is checked at every level by `orchestrator.content_scan` (it flags only text written to an assistant or a system, never one person asking another to forward or share; a search of the owner's own mail is checked entry by entry with `scan_list`, so a flagged thread's subject and sender name are left out and the rest passes, and a thread the Executive itself sent (its own address, authenticated by Gmail or Exchange, under a subject of its own, not a reply's or forward's in any common language) is not checked; the flag notice never asks the model to mention it, and each flag is logged as `content_flagged`): one small-model call (the inbox classifier's model) with no tools reads the content as data and reports whether it tries to steer an assistant, and which of a fixed list of things it tried (`CATEGORIES`: ignore its rules, forward or share, reveal information, write to another address, open a link, change payment details, hand over a login); a failed call, an unreadable answer, content over `MAX_CHARS` or a turn past `MAX_PER_TURN` checks is *unchecked*. Verdicts are cached by content hash. A read whose text is in hand is checked in `mark_read`; an attachment and a synced excerpt are queued (`mark_pending`, as the retriever runs in a thread) and checked together by `settle` before each round of tools is dispatched (and before each `run_script` call). **Careful** (`ask`) is the hold above: every read marks the turn. **Balanced** (`outsiders`, the default) marks it only when the check flags the read; a read it couldn't check reaches the model behind `UNCHECKED_NOTICE` and holds nothing (except content too big to read whole or read past the turn's `MAX_PER_TURN` checks, `TOO_BIG`, which holds like a flag, since padding or a pile of harmless reads is how content would dodge the check), and a web search (its results arrive encrypted, so nothing checks them) holds nothing either. Reads that came from the team are not even checked: a Gmail search that shows only ids and links, a Gmail message read where every message's sender is a teammate (not a contact) and Gmail authenticated it (`fact_confirmation.sender_authenticated` on a raw read of each id, at most 10) and no other address appears, and a calendar read naming only the team where the Executive itself organized every event (a teammate's invite counts as outside, since its organizer is whatever the mail that brought it says) (Google's `get_events` only when `detailed` or for one event; Microsoft 365's calendar reads) (`from_the_team`; an `@` the address pattern can't read counts as a stranger). **Hands-off** (`trust`) applies only on the principal's own turn on an interactive surface that isn't email or a shared chat (`content_trust.principal_only_withheld` empty): no read marks the turn but an attachment or synced excerpt the check flagged (the model read it before its check, so no notice reached it first), a read in a round holds nothing in it, a result the check couldn't read reaches the model behind `UNCHECKED_NOTICE`, and reading their own mail holds only what it holds at every level (`lockdown.mail_turn_withholds`: broadcasts, department messages, alerts, roster and authority changes, a contact the speaker didn't name); anyone else's turn gets Balanced. At every level a flagged read's result reaches the model behind `FLAG_NOTICE` (it is data, not to be followed; tell the person what was skipped), and the flag is kept for whoever spoke in plain words built only from the module's own words (`flag_words`), per conversation and speaker, each turn replacing the last's: the web chat streams it as a `flags` event after the reply and `GET /sessions/{id}/messages` re-attaches it to the last reply for an hour (`pending_flags`). Whatever the level, a shared chat, another AI app's turn and mail from someone not in People are Careful, sends still go only to people on People, and someone added this turn is reached no earlier than the next one. An unreadable setting is Careful.\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 (mail, calendar, and Drive, Docs and Sheets search and file reads, with their Microsoft 365 twins; OneDrive's `download-bytes` only for a file's content) 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.\n\nA turn another AI app asks over the MCP server (`Session.from_mcp_client`, set by `ask_executive`) reads and advises but never acts, unless the request may act (below). It is neither offered nor allowed to run `schedule_tools.MCP_CLIENT_WITHHELD_TOOLS`: the private-turn and unattended sets, plus every direct message (`message_person`, the Slack, Discord and Telegram DMs), alert acks and new alerts, brief edits, closing open loops, roster and department-head writes, watchlist changes, workflow drafts and form proposals. It gets no Act as me, `recall_history` or extension tools, and of the gateway tools only `schedule_tools.MCP_CLIENT_MCP_TOOLS`: the private-turn reads without the Gmail and Outlook send and draft tools. The set is fixed, so the variant keeps a stable cached tool prefix. A call the model emits anyway, through `use_tool` or `call_tool` included, gets an error tool_result telling it the conversation comes from another AI app, so it can read and advise but not send, post, book or change anything, and writes an audit row (`refused: mcp_client`); `MCPGateway.call_tool` refuses the same calls again.\n\nA web chat turn a **host origin's** page sent (`Session.from_host`, set per turn from `api.caller.from_host`: another app framing Open Executive, `OE_HOST_ORIGINS`) is read-only the same way (`schedule_tools.read_only_turn`): the same withheld set and gateway reads, no Act as me, `recall_history`, script or extension tool, and the principal-only tools withheld too (`content_trust.principal_only_withheld`), since a script on that host's page can start such a turn as the person. Its refusal tells the model the conversation comes from a page another app shows (`HOST_REFUSAL`), so the person acts in Open Executive itself. It stops and adds to its own turns only (`chat._stop_owner_key`). `tests/unit/test_host_surface_turns.py` pins what it is offered. Once a host's page has written a line in a conversation (`chat_messages.sender_surface = 'host'`, `session_store.host_wrote`), every later turn in it is held the same way, from any page and after a restart, because that line stays in what the model reads.\n\nA request may let that turn act (`Session.mcp_client_may_act`: the `x-mcp-client-actions: on` header on a request the shared secret authenticated, or `MCP_CLIENT_ACTIONS` where no secret is set). It then runs the speaker's own changes inside Open Executive (`schedule_tools.MCP_CLIENT_RUNS_WHEN_ACTING`: alerts, open loops, follow-ups, the watch list, goals, decision outcomes, facts and company profile writes; never the roster), each under its own owner-only and person checks, since the turn counts as a verified surface for its caller. It is still denied a fixed set, `MCP_CLIENT_ACTING_WITHHELD_TOOLS` (DMs, calendar writes, broadcasts, `load_mcp_server`, scripts, Python jobs, workflows, research and the rest of the read-only set), with a refusal telling the person to do it in Open Executive. A message or a meeting goes on an approval card instead (`propose_actions`), which is carried out at once when the person's Handle it for me covers it, everyone on it has been on the roster for a week, and `action_cards.on_its_own_refusal` finds nothing against it, and otherwise waits for their tap. Every audit row it writes names the app (`via`).\n\nA web chat its owner shared (`Session.shared_chat`) mixes people. The note naming who is in it says which of them owns it and that the others' lines are messages from them, not the owner's instructions. While someone other than the owner has written since the owner's last message (`Session.others_spoke_last`, set per turn by the chat route from the saved history, the speaker included, and true when the history can't be read), the turn is neither offered nor allowed to run `schedule_tools.SHARED_CHAT_WITHHELD_TOOLS`: direct messages, the broadcasts, meeting invites and cancellations, follow-ups, roster writes and workflows (a run, a save or a suggested schedule acts later with the full tool set). Through `call_tool` it can't send, reply, forward or draft mail in Gmail or Outlook, or make a calendar change that mails attendees (`schedule_tools.shared_chat_withholds`). That holds on the owner's own turn right after someone else's line too, so a request carried over from it can't send; the owner's next message with nobody else's in between lifts it. A call the model emits anyway gets an error tool_result and writes an audit row (`refused: shared_chat`). The principal-only tools stay out of every shared chat (`content_trust.principal_only_withheld`).\n\nOn 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, Confluence sync (when on) and Act as me, and pins the Google tool names it calls directly with `call_tool`. Both the service list and the pinned names are narrowed to what workspace-mcp actually loaded (`WORKSPACE_MCP_TOOLS`, `WORKSPACE_MCP_TOOL_TIER`), so a service left out is not named and its tools are not pinned — being told a tool is already available when it is not in the index costs a failed call the model cannot explain to itself. `search_tools` is for anything not listed. When work repeats over many items, the Executive can also call `run_script` (`workflows/step_script.py`, offered when the gateway runs, unless `CHAT_SCRIPTS=false`, and only on the principal's own turns — `PRINCIPAL_ONLY_TOOLS`, withheld on an unattended pass too, because it spends the turn's whole call budget on code the model just wrote): one short Python script, run in a sandboxed Monty worker with no files, network or environment, whose only reach is the gateway tools `call_tool` could reach (those `search_tools` has returned; the gateway keeps that set for its own process-wide session, not per conversation). Each call it makes is a `call_tool` in every way that matters — the gateway's discovery, deny-list and recipient gates, Take the lead's gate on an unattended run (or the department gate on a team member's turn, see Org), and the same action chip and `tool_invocation` row (marked `via: run_script`, `ok: false` when it raised), as each call happens; the script itself gets a `kind: script` row with its source and result. Its wall clock is half the turn's deadline, so a long script ends with the list of calls it made rather than being cut off with the turn, and a stopped turn closes it and its worker. A turn private to the principal is not offered it, and the Act as me lockdown withholds it whole. Besides gateway tools, a chat script may call a fixed list of the Executive's own tools (`step_script.CHAT_OWN_TOOLS`: reads, alerts, open loops, goals, the watch list, follow-ups, `message_person`, `upsert_person` — nothing that broadcasts, books calendars, edits memory or skills, or starts workflows or research), each only when the turn is offered it and through the turn's own handler (Take the lead's gate included), with the same chip and a `kind: skill`, `via: run_script` audit row. A direct call needs a `tool_use` each, so a turn's scripts share a budget instead: `CHAT_SCRIPT_MAX_CALLS` (default 200) calls in all, and per-turn caps on own tools that could otherwise act in bulk (`CHAT_OWN_TOOL_CAPS`: `message_person` 10 — messaging the whole roster would be a broadcast — `upsert_person` 25, `create_alert` 50); a refused call tells the model to say what is left. A call stopped mid-flight by the script's clock or the turn still gets a `cancelled` audit row, since it may have run. Because every round re-reads the conversation, the loop also nudges at the moment of choice: after a round whose results include a list of five or more items (`step_script.lists_many`), with `run_script` on offer and not used that round, it adds the constant `FANOUT_HINT` as a text block in that round's user message (never a cached block), once a turn, pointing the per-item work at one built tool. For library work on files (PDFs, spreadsheets, charts, images) the chat also has `run_python_job` (see Workflows → Python jobs): Python with a fixed library set in a Deno-isolated WebAssembly sandbox, fed Knowledge files by name, the message's own attachments as sent, or text it already holds, and able to keep a job that worked as a Custom tool, with result files linked for the principal to download; it is offered only on the principal's own turns and only where the sandbox is installed (not offered otherwise, so the tool prefix stays fixed per process). Agent Activity shows each run as one \"Built tool\" card (debug event `script_run`: ok, the calls it made, how many, how long, and the kept or reused tool's name). The persona's tool-building section is present only when chat scripts can actually run (the setting and Monty installed). `TOOL_BUILDING_ADDENDUM` in the cached persona tells the Executive when to build a tool — a job that looks something up and then checks or acts on each result, paged results, more than about ten items, or an answer that needs three or more reads (find, open, read; the tool returns only what answers the question, not whole documents, and only what is about to be edited or quoted at length is read in full), while a handful of items already named go as direct calls in one turn — and never to say it has none, and to talk about it as building a tool or doing it in one go. On the principal's own verified, interactive turns, a script that works can be saved as a named tool (`save_as`; elsewhere the script runs but is not saved) and run again with `run_script(tool=…, inputs=…)`; `list_saved_tools` (a constant definition, in `PRINCIPAL_ONLY_TOOLS` with `load_mcp_server`, so offered only while the principal is speaking on a verified, interactive surface; `run_script(tool=…)` is refused on any other turn) lists them, and each call a saved tool makes is a gateway call like any other (see Workflows → Saved tools). The tool's definition is a constant, so the cached tool prefix does not move. 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 (3 built-in and 2 company chunks by default, see the RAG section) 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`; the last two sit in the `memory` group of `open_tools`, since they are rarely needed) 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-5`; the deep-reasoning tier (CSO, CFO, GC, Board) runs on `DEEP_REASONING_MODEL`, `claude-sonnet-5-5` by default, with adaptive thinking; routing/fast classification uses `claude-haiku-5-5`. Requests are fitted to the model's generation on the way out (`feature_gate.fit_claude_generation`): 5-generation Claude models never receive `temperature` / `top_p` / `top_k`, and Haiku 5.5, which thinks unless told otherwise, gets thinking turned off when the caller asked for none. 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-5`, `claude-sonnet-5`, `claude-haiku-5-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. The Executive's card also has **Model after pushback** (`agent_overrides.pushback_model`, default `PUSHBACK_MODEL`, empty = off): any model the picker offers, or \"Same as normal answers\" (stored as `off`, so it wins over a `PUSHBACK_MODEL` that names a model). See **After pushback** in the turn lifecycle. 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-5-5`, else `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**. Each Council agent has a **visibility**: `core` for the Executive and the domain specialists (`BaseAgent.visibility = \"core\"`, which a new specialist must declare) and `internal` (the default) for triage and the helper agents below. Thorough moves only core agents. The Council opens in a **simple view**: the Quality choice, the voice picker, and only the core agents, each with its additional instructions and a model badge. **Show all agents** lists the internal ones too, and **Advanced** opens the full page (the browser remembers the choice). 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, from what they wrote plus any attached files and website pages, which reach it as untrusted content it may draw facts from but never take instructions from), `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\n**Voice.** The Executive answers in one voice persona, substituted into block 0 at `{VOICE_PERSONA}` (`personas/loader.get_active_body`) from the Executive override's `voice_persona_slug`. Three general voices ship in `personas/builtin/`: **Direct** (`default`, the slug used when none is set: answer first, brief and decisive), **Supportive** (a warm coach who explains the why and checks how the plan sits) and **Analytical** (numbers first, options and trade-offs, then one recommendation). They are offered by the picker in Settings → Executive (setup doesn't ask), which saves through `PATCH /agents/executive`; a built-in voice's frontmatter carries the picker's one-line `description` and `sample` reply. The named-executive voices are marked `legacy: true`: the picker hides them, but they still load, so an install that picked one keeps it, and the Agent Council lists them under \"Legacy voices\". Voice files hold disposition only; the response-length ladder lives in `prompts/executive_persona.py`, and a test keeps numeric length rules out of every voice file. An eval scenario may set `voice_persona` to answer in a voice; it rides on `Session.voice_persona_slug`, which wins over the override for that session only.\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**Goals without departments.** The goal tools (`orchestrator.department_tools`) no longer assume a department: `list_department_goals` with no `department_slug` lists every goal with its owner and department, `update_department_goal` names a goal by `goal_id` alone, and `create_goal` takes an optional `area` and `owner_person_id` (a team member). The org block renders goals with no department with their `goal_id`, and their action chips link to `/goals` (see Org).\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\n`recall_history` (Always in the loop, `orchestrator.history_tools`) reads the speaker's own notes, on the same terms as `ghostwrite_email` below: its own registry, offered only on a verified turn in a conversation private to them with their switch on; its `due` flag lists only dated notes, soonest first (see Memory). The ghostwriter below also gets the writer's notes from mail every recipient was on, as a consistency check (`<writer_noted>`).\n\nThe morning reflection, which has no question to look up and no specialist to consult, gets one more read-only tool of its own: `search_knowledge` (`orchestrator.knowledge_tools`), the same knowledge lookup a chat turn makes, for what the company's documents say about a customer, contract, price or policy before it acts.\n\nA fifth, `remind_me` (`orchestrator.reminder_tools`), sets a plain-text reminder sent to the speaker alone when it is due; it opens no mailbox, so it never locks a turn. A sixth, `propose_actions` (`orchestrator.action_card_tools`), does nothing itself: it leaves the speaker a card of up to five actions (a meeting, a message, a new contact) that happen only when they tap Approve, so it stays on after a turn read mail; it is where what an email itself asks for goes, since that is never done on the email's say-so. Four read-only tools beside it read the speaker's own mailbox on the same terms — `search_my_email`, `read_my_email`, `read_my_email_attachment`, `my_email_awaiting_reply` (`orchestrator.mail_read_tools`) — and `my_calendar` their own calendar while Read my calendar is on, capped per turn, other people's messages and attached files returned as untrusted blocks (see Act as me). Beside them, `save_my_email_attachment` copies one attached file, when the speaker asked in their own words, into a fixed folder of the Executive's own Drive or OneDrive and shares it with them alone, every call built in codeOne 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 mailbox, Gmail or Outlook (`delegation.gmail.gmail_for` picks the client by the person's credential); chat never sends it (the person sends it themselves, or taps Send on its card). 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, or a team member once the owner lets them, 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. From the round that calls it until the turn ends, the dispatch guard refuses only what opens an outside address, runs a script or workflow, or posts to everyone (`delegation.lockdown`), without changing the offered list; messages and invites to the roster, follow-ups, facts in the person's own words and a contact they name still run, each fenced in its own path. That is Careful; on Balanced the rest lifts once every mail read so far was checked clean by `content_scan` (`outside_content.check_mail_read`, the round that reads still holding), and a read inside a script or workflow, flagged, too big or unchecked keeps it (`lockdown.mail_lock_holds`). A later turn in the conversation stays private to its owner but holds nothing: the person asking again, having read the reply, is their own request. A contact add the lockdown refuses becomes an approval card in the chat instead (`propose_actions`). Recipients are chosen in code, never by the model (a draft's new email may go to any address, named back to check when it is neither on the roster nor typed), 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)**. A second tool joins the same way: `recall_history` (`orchestrator.history_tools`, Always in the loop) reads the speaker's own notes of what they said, by email or in chat. It has its own registry and per-turn handler map too, and the loop adds it only when `history_tools.recall_person` finds the speaker verified, in a conversation private to them, on an interactive turn that isn't private to the principal, with their notes switch on. It doesn't need Act as me. After every chat turn the Executive also hands the speaker's own words to `history_chat.schedule_chat_notes`, which takes notes in the background when their switch is on and the surface verified them (see **Memory**). A meeting `create_calendar_event` proposes works the same way when the person chatting is the one who approves it: its chip carries the `decision_id` and the chat shows the meeting card (Approve, Edit, Dismiss) under the reply, while the briefing keeps it too. A tool result held for someone else's approval (`waiting_for_approval`, the department gate) gets a *Waiting for approval* chip, never a done one.\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). Every artifact belongs to someone: a draft to the person whose turn published it (`artifact_records.current_viewer`; with nobody speaking, the scheduler or the CLI, the principal), and a run someone started by hand to them, while scheduled runs are the team's. The tools, the recall, `message_person`'s link and mail attachments only ever reach the speaker's own (a link is refused when the recipient couldn't open it), not even the principal sees a teammate's, and a speaker who isn't on the People list publishes nothing. A workflow's own session inside someone's turn (the research synthesis) is pinned to that turn's viewer (`Session.documents_viewer`). 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\n**Extensions** (`orchestrator.extensions`). An install can add chat tools and kinds of document without changing this code. `OPENEXECUTIVE_EXTENSIONS` names Python modules. The first turn, or the first Documents read, imports each one and calls its `register()`. A module that fails is logged and skipped. `register_tool` takes an `ExtraTool`: a definition, an async handler, an optional `tool_groups` group (new or existing) and an optional chip. It refuses a name the loop already knows (`executive.builtin_tool_names`). An extension tool is never in `_ALL_SKILL_TOOLS`, so reflection, research and the synthesis never see it. The chat loop adds it per turn, like the Act as me tools, but never on an unattended run, a turn private to the principal or to a speaker who isn't on the People list (mail from a stranger), and only where its own `offered(session)` says. A tool registered `known_caller=False` is the one exception to the People-list rule: it is asked on a turn with no verified caller too (a surface of the extension's own that names its user without proving who is speaking), so `register_tool` requires it to have an `offered` that checks who is asking; it is still never offered on an unattended, private, AI-app or replay turn. That predicate depends only on the kind of turn, so each kind of turn keeps one cached tool list. Act as me's lockdown refuses it once the turn has read the owner's mail, because it is unclassified and the lockdown fails closed, unless it was registered with `after_mail_read=True`: a tool that only reads the install's own data and carries nothing the model wrote anywhere outside. Its chip goes through `action_chips.summarize_action`, which applies the same no-chip rules for an error or refusal and keeps a link to a path inside the app. A `waiting_for_approval` result is the tool's own chip's to describe, never core's generic \"Waiting for approval\": the department gate never holds an extension tool. A tool may also name the chat's activity line while it runs (`activity_label`) and keep its dispatch audit row private (`private_row`: its input or result quotes the speaker's own data). `register_collection` adds a kind of document: a drafted artifact tagged `collection:<name>` carries that collection on its record. The Documents page gives each collection its own filter. The collection's `on_change` hears about archive, restore and delete before they happen; if it raises, the change does not happen. `draft_artifact(supersedes=…)` refuses a collection's document. The alert pipeline strips `collection:` tags, so only the extension's own code files a document in its collection. A module that fails partway through `register()` leaves nothing registered. A tool registered with `workflow=True` is also offered to workflow action steps as `oe__<name>` (see Workflows); `read_only=True` marks one that only reads. A step runs with nobody in the turn, so `offered` isn't asked: `extensions.in_workflow_step(name)` is True for that tool, during its call only, and the handler decides what an unattended call may do.\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. For questions about the product itself, the always-offered `read_user_guide` tool (`orchestrator/guide_tools.py`) returns any `guide/prebuilt/<id>.json` section; its description lists the section ids, fixed at import, so it never changes the cached tools prefix.\n\n**Take the lead** (`orchestrator.take_the_lead`) is how the Executive acts on its own, behind one gate. It has two switches, both off until someone turns them on. **As the Executive** is the principal's alone (`PUT /take-the-lead`). With it on, the unattended passes (reflection, research, the scheduler's proactive trigger) keep the acting tools solo mode otherwise withholds from them: booking, starting workflows, and messaging teammates rather than only the principal. `schedule_tools.unattended_toolkit` and the chat loop's unattended path then wrap every acting tool (`ACTING_TOOLS`, plus any MCP tool whose name sends, creates, updates, deletes or shares) in `gated_handlers` / `gated_call_tool`. The principal-only tools (`UNATTENDED_WITHHELD_TOOLS`) stay withheld, and every guard inside a handler still applies, including department approval levels (a booking in a department on Proposes is still a proposal) and the contact-egress rule. New mail or chat (any turn with an `origin_channel`) wakes the existing reflection early (`take_the_lead.wake`): one run waiting at most, five minutes after the first message and no more than every 30 minutes, as a one-off `take_the_lead_wake` scheduled action. Pause holds it like any scheduled work. **As you** is the Handle it for me dial's top step (delegation section).\n\n**The gate** is plain code (`take_the_lead.check`). Six kinds of action wait for a yes first, each with an Ask first switch, all on to start. The switch is the decision ledger's own mode for the class `take_the_lead_action:<kind>` (`propose` asks first, the default; `auto_execute` doesn't). The kinds are money, contracts and legal, hiring and people decisions, deleting/cancelling/sharing, someone new (an address on neither the roster nor the contacts) and big sends (a broadcast or department message, or more than five people). On top of these, the company (set by the principal) and each person (for their own As you) add structured rules: a person or address, a domain, words, or an amount at or above a figure. Added rules always hold, and an error reading them holds the action. The one thing the gate lets straight through is a direct message (`message_person` or a Slack, Telegram or Discord DM) whose only recipient is the principal (`_only_to_principal`): they are who it would wait for, so a card would only ask them to approve a message to themselves. Anything that reaches or acts on anyone else is checked, and a roster that can't be read is not the principal. A held action becomes a `take_the_lead_action` decision instance with a companion `DECISION_ALERT_SOURCE` card on Today, routed to the first teammate holding one of its People approval ranges (`take_the_lead.approval_ranges`, plain code, closest fit first: money to `spend_lt_2k`, `spend_lt_10k` or `spend_gt_10k` by its largest amount, with a higher range able to approve a lower one and no amount read as large, or to `customer_credit` for credit and payment terms; vendor contracts to `vendor_onboarding` then `legal_sign`, other contracts to `legal_sign`; hiring to `hiring_signoff`; anything else about the board or investors to `board_comms`; in Personal as in team mode), or else the principal through the authority gate's fallback (`departments.authority._route_proposal`). Deletes and shares always go to the principal. Only the principal and that approver see or resolve it (`DecisionClassSpec.principal_and_approver`). Approving it claims the row and carries out the exact call once (`take_the_lead.carry_out`: the unwrapped handler, or the gateway's `call_tool`, on an unattended session, with contact egress only when the principal approves). Declining drops it. Everything done or held is a row in `take_the_lead_log`. What it did and what was approved show in Recent activity (`today._build_activity`, kind `took_the_lead`), named but never quoted, since that feed is the team's. The held card's own `decision_resolved` row is left out because its payload quotes the message. `GET /today/activity` also adds the caller's own Handle it sends (kind `sent_as_you`, actor `you`), which are never in the shared feed.\n\n**In training.** The As the Executive switch has three positions: Off, **In training** and On (`take_the_lead.training`). In training, an action the gate would let through still waits, as a `training` hold for the principal alone, unless the principal has allowed that action with that person or thing (`take_the_lead.allowance`: \"Message Priya Nair\" covers a message to her on any channel; \"Book meetings with Priya Nair and Sam Lee\" meetings with exactly them; a workflow by id; a connected tool by name and the file it names, never one that reaches people such as a mail send or a share). The card carries Approve with a **Do this on its own next time** tick (`allow`), **Edit** (the message, a meeting's title, times or description, a task and its due date: `take_the_lead.apply_edits`) and Decline. Allowing is the principal's alone and needs a request the API can tie to them, as turning it on does; the six kinds and the added rules hold whatever is allowed. An edit approved with \"Do it like this next time\" is kept as an example (only the edited text, the principal's own words), and `take_the_lead.learned_note` hands the examples and the fact it's in training to the reflection and research passes in their user turn. After `SUGGEST_AFTER` (3) unchanged approvals of the same action in 30 days, Settings suggests allowing it. What it's learned is one list keyed by feature (`take_the_lead_allowed.feature`), so other features that learn from approvals can join it; each keeps its own switch. Act as me is the second (`act_as_me`, per person, `delegation.training`), with a training switch per setting (Replies, Follow-ups, Suggested actions, Drafts): its rows carry the person's id and the setting in their key, are listed and removed by that person alone, count toward their own cap, and never reach `learned_note`.\n\n**AI disclosure.** Nothing the Executive sends to people outside the web chat goes without saying it is an AI: plain code adds the line in the MCP gateway (mail) and at each chat send (Slack, Telegram, Discord, Google Chat replies, its DMs and room posts), never the prompt, so the persona and the cached system blocks are unchanged and a reply the model writes can't drop it. Replies the inbox watcher writes as a person carry their own line by that person's switches. See Integrations → **AI disclosure** and Act as me → **AI line on replies**.\n\n**App control from chat** (`orchestrator/app_control.py`, catalog in `orchestrator/app_control_catalog.py`). Three tools in the `app` tool group let the Executive do what the app's buttons do when the person asks (\"pin this\", \"delete that chat\", \"turn off Handle it for me\"): `find_in_app(kind, query)` lists what the speaker may change (their chats, topics, documents, workflow runs, settings; files, memory, departments, skills and workflows for the principal), `do_in_app(action, id, value)` does one action (`id: \"this\"` is the chat they are in), and `open_in_app(screen)` returns an in-app link. Each action calls the API route its button calls, as a function, with a request naming the turn's verified speaker (`correction_tools._speaker`; an email or unattended turn gets a refusal), so the route's own checks decide what this person may do. Actions whose route checks nothing about the caller (their page is the principal's) are `principal_only`. Deletes, shares, turning on Act as me, Handle it for me or Take the lead, removing a Take the lead rule, clearing every card and approving a workflow's waiting step never run in the turn: they become an `app_action` decision card, private to the speaker, shown under the reply; the tap runs the action with the tapper's own request through `POST /decisions/{id}/approve` (claimed once; a card older than a day is turned down). After a turn reads outside text or the speaker's mail, every action becomes a card. The tools are withheld from unattended and AI-app turns, and `do_in_app` from a shared chat someone else spoke in. Snoozing a card uses `ack_alert`'s trust rule: only ids the server showed or found this turn. Extensions add kinds, actions and screens with `register_kind` / `register_action` / `register_screen` at startup. The person's notes stay with `recall_history`; account, sign-in and billing stay on their screens.",
"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-22T20:00:00+00:00"
+ "generated_at": "2026-10-27T21:30:41Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 4d1c0df1..29c02b6e 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). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is 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 and Slack 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 the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. 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\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\n**Host origins.** Another app on a sibling host (`OE_HOST_ORIGINS` on the UI, exact origins) may frame the pages and call a short list of routes from its own pages, as the signed-in person. The list is `packages/ui/src/lib/host-list.json`: who is signed in (`GET /auth/me`, the email the call is made as, so the host can warn when that isn't its own user; never `/auth/allowed-emails`), `/today*`, `/decisions` and one decision, conversations (`GET /sessions*`) and the watch list; `ack`, `snooze`, `reopen`, `bulk-ack` and `review` on alerts; `POST /chat`, `/chat/stop`, `/chat/add`, `/chat/upload`, `/chat/transcribe`; and the watch list's describe, add, edit, delete, approve and decline. No card's approve, reject or cancel, no prepare, Act as me, delegation, settings or People (`tests/unit/test_host_list.py` checks each entry against the app's routes and against that rule). The UI's middleware and proxy enforce it: a request whose `Origin` is a listed host origin, with `Sec-Fetch-Site: same-site`, may make only those calls, with CORS for that exact origin and credentials (its preflight answered before the session check, a missing session a `401` with CORS), and anything else from it is a `403`. The proxy then drops the browser's `Origin`, `Referer` and `Sec-Fetch-*`, so the local-login rule above never sees them, and marks the call's **surface** `host`: an optional `surface` claim in the signed assertion and `x-caller-surface`, which must agree with it (`401` otherwise; without signed callers the header is read like the email). `api.caller.from_host` answers it, and a chat turn on that surface (`Session.from_host`) only reads and advises (see Agents). Every page of the UI also sends a `Content-Security-Policy`: scripts only with that response's nonce (no `unsafe-inline`, no `unsafe-eval` outside the dev server) and `frame-ancestors 'self'` plus the host origins. `make embed-outputs` writes the API's OpenAPI description (`scripts/export-openapi.py`), the host list and the UI's navigation for a host app's own checks.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background`, `GET /chat/voice`, `POST /chat/transcribe` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. 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`. When the turn held steps for an outside read that still wait on the speaker's go (`outside_content.pending_held`), it then sends one `held_steps` event, `{type, session_id, steps: [plain words]}` (not after a stop or a timeout), which the UI shows as Approve / Not now under the reply; Approve sends \"Go ahead\". `GET /sessions/{id}/messages` puts the same `held_steps` on the last reply while they still wait (never for a shared chat's member). When the content check flagged something the turn read (`outside_content.pending_flags`, `orchestrator.content_scan`), it also sends one `flags` event, `{type, session_id, flags: [plain words]}`, shown as \"Something looked off\" under the reply, and `GET /sessions/{id}/messages` puts the same `flags` on the last reply for an hour (never for a shared chat's member). 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/shared-with-me`, `GET /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). 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. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. 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. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `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) with `narrative_progress` `{step: reading|writing|checking, new_mail, since}` while it is, the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since, source}]` (`source`: the email or Needs you card a point is about, or null), `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. 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` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `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| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss`, `GET /contacts/{person_id}/note` | The contact keeper (see Org), principal only (404 for anyone else). `GET /contacts/{person_id}/note` returns what is remembered about one contact or teammate (`note`, `topics`, `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `note_written_at`, `updated_at`), 404 when there is nothing yet or they are not active. `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `GET\\|POST /goals`, `PATCH\\|DELETE /goals/{id}` | Department state and goals. A goal has an optional department and an optional `owner_person_id` (a non-archived team member, else 422). `GET /goals` lists every goal with `owner_id`/`owner_name` (its own owner, else its department's head, else the principal) and `department_title`. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing department by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else no department when blank. `PATCH /goals/{id}` edits any goal and may move it (`department_slug`, null = none; `owner_person_id`, null = follow the department) — only the fields sent change; `DELETE /goals/{id}` removes any goal. The department-scoped goal routes still reach only that department's goals. `DELETE /departments/{slug}` keeps its goals with no department, on their owners. `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, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. 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). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `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`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `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. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\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). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. 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/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `GET /delegation/mail?thread_id&message_id` (one email in the caller's own mailbox: their words without the quoted mail, attachment names, what they last wrote in the conversation, a mailbox link, the open reply card), `POST /delegation/mail/reply` `{thread_id, message_id}` → `{decision_id}` (a reply card on request, the conversation's open one when there is one; 409 with a code when it can't), `PUT /delegation/replies/{id}/text`, `POST /delegation/drafts/{id}/send`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `POST /delegation/replies/{id}/change`, `GET /delegation/actions`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `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), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), 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 mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. 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 caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, a one-line `gist` (what they asked and what the draft says, written with the draft and brought up to date when an answer rewrites it; empty on an older card), the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. Send with the *on its own next time* tick adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for the *Do this on its own next time* tick while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`), the finer `cause` (null when the grade gave none) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\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), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. 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 usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\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. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\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 mailbox (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. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. 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\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|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`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) 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 (every sync holds 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`, `GET`/`PUT /executive/outside-content` | 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, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `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. `GET /executive/outside-content` returns `{mode, channels, channel_ids, can_change}` for the owner's safety level, \"When should I check with you?\" (`ask` Careful, `outsiders` Balanced or `trust` Hands-off; `orchestrator.outside_mode`): `channels` maps each channel set apart to its own level, and `channel_ids` lists the channels a level can be set on. `PUT` with `{mode, channels?}` changes it for the principal only (403 otherwise; an unknown channel or level is a 422): a channel given a level is set apart, one given `null` follows `mode` again, and channels left out keep theirs. A change writes an `outside_content_mode_changed` audit row. |\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/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. 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`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. A workflow with a step that sends email as its creator (`oe__send_email_as_me`) or reads their mail or calendar (`oe__search_my_email` and the other reads, `delegation.workflow_reads`) can be created, changed (`PUT`, save-edit) or switched on (`activate`) only by that creator, verified as Send on a reply card is; anyone else gets a 403 (`delegation.workflow_email.save_refusal`), as does a save of one that reads and also lists a tool a run may not use after reading mail. `POST /workflows/{name}/runs` answers 403 to anyone but the creator of a workflow that reads their mail. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. 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. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `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`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). 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| `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). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller 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/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/onboard/interview/commit` | Conversational company setup. `understand` and `start` take multipart `description`, optional `files` and an optional `website` the server reads itself (a non-address is a 422; an unreadable site is no pages, never an error); `start`'s response lists the pages read in `website_pages`, and the draft's profile carries `website`. The `onboarding_interviewer` agent asks up to four quick questions (a question response carries `question_options`, suggested answers to tap), then emits a draft profile + people + `draft_goals` (each `{title, target, owner_name, department_title}`) + departments only when the user listed people by department. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` takes the reviewed `goals` too (422 when one names a person or department not in the draft) and saves them with owners, additively. It 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/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. 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| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\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| `auth` | `GET /auth/me` | `{email}`: the email the request is made as (`api.caller`, lowercased; `\"\"` when it names no one), nothing more. On the host list, so a host's own screens can warn when the session signed in here is someone else's. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\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`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\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, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it does for you.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
+ "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). A request it lets through is marked `request.state.shared_secret_ok`, which is what lets an MCP request turn on \"may act\" with `x-mcp-client-actions: on` (`mcp_server.may_act`; with no secret the header is ignored and `MCP_CLIENT_ACTIONS` decides). With local login (`OE_LOCAL_LOGIN=1`, which only `make dev` sets, and only while neither Google nor SSO sign-in is 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 and Slack 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 the UI origins in `BACKEND_ALLOWED_ORIGINS`, plus the `make dev` UI on `localhost:3000` only when `OE_PUBLIC_DEPLOYMENT` is unset, so a public instance never answers a localhost page with credentials. 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\n**Who is calling** is read in one place, `api/caller.py`, which answers with a `Caller` kind and email; a test fails on any other read of an `x-caller-*` header. By default (`open`) it is the `x-caller-email` the UI proxy stamps from the sign-in, trusted because whoever holds the shared secret is trusted as the proxy, and a request with none runs as the principal. **Signed callers** remove that trust. With `CALLER_ASSERTION_PUBLIC_KEYS` set, the proxy signs every request with an Ed25519 key only the UI holds, and a third middleware checks the `x-caller-assertion` header:\n\n- **What it covers.** It is good for one method, the exact path and query, at most 120 seconds, and one use. The API keeps used ids in memory.\n- **What it names.** A `user`, by email, or the `operator`: local login, which runs as the principal.\n- **No caller header at all** is a `service`, for scripts or MCP clients holding only the secret. It is never the principal, not even on an install with no owner yet, so it can't save a first setup.\n- **Anything else is a 401.** That includes an `x-caller-email` without an assertion (`caller_assertion_required`), and a bad, expired, reused or mismatched assertion (`caller_assertion_invalid`).\n\nPublic keys that can't be read stop the boot, rather than fall back to trusting the header. `scripts/make-caller-keys.py` makes the pair, and `scripts/mint-caller-assertion.py` signs one request for curl. The API holds only public keys. Setup's API-protection check warns while a shared secret is set without them.\n\n**Host origins.** Another app on a sibling host (`OE_HOST_ORIGINS` on the UI, exact origins) may frame the pages and call a short list of routes from its own pages, as the signed-in person. The list is `packages/ui/src/lib/host-list.json`: who is signed in (`GET /auth/me`, the email the call is made as, so the host can warn when that isn't its own user; never `/auth/allowed-emails`), `/today*`, `/decisions` and one decision, conversations (`GET /sessions*`) and the watch list; `ack`, `snooze`, `reopen`, `bulk-ack` and `review` on alerts; `POST /chat`, `/chat/stop`, `/chat/add`, `/chat/upload`, `/chat/transcribe`; and the watch list's describe, add, edit, delete, approve and decline. No card's approve, reject or cancel, no prepare, Act as me, delegation, settings or People (`tests/unit/test_host_list.py` checks each entry against the app's routes and against that rule). The UI's middleware and proxy enforce it: a request whose `Origin` is a listed host origin, with `Sec-Fetch-Site: same-site`, may make only those calls, with CORS for that exact origin and credentials (its preflight answered before the session check, a missing session a `401` with CORS), and anything else from it is a `403`. The proxy then drops the browser's `Origin`, `Referer` and `Sec-Fetch-*`, so the local-login rule above never sees them, and marks the call's **surface** `host`: an optional `surface` claim in the signed assertion and `x-caller-surface`, which must agree with it (`401` otherwise; without signed callers the header is read like the email). `api.caller.from_host` answers it, and a chat turn on that surface (`Session.from_host`) only reads and advises (see Agents). Every page of the UI also sends a `Content-Security-Policy`: scripts only with that response's nonce (no `unsafe-inline`, no `unsafe-eval` outside the dev server) and `frame-ancestors 'self'` plus the host origins. `make embed-outputs` writes the API's OpenAPI description (`scripts/export-openapi.py`), the host list and the UI's navigation for a host app's own checks.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop`, `POST /chat/add`, `POST /chat/background`, `GET /chat/voice`, `POST /chat/transcribe` | SSE stream of a live Executive turn, with a `: keepalive` comment every `CHAT_STREAM_KEEPALIVE_S` while the turn is quiet. `POST /chat/background` starts a new chat that the server answers to the end with nobody connected (a phone approving a card, then closing the app): it answers `202` with the new `session_id` once the same caller, access and quota checks as `/chat` pass, the turn saves itself as a `/chat` turn does, and one caller may have three running at once (`429` beyond that). `POST /chat/add` hands the running turn a message the person typed while it works; the turn takes it at its next step and the stream names it in a `message_added` event, and a second `POST /chat` on the same conversation waits for the first to finish. `GET /chat/voice` says whether the chat mic shows (`available`, `max_seconds`); `POST /chat/transcribe` takes one recording (multipart `file`) and answers `{text}` for the message box, nothing kept: `404` when speech to text isn't set up, `400` for a file that isn't audio, `413` over 25 MB, `502` when the speech server fails. 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`. When the turn held steps for an outside read that still wait on the speaker's go (`outside_content.pending_held`), it then sends one `held_steps` event, `{type, session_id, steps: [plain words]}` (not after a stop or a timeout), which the UI shows as Approve / Not now under the reply; Approve sends \"Go ahead\". `GET /sessions/{id}/messages` puts the same `held_steps` on the last reply while they still wait (never for a shared chat's member). When the content check flagged something the turn read (`outside_content.pending_flags`, `orchestrator.content_scan`), it also sends one `flags` event, `{type, session_id, flags: [plain words]}`, shown as \"Something looked off\" under the reply, and `GET /sessions/{id}/messages` puts the same `flags` on the last reply for an hour (never for a shared chat's member). 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/shared-with-me`, `GET /sessions/topics`, `PATCH\\|DELETE /sessions/topics/{topic_id}`, `POST /sessions/topics/{topic_id}/merge`, `POST /sessions/topic-areas/rename`, `POST /sessions/topic-areas/ungroup`, `GET\\|PATCH /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup`, `GET\\|PUT /sessions/{id}/shares`, `DELETE /sessions/{id}/shares/me`, `GET /sessions/{id}/people`, `GET /sessions/{id}/live`, `POST /sessions/{id}/typing`, `GET /sessions/{id}/export`, `POST /sessions/{id}/rewind` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller, and each chat carries `preview`: its last message as one plain line, Markdown marks stripped and cut at a word near 120 characters, with `You:` before the person's own words. With `?q=` it is a search: the caller's own chats whose title or message text contains the words (case-insensitive, `LIKE` with wildcards escaped), each with `match_count` (messages that contain them; 0 for a title-only match) and `snippet` (the newest matching message, around the match, prefixed `You:` or `Executive:`). Scoped exactly like the list, so nobody else's conversation can match. The Chats page searches this way and opens a result with `?find=`, so the chat starts on that message and steps through the others. Each of the owner's chats also carries `topic_id`, the topic it is filed under (`memory.chat_topics`). `GET /sessions/topics` lists the caller's topics (`id`, `name`, `chat_count`, `kept`, `pinned_at`, `area`, `updated_at`) and, when some of their chats have no topic yet or some topics no area, starts filing them in the background from their titles and answers `organizing: true` until done. `PATCH /sessions/topics/{topic_id}` renames (a name another of their topics has merges the two) or pins one, `POST …/merge` moves its chats into another (`into_id`), and `DELETE` ungroups it, leaving its chats under no topic; another person's topic is a 404. `POST /sessions/topic-areas/rename` (`area`, `name`) renames one of the caller's areas and `…/ungroup` (`area`) drops it, its topics standing alone; an area they don't have is a 404. `PATCH /sessions/{id}` also takes `topic_id` (null for none) or `topic_name` (made if new) to file the chat, which then is never refiled on its own. A chat-app conversation started with /new is left off the list until its first turn (`memory.conversations`). 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. A teammate's own chat (a web chat, a DM, a private Telegram chat; not a channel or group conversation, `chat._shared_space`) is theirs alone, the principal included, as their mail with the Executive is. 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. The owner (not the principal on someone else's chat; the principal for an ownerless one) also has the chat controls. `PATCH` takes `{title?, pinned?}`: a name they give is kept (`sessions.title_locked`, so the automatic title never replaces it) and a pinned chat lists first, newest pin first, with `pinned_at`. `PUT /sessions/{id}/shares {person_ids}` adds exactly those team members to it (not contacts, the archived or the owner: 422), audited `session_shared`; a chat that read its owner's own mail (`mail_private`) is never shared (409) and stops being open to those it was shared with before, and a chat-app conversation is never shared (409). Those added get it from `GET /sessions/shared-with-me` (with `shared_with_you`, `shared_by`, `shared_at`) and **write in it with the owner**: `POST /chat` with its id runs their turn as themselves (`chat._shared_member` widens the turn's access, never its ownership), and they may read it, its messages (without the owner's ratings) and its export. They can't rate, rename, delete, share or redo it, and `DELETE /sessions/{id}/shares/me` takes them out of it (audited `session_shared`, with them under `removed`). In a chat several people are in, messages carry `sender_person_id` and `sender_name` (a message from before it was shared is the owner's), `GET /sessions/{id}/people` returns `{you, people: [{person_id, full_name, owner}]}` (owner first; empty for a chat of one), and redo is refused (409) when the last message is someone else's. `GET /sessions/{id}/live` is a server-sent event stream each open page holds (`api.chat_live`, one in-process broker): `ready` first (with the running turn so far, if any), then `turn_started` (who sent what), the reply's `chunk` / `thinking` / `activity` / `action_taken` / `phase`, `turn_ended` (the page reads the chat again), `typing` (from `POST /sessions/{id}/typing`, at most once per 2 s per person) and `people`. `removed`, `deleted` and `resync` (a page that fell 1024 events behind) end it; the access check runs again on every 20 s keepalive. At most 12 pages per person, 40 per chat and 2000 per process (429). Archiving someone takes them out of every chat shared with them, and their open streams close at the next keepalive. The page closes it while its tab is hidden. `GET /sessions/{id}/export` returns the chat as a Markdown file (`memory.chat_export`: each message under its writer's People name or `Executive`, the reply's sources listed under it). `POST /sessions/{id}/rewind {last_message_id}` takes back the last turn for Try again and Edit: under the conversation's turn lock it deletes the last reply and the messages it answered, but only while that reply is still the chat's last row, and returns those messages' words (`{message}`), which the page sends again as an ordinary `/chat` turn through the usual gates. 409 while a turn is answering, for a stale reply id, and for a chat-app conversation (its reply also lives in Slack, Telegram or Discord); audited `session_rewound`. |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily`, `GET /today/brief-delivery`, `GET /today/value`, `GET /today/top-three`, `GET /today/weekly-review`, `POST /today/seen` | Morning-brief aggregation (in the install's first week, for the principal, `first_week_card` `{needs_goal, findings: [{title, summary}], brief_tomorrow}` or null), recent-action rail, Pulse heartbeat heatmap (per-day activity counts), and the owner's month tally for Pulse's Done for you (`GET /today/value?period=month|week&offset=N`: counted lines beside the period before plus the finished reports, owner only, 403 otherwise; see Today). `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) with `narrative_progress` `{step: reading|writing|checking, new_mail, since}` while it is, the same text split for Home's Right now card (`narrative_lead`, `narrative_points` `[{text, since, source}]` (`source`: the email or Needs you card a point is about, or null), `narrative_move`), `narrative_seen_at` (this reader's last look, which `POST /today/seen` records and returns as `{seen_at}`) and, for the principal, `morning_brief` `{at, text}` and `calendar_next` `[{title, start, all_day}]`. 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` (a `POST` tells the owner once and returns `notified`: `sent` with the channel, `held`, `not_reached` or `skipped`; see Attunement), `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| `contacts` | `GET /contacts/changes?person_id=`, `PUT /contacts/keeper`, `POST /contacts/changes/seen`, `POST /contacts/changes/{id}/undo`, `POST /contacts/changes/{id}/accept`, `POST /contacts/changes/{id}/dismiss`, `GET /contacts/{person_id}/note` | The contact keeper (see Org), principal only (404 for anyone else). `GET /contacts/{person_id}/note` returns what is remembered about one contact or teammate (`note`, `topics`, `last_emailed_at`, `last_heard_at`, `last_met_at`, `next_meeting_at`, `next_meeting_title`, `emailed_count`, `met_count`, `note_written_at`, `updated_at`), 404 when there is nothing yet or they are not active. `GET` returns `{mode, status, last_run_at, changes}`: the switch (`on` / `ask` / `off`), how the last pass went (`ok`, `act_as_me_off`, `not_connected`, …) and the last 30 days of changes (each `id`, `person_id`, `action` add/update, `field`, `email`, `full_name`, `old_value`, `new_value`, `reason`, `evidence`, `status` applied/suggested/undone/dismissed, `seen`, `created_at`); with `person_id`, that person's every change. `PUT` sets the switch; `seen` is Got it; `undo` / `accept` / `dismiss` return the change, 409 when there is nothing to undo or decide. |\n| `chat-directory` | `GET /chat-directory/people`, `GET /chat-directory/channels`, `GET /chat-directory/slack/lookup?email=` | The Slack, Discord and Telegram people and rooms the bots can reach, by name, for the People and department pickers (`integrations/chat_directory.py`). Each answers `{slack, discord, telegram}`, every one `{configured, ok, options: [{id, name, detail, email}], truncated, members_available}`: `configured` false (and no options) when that bot has no token, `ok` false when the provider could not be read, `members_available` false when Discord refuses to list server members (the Server Members intent is off). `lookup` returns `{configured, match}`, the Slack person with that work email or null. Cached in-process for 60 s; tokens are never returned. The principal's alone, like changing the People list (`chat._caller_is_principal_or_unclaimed`); channels also open while no one is principal yet, people and lookup wait for one; a 403 otherwise, and the pickers then keep only the by-hand id field. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals`, `GET\\|POST /goals`, `PATCH\\|DELETE /goals/{id}` | Department state and goals. A goal has an optional department and an optional `owner_person_id` (a non-archived team member, else 422). `GET /goals` lists every goal with `owner_id`/`owner_name` (its own owner, else its department's head, else the principal) and `department_title`. `POST /goals` takes a goal plus `area` (a name, ≤80): an existing department by slug or title, else a new one of that name (no specialist, as with `POST /departments`), else no department when blank. `PATCH /goals/{id}` edits any goal and may move it (`department_slug`, null = none; `owner_person_id`, null = follow the department) — only the fields sent change; `DELETE /goals/{id}` removes any goal. The department-scoped goal routes still reach only that department's goals. `DELETE /departments/{slug}` keeps its goals with no department, on their owners. `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, i.e. the check-in is off); a changed `check_in` cancels the pending check-in and queues the next one on the new schedule. `GET` and `PATCH /departments/{slug}` return the department state plus `next_check_in_at` (ISO UTC of the pending check-in, `null` when it is off, the workspace is solo or none is queued); the list route does not carry it. 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). The Executive's `AgentDetail` also carries `pushback_model` (its model for one answer after pushback; `off` or empty = off) and `pushback_model_default` (`PUSHBACK_MODEL`); `PATCH /agents/executive` takes `pushback_model` (an allowed model, `off`, or null to follow `PUSHBACK_MODEL`), and any other agent rejects it with a 400. `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). Each `AgentMeta` carries `visibility` (`core` or `internal`) so the Council's simple view can list core agents first. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/approve`, `GET /alerts/approvals/{id}`, `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/snooze`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `approve` (body `{edited_body?}`, 202) carries a proposal card out on the server and records who approved it and when (`alerts.approvals`, see Today): it queues the scheduled action a department-gated card held, or runs one Executive turn as the approver in a new chat (`session_id`). 409 for a card already approved or closed, a decision-backed card (approved at `/decisions`), a roster request or a drafted artifact; 403 unless the caller is the card's routed person or the principal (an unrouted card is the principal's); 429 when the caller already has three background turns running. `GET /alerts/approvals/{id}` reads one back (`running`, then `done` / `failed` with `outcome`) for its approver, the card's person or the principal (404 for anyone else). `snooze` (`until`, an ISO time up to 30 days ahead; `null` clears it, the Undo) hides an `unread` card until then by setting `snoozed_until` (409 on a closed card or a roster request); the TTL then counts from the snooze, so a card snoozed past its TTL still comes back. `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`, `supersedes_id` and, for an extension's kind of document, `collection` / `collection_label` on every summary (`orchestrator.extensions`; archive, restore and delete tell the collection first and answer 502 if it refuses). `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. Every route answers for the signed-in caller (`artifact_records.Viewer`): a drafted artifact is its owner's alone (`alerts.owner_person_id`, the person whose conversation published it; none = the principal's), a workflow output follows its run (`persistence.run_visible_to`), and anything the caller may not see is a 404 like a missing id, the principal included. `POST /alerts/{id}/ack` and `/reopen` answer 404 for someone else's drafted artifact the same way. |\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). What approve/reject/cancel do is per class (`DECISION_CLASSES`, one `DecisionClassSpec` each; meeting booking books on approve and deletes on cancel; `delegation_reply`, an inbox reply card, is its approver's alone (`approver_only`) — hidden from everyone else, the principal included when it is a team member's — sends its Gmail draft on approve and, after a reject, deletes the draft unless it was edited; `delegation_invite`, a meeting invite card, is its approver's alone too, and answers the invite in their own calendar on approve (`edits.answer`) and nothing on reject; `department_action`, a team member's chat send or edit their department held (see Org), is the principal's and its approver's alone (`principal_and_approver`), makes that exact call on approve and audits `department_action_done` / `_failed` / `_declined`), and an instance of a class with no spec gets 409 instead of being carried out as another. Only the principal, or the person the decision went to for approval (`approver_person_id`), may approve, reject or cancel it. Anyone else gets 403, and a decision nobody was asked about, or one private to the principal, is the principal's alone. The resolver is recorded as `resolver_person_id`, and a reject that loses the race to another answer is a 409. `GET /audit/reliability` is the principal's alone (403 otherwise), because it counts private decisions too. 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/describe`, `POST /delegation/voice/signature`, `PUT /delegation/inbox`, `POST /delegation/inbox/check`, `GET /delegation/replies`, `GET /delegation/mail?thread_id&message_id` (one email in the caller's own mailbox: their words without the quoted mail, attachment names, what they last wrote in the conversation, a mailbox link, the open reply card), `POST /delegation/mail/reply` `{thread_id, message_id}` → `{decision_id}` (a reply card on request, the conversation's open one when there is one; 409 with a code when it can't), `PUT /delegation/replies/{id}/text`, `POST /delegation/drafts/{id}/send`, `PUT /delegation/replies/{id}/recipients`, `POST /delegation/replies/{id}/answer`, `POST /delegation/replies/{id}/change`, `GET /delegation/actions`, `GET /delegation/invites`, `PUT /delegation/handle-it`, `PUT /delegation/disclosure`, `PUT /delegation/training`, `DELETE /delegation/learned/{id}`, `GET /delegation/handled`, `PUT /delegation/team` | Act as me — the **caller's own** delegation only; nobody sets it for anyone else. It answers the principal, and a team member once the owner lets them; anyone else gets 403 `not_available_yet`. `GET /delegation` returns `{enabled, gmail: {status, message, email, connect_command, outlook_connect_command, provider}, inbox: {enabled, status, message, watch_since, last_poll_at, checking}, handle_it: {enabled, mode, available, sent_today, lead, lead_available}, training: {replies, follow_ups, actions, drafts, learned}, disclosure: {enabled, handle_it, approved_sends, line}, team}`, where `team` is the owner's switch for the principal while `DELEGATION_TEAM_MEMBERS` allows it — `{enabled, members: [{person_id, name, enabled, inbox, drafts_30d, sent_30d}]}`, counts only — and `null` otherwise. `PUT /delegation/handle-it` takes `{enabled?, mode?}` (`mode` is `careful`, `balanced` or `bold`; anything else is a 422 `bad_mode`) from a caller the API knows is that person — 403 `not_yours`, 409 `caller_signing_required` with only the shared secret — and turning it on needs Act as me and Draft replies to my inbox on (409 `act_as_me_off` / `inbox_off`); `GET /delegation/handled` returns `{replies: [{decision_id, sent_at, to_name, to_email, subject, body, open_questions, gmail_link, source, summary}]}`, the caller's replies and follow-ups (`source` `follow_up`) sent on its own in the last 7 days, and the meeting invites it accepted on its own (`source` `invite`, `subject` the meeting's title, `summary` one line such as \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\"); a card on `GET /delegation/replies` carries `source` the same way, `can_allow` while Replies (Follow-ups, on a follow-up) is in training, and `learns_style` while Drafts is. `PUT /delegation/disclosure` takes `{handle_it?, approved_sends?}` (any other field is a 422), the caller's own switches for the AI line on replies sent as them (`disclosure.enabled` is the install's `AI_DISCLOSURE`); turning one on needs no signed sign-in, turning one off does (409 `caller_signing_required`), and a change is audited as `delegation_disclosure_changed`. `PUT /delegation/training` takes `{replies?, follow_ups?, actions?, drafts?, actions_on?}` (any other field is a 422; `actions_on` is Suggested actions On, and `actions` and `actions_on` set true clear each other) and returns the `GET /delegation` shape, whose `training` carries `actions_on` too; putting Replies or Follow-ups in, or Suggested actions out of training or On, needs no signed sign-in, anything else does (409 `caller_signing_required`), and putting Replies or Follow-ups in turns Take the lead as you off (`PUT /delegation/take-the-lead` on answers 409 `in_training` while they are). `training.learned` is `[{id, label, setting, example, uses, created_at}]`, what the caller allowed or kept in training (`setting` `replies`, `follow_ups`, `actions` or `drafts`; the kept example, or \"\"); `DELETE /delegation/learned/{id}` removes one of the caller's own (404 for anyone else's). `PUT /delegation/team` takes `{enabled}` from the principal alone (403 `principal_only`; 409 `not_available` when the install doesn't allow it). The Gmail `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), write it from the caller's own description (`POST /delegation/voice/describe` with `{description}`: one model call applies their words to the profile they have and returns it with a short `sample_reply`, saving nothing, so they review it and save it with `PUT`; a 409 `empty`, `too_long`, `in_progress`, `too_many` past 10 an hour or `no_profile`; no mailbox needed), 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 mailbox isn't connected, it refuses the sign-in or the check itself fails (`gmail_error`), and a 502 `gmail_error` when reading the signature fails. On an Outlook mailbox it is a 409 `signature_unavailable`, since Outlook gives apps no signature to read, and the stored one is left alone. 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 caller is read through `api/caller.py`, as on every principal-only route). `PUT /delegation/inbox` takes `{enabled}` and turns **Draft replies to my inbox** on or off, returning the same shape as `GET /delegation`: on needs Act as me on (409 `act_as_me_off`) and the mailbox connected (the Gmail codes above, which keep their names for an Outlook mailbox too), and turning Act as me off turns it off too. `POST /delegation/inbox/check` starts a scan now in the background and answers 202 with the `inbox` state (409 `inbox_off` or `in_progress`). `GET /delegation/replies` returns `{cards: [...]}`, the caller's open reply cards from the database alone (no Gmail call): the decision id, the sender's name, address, relation and whether it was verified, the subject, when it arrived, what they wrote, a one-line `gist` (what they asked and what the draft says, written with the draft and brought up to date when an answer rewrites it; empty on an older card), the draft's recipients, subject and body, `open_questions`, `flags` and a Gmail link built from a fixed prefix. **Send** is `POST /decisions/{id}/approve`: it sends the card's draft exactly as it is in Gmail, after checking again that the caller is its owner — which on a server needs signed callers (409 `caller_signing_required` otherwise) — that both switches are on (`inbox_off`), no client slot is active (`client_slot`), the Gmail is connected (the Gmail codes), the draft is still there and unanswered (`draft_gone`, `you_replied`) and its recipients are allowed (`no_recipients`, `too_many_recipients`, `executive_recipient`, `not_from_you`). Recipients that changed, or a newer message in the thread, answer 409 `{code: \"confirm\", message, reasons, recipients}`; approving again with `edits: {recipients: <the list shown>, thread_moved_on: true}` is the second yes. Send with the *on its own next time* tick adds `edits.allow: true`: 422 `cant_allow` unless Replies (Follow-ups, on a follow-up card) is in training, 409 `learned_full` when their list is full, both before anything is sent; `edits.example: true` keeps a draft edited in the mailbox as how they write to that person while Drafts is in training. A draft edited in Gmail between those checks and the send is not sent (`draft_changed`). A double tap sends once (`already_handled`); Gmail refusing answers 429 `rate_limited` or 502 `gmail_error` with nothing sent, and a send Gmail didn't confirm answers 502 `send_unconfirmed` and is settled by the next inbox scan. Dismiss is `POST /decisions/{id}/reject`. `GET /delegation/invites` returns `{cards: [...]}`, the caller's own meeting invite cards (`delegation_invite`, Read my calendar on): `decision_id`, `status`, `created_at`, `from_name`, `from_email`, `relation`, `title`, `when` (in the workspace time zone), `start`, `end`, `all_day`, `clashes` (busy times only, `\"14:00–14:30\"`), `clash_checked`, `can_answer` (false for a sign-in that reads but can't answer the calendar; then `connect_command`), `can_allow` (Replies in training) and `waited_because`. **Accept** / **Decline** is `POST /decisions/{id}/approve` with `edits: {answer: \"accept\" | \"decline\"}` (accept is the default; `allow: true` with accept for the *Accept from them on its own next time* tick), on the same caller checks Send uses (403 `not_yours`, 409 `caller_signing_required`); 409 `calendar_write_needed` when the sign-in can't answer (the card stays), `gone` when the event left their calendar, `expired` once the meeting started, `already_handled`; 502 `calendar_error` leaves the card for another try. **Dismiss** is `POST /decisions/{id}/reject` and answers nothing. `GET /delegation/actions` returns `{cards: [...]}`, the caller's own approval cards (`delegation_actions`): the decision id, when it was made, a one-line `why`, and each action's `index`, `kind` (`invite`, `message`, `add_contact`), `summary` and `text` (a message as it will be sent, or a meeting's description). **Approve** is `POST /decisions/{id}/approve` with `edits: {only: [indexes]}` (and `allow: true` for the *Do this on its own next time* tick while Suggested actions is in training: 422 `cant_allow` otherwise or when nothing on it can be allowed, 409 `learned_full`; a card carries `can_allow`); it needs the card's own person signed in (403 `not_yours`, 409 `caller_signing_required`), Act as me on (409 `act_as_me_off`) and a card under a week old (409 `expired`), runs once (409 `already_handled`), and returns the decision with `final_payload_json.results`: per action `done`, `waiting` (sent to whoever approves meetings), `failed` with why, or `skipped`. Every change writes a private audit row. |\n| `history` | `GET /memories/history` (`?q=`), `PUT /memories/history/settings`, `PATCH`/`DELETE /memories/history/{id}`, `POST /memories/history/{id}/forget-conversation` | Always in the loop: the **caller's own** notes and switches only, resolved as for Act as me (a signed-in person on the roster, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{notes, reply_notes, retention_days, effective_retention_days, company_retention_days, retention_choices, can_keep_notes, can_note_replies, can_set_company_retention, share_work_style, can_share_work_style}` (`can_keep_notes`: a team member on the People list may turn notes on; `can_note_replies`: they can use Act as me, so email replies are noted too; `share_work_style`: their own \"Share my work style with the team\" switch, `can_share_work_style`: a team member in a team workspace). `PUT` turns notes on only for someone who may keep them, and `share_work_style` on only for someone who may share it (403 `not_available` for either; turning either off always works), takes a person's retention only when shorter than the company's (422 `invalid_setting`), and the company retention only from the principal (403 `principal_only`). `PATCH` pins or corrects a note; `DELETE` forgets it; `forget-conversation` is \"Don't remember this\". A note that isn't the caller's is 404. Every change is audited privately to its person. |\n| `reflection` | `GET /memories/reflection` (`?person_id=`), `DELETE /memories/reflection/misses/{id}` | Learning: the turns the conversation review graded a miss (`memory.chat_review`), with the person's words, the reply, the tools run, what they wanted instead, the `kind` (`company` / `product`), the finer `cause` (null when the grade gave none) and the signals, plus `weeks` (`{week, graded, misses}` per ISO week, newest first) and `sees_everyone`. The caller is resolved as for `history` (403 `sign_in_required` / `not_on_roster`); each person sees their own, the principal those from chats `chat._session_access` lets them open (a teammate's own web chat or DM and a mail-private conversation stay their owner's; channels and groups are open), or one person's with `?person_id=` (a teammate naming someone else gets 403 `not_yours`); the weekly counts carry no words and are not filtered. The same response carries `lessons` (`memory/lessons.py`: live first, then retired, each with `shown`/`fine_after`/`miss_after` and `retired_reason`), filtered by the same rule, and `DELETE /memories/reflection/lessons/{id}` retires one (204; 404 for a lesson the caller may not see, already retired, or missing). `DELETE` forgets one miss (`is_principal_or_self`; 404 `not_found` otherwise) and writes a `chat_review` audit row. Each miss also carries its nightly replay (`memory/replay.py`): `replay_state` (`open` / `closed` / `evidence`), `replayed_at`, `closed_at`, `replay_notes`; and the response carries `replay` (`{misses, would_pass, evidence, last_run_at}`: of the caller's visible misses from the last 30 days, how many would go right today). |\n| `notifications` | `GET /notifications/settings`, `PUT /notifications/settings` | Settings → Notifications: the **caller's own** settings only, resolved as for the notes (a signed-in person on the People list, or the principal under local login; otherwise 403 `sign_in_required` / `not_on_roster`). `GET` returns `{quiet_hours: {enabled, start, end, days}, delivery, urgent_through, timezone, effective_timezone, held_count, gets_briefs, updated_at}` — `days` is `every_day` or `weekdays`, `delivery` `instant` or `digest`, `timezone` the zone they chose (`\"\"` for the workspace's), `held_count` how many messages wait for their quiet hours or brief (counted, never listed), `gets_briefs` whether they are the principal. `PUT` takes `{quiet_hours, delivery, urgent_through, timezone}` and replaces them (extra fields, equal start and end, a bad time or an unknown zone → 422); switching `digest` → `instant` makes what waited for the brief go now. Audited as `notification_settings_changed`. See Org. |\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), plus `scripts`: how many `run_script` scripts ran (and worked, and in workflows), the tool calls they made, their time, and `turns_avoided` — an upper bound on the model turns those calls would otherwise have needed (each call past a script's first) — and `python_jobs`: how many Python jobs ran (and worked, ran a kept Custom tool, took a chat attachment), their time, CPU, largest peak memory and bytes in and out, and the tokens and charge of the turns that ran one. The Token usage page shows it as a Scripts section. 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 usage totals leave them out. Once a principal is on the roster, anyone else reads only their own rows (a teammate's own turns, their Act as me work) in the list, by id and in a session, and the principal reads those as actions only — what was done, when and in whose conversation, with the text, details and `full` left out, and no text search over them; any other row's id is a 404, and a session shows only the rows the caller reads. |\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. Only `/health` is unauthenticated; `/health/honcho` sits behind the gate like everything else, because the exemption is an exact-path set. `/health` also carries `google_tools_missing`, the pinned Google tools startup priming could not find: `[]` once it has checked and they are all there, a list of names when a workspace-mcp rename or the configured services and tool tier left one out, and `null` for no answer — Google Workspace is not configured, or the probe has not finished or it failed. Only `[]` asserts they are present. It also carries `gateway`, the MCP gateway's state from its supervisor (`orchestrator.gateway_boot`): `state` is `off` (MCP not enabled), `no_servers` (enabled, the config names none), `starting` (an attempt is running), `up` or `down` (every attempt so far failed; `next_retry_at` is the next one), with `attempts`, `up_since` and `email_poller` (whether the poller that rides on the gateway runs); the failure's own text stays out, since the route is open to anyone, and goes to the log and the owner's notice on Home. A hosted instance whose gateway never came up used to answer `ok` here with no email going out or in. Only `[]` asserts the tools are present, so a probe that died cannot read as healthy; Setup status says which of the three `null` means. |\n| `version` | `GET /version` | The running version, the latest release on GitHub and `update_available`, for Settings → About. The GitHub answer is cached 6h, only a semver `tag_name` is used and the release link is built from it; `UPDATE_CHECK_ENABLED=false` skips the call and still returns the running version. No in-app updater: upgrading is host-side (`docs/deployment.md#upgrading`). |\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 mailbox (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. With `CONFLUENCE_SYNC_ENABLED` it bootstraps the `confluence_sync_scan` heartbeat the same way; that sync is run by hand with `openexecutive sync-confluence` / `purge-confluence`. 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\\|onedrive\\|notion}/sync`, `GET /documents/{drive\\|onedrive\\|notion}`, `GET /documents/{drive\\|onedrive\\|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`, `/documents/onedrive` and `/documents/notion` list synced files from the sync state (`{enabled, last_run, last_error, files: [{id, name, url, modified_at, synced_at, indexed}]}`; a Drive row also carries `unreadable_reason`, why a file with `indexed: false` has no text — e.g. a scan OCR could not read — or null); `/documents/{drive\\|onedrive\\|notion}/{id}` returns the stored text (a OneDrive id is `<drive id>:<item id>`) 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 (every sync holds 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`, `GET`/`PUT /executive/outside-content` | 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, name}` — `held_actions` counts due `pending` rows that fire on resume, and `name` is the Executive's name (`EXEC_DISPLAY_NAME`), which the web chat shows over its replies. `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. `GET /executive/outside-content` returns `{mode, channels, channel_ids, can_change}` for the owner's safety level, \"When should I check with you?\" (`ask` Careful, `outsiders` Balanced or `trust` Hands-off; `orchestrator.outside_mode`): `channels` maps each channel set apart to its own level, and `channel_ids` lists the channels a level can be set on. `PUT` with `{mode, channels?}` changes it for the principal only (403 otherwise; an unknown channel or level is a 422): a channel given a level is set apart, one given `null` follows `mode` again, and channels left out keep theirs. A change writes an `outside_content_mode_changed` audit row. |\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/describe`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. `POST /watchlist/describe` `{text}` drafts a watch from a sentence (one forced tool call on the utility-fast model, `monitoring.describe`; the company profile's name, competitors, vendors and tickers ride in the user turn) and saves nothing: it returns the create fields (`slug`, `signal_type`, `target`, `display_label`, `trigger`, `cadence`, `mode`, `severity_floor`, `severity_ceiling`, `notes`) plus four plain lines (`watching`, `tell_you_when`, `how_often`, `how_loud`) written by code from those fields, after the create route's checks (registered kind, cadence, severity, the URL guard, the rss feed check, a free slug); 422 with a plain reason when it can't be a watch, 429 past 30 drafts an hour, 502/504 when the model fails. `GET /watchlist/{slug}` also returns `noise` `{recent_alerts, recent_dismissed, noisy}` (its last 8 alerts, noisy at 6 dismissed, `monitoring.noise`), and `PATCH` takes `quiet_noise_nudge: true` to stop that question for the alerts so far. `display_label` on create maps to the adapter's label key for every kind. 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`, `POST /workflows/runs/{run_id}/rerun`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. A workflow with a step that sends email as its creator (`oe__send_email_as_me`) or reads their mail or calendar (`oe__search_my_email` and the other reads, `delegation.workflow_reads`) can be created, changed (`PUT`, save-edit) or switched on (`activate`) only by that creator, verified as Send on a reply card is; anyone else gets a 403 (`delegation.workflow_email.save_refusal`), as does a save of one that reads and also lists a tool a run may not use after reading mail. `POST /workflows/{name}/runs` answers 403 to anyone but the creator of a workflow that reads their mail. `rerun` queues a failed scheduled run (a department check-in, a saved workflow on a cadence) once more, due now (see Scheduler); the principal may, and for a saved workflow the person it delivers to; 409 for a run that did not fail, one started from `/jobs` (\"Start this one again from its page\") or one already queued again. 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. A run started by hand (this endpoint, or `run_workflow` / research in chat) records its starter as `owner_person_id` and is theirs alone: `GET /workflows/runs` lists the team's (scheduled, no owner) runs plus the caller's own and the ones waiting on them, and `GET` / `DELETE /workflows/runs/{run_id}` and `POST /workflows/runs/{run_id}/decision` are a 404 for anyone else's, the principal included. A signed-in email that is on nobody's People entry cannot start one (403), and a run whose starter can't be read is refused (503); its steps read and draft documents as the starter only. `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`, `background` (true for the system-run built-ins the UI files under “System”) and `quick` (true for a Quick workflow, one per playbook nothing else follows, named `quick_<playbook>`). 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| `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). Peer memory is each person's own: the overview holds only the caller's entry (none for a caller off the roster; `conclusion_total` counts only theirs), the principal included, and `/conclusions` for anyone but the caller 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/understand`, `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/revise`, `/onboard/interview/{id}` (GET resumes, DELETE starts over), `/onboard/interview/commit` | Conversational company setup. `understand` and `start` take multipart `description`, optional `files` and an optional `website` the server reads itself (a non-address is a 422; an unreadable site is no pages, never an error); `start`'s response lists the pages read in `website_pages`, and the draft's profile carries `website`. The `onboarding_interviewer` agent asks up to four quick questions (a question response carries `question_options`, suggested answers to tap), then emits a draft profile + people + `draft_goals` (each `{title, target, owner_name, department_title}`) + departments only when the user listed people by department. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). `revise` changes one earlier answer (0 = the description) and runs the interview again from there. `commit` takes the reviewed `goals` too (422 when one names a person or department not in the draft) and saves them with owners, additively. It 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/edit`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard, and editing a saved workflow by conversation. `/edit` (`{name}`) opens a session on a saved custom workflow with no model call: the stored definition is the starting draft, and every response then carries `editing` (its name) and `original` (the stored definition as the session opened on it); drafts keep that name and its on/off state whatever the model writes (404 for an unknown workflow). The UI saves one with `POST /workflows/custom/{name}/save-edit` (`{session_id, definition}`): the server saves the session's own draft, never a client-sent body, and only when it equals the `definition` the user reviewed (a later message is a 409, so the click saves only what was shown); it re-validates it, keeps the stored on/off state, and writes only if the stored workflow is still the version the conversation opened on — otherwise 409, as it is for a session about another workflow or one with nothing drafted yet. It sits under `/workflows/custom` so anything that limits writes to custom workflows covers it too. 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| `python_jobs` | `GET /python-jobs/{job_id}/{name}` | A result file a Python job (`run_python_job`) wrote, the principal's alone (403 otherwise), served as a download (`Content-Disposition: attachment`, `Content-Security-Policy: sandbox`, `nosniff`, `Cache-Control: no-store`); 404 for a bad id or name or a file past its 7 days. |\n| `saved_tools` | `GET /saved-tools`, `GET\\|PUT /saved-tools/{name}`, `POST /saved-tools/{name}/rollback` | The scripts the Executive saved as tools (Settings → Advanced → Saved tools), the owner's alone (403 otherwise). The list gives each tool's name, description, on/off, current version, `kind` (`script` or `python`, a kept Python job) and the tools it calls, plus whether `SAVED_TOOLS_ENABLED` is on; the detail adds the script, every version and the last 20 runs. `PUT {enabled?, workflows?, version?}` turns one on or off (off also turns it off for workflows, so turning it back on never re-arms unattended runs), and turns the named `version` — the one the owner looked at, never whatever is current by then — on for workflows (or workflows off); a Python tool never turns on for workflows (409) — turning workflows on lets more run unattended, so it needs a request tied to the owner (signed sign-ins or local login, as Take the lead's switches do; 409 otherwise); `rollback {version}` makes that version the one that runs. Both are audited as `saved_tool_changed`. The Executive saves tools itself through `run_script`; there is no create route. |\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| `auth` | `GET /auth/me` | `{email}`: the email the request is made as (`api.caller`, lowercased; `\"\"` when it names no one), nothing more. On the host list, so a host's own screens can warn when the session signed in here is someone else's. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. `POST /fixtures/reset` leaves no departments, like a new install (`departments_seeded` is always 0). |\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`, `POST /webhook/slack` | Inbound integration callbacks (self-verified). `/webhook/slack` answers 503 unless `SLACK_SIGNING_SECRET` is set. |\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, answered as the verified caller (`api.caller`) by the web app's rules. See the MCP Server section. | A card the Executive left for something asked in chat (`app_action`, `orchestrator/app_control.py`) is its person's alone too: its payload holds `action`, `id`, `value`, `title` and the `card` line shown; **Confirm** is `POST /decisions/{id}/approve`, which runs the action through the route its button calls with that request (a refusal comes back as that route's status and words, and the card is marked `failed`), and a card older than a day is turned down with 409.\n\n**What it does for you** (`api/routes/may_do.py`): `GET /what-it-may-do` is read-only. It returns `{paused, sections}`, three sections in order (`as_you`, `executive`, `departments`), each `{key, title, available, unavailable, notes, rows, footer, goes}`, and each row `{id, what, outcome, then, why, setting, items}`: `outcome` is `goes`, `waits`, `always_waits`, `drafts` or `off`, and `setting` names where to change it (`act_as_me`, `handle_it`, `take_the_lead`, `pause`, `department:<slug>`, or empty). `as_you` is the caller's own (`available` false, with why, when they can't have Act as me); `executive` is the principal's alone (`available` false for anyone else); `departments` is everyone's. Any team member on People may call it; a contact, someone not on People, or a request with no caller outside local login gets 403. See Delegation → What it does for you.\n\n**How far it goes as you** (`api/routes/delegation.py`): `PUT /delegation/reach` takes `{step}`, one of `off`, `when_asked`, `inbox`, `careful`, `balanced`, `bold`, `everything`, and answers the caller's delegation state as `GET /delegation` does. Going down turns the switches above the step off, highest first; going up runs each switch's own route in order (`PUT /delegation`, `PUT /delegation/inbox`, `PUT /delegation/handle-it`, `PUT /delegation/take-the-lead`), so the first refusal (409 `gmail_not_connected`, a signed sign-in missing, `in_training`, 403 for Everything when not the owner) stops it at a whole step. See Delegation → How far it goes as you.\n\n**Take the lead** (`api/routes/take_the_lead.py`): `GET /take-the-lead` returns the As the Executive switch, its six Ask first switches (`{kind, label, hint, on}`, the hint a plain line on what each one catches), the company's rules, whether this server can tie a change to the owner (`available`), and whether the Executive is paused. `PUT /take-the-lead` takes `{enabled?, ask_first?}`, and `POST /take-the-lead/rules` / `DELETE /take-the-lead/rules/{id}` add or remove a company rule (`{kind: person|domain|words|amount, value}`, 422 on a bad one). All four are the principal's alone (403). Anything that lets more happen on its own (turning it on, turning an Ask first off, removing a rule) needs a caller the API can tie to them (`delegation.verified.caller_refusal`, else 409). `GET /today/activity` adds `took_the_lead` rows (what Take the lead did, named, not quoted) and, for the caller alone, `sent_as_you` rows for what Handle it for me sent as them (and the meeting invites it accepted as them, \"Accepted Dana's Pilot review, Wed 21 Oct, 14:30\") and, for the principal, one `contacts_kept` row a day the contact keeper changed something (`detail` like \"2 added, 1 updated\"). Under `/delegation`: `PUT /delegation/take-the-lead {enabled}` is Take the lead as you (the owner's only for now; turning it on turns Handle it for me on), and `GET|POST /delegation/take-the-lead/rules` and `DELETE …/rules/{id}` manage the caller's own rules. `HandleItOut` gains `lead` and `lead_available`. A `take_the_lead_action` decision is approved or rejected through the existing `/decisions/{id}/approve|reject`. Training: the response also carries `training` (In training: everything waits unless allowed), `learned` (`{id, label, feature, example, uses, created_at}`: what it was allowed, the edit kept as an example by field) and `suggested` (`{key, label, approvals}`); `PUT` takes `training?` too, and leaving training while on needs the same provable owner as turning it on. `POST /take-the-lead/learned {key}` allows a current suggestion (404 for anything else; provable owner), `DELETE /take-the-lead/learned/{id}` makes it ask first again. `learned` also lists the owner's own Act as me senders (`feature` `act_as_me`), never anyone else's, and Remove works on those too. On a `take_the_lead_action` card, `POST /decisions/{id}/approve` takes `edits.input` (the card's editable fields, 422 for any other; the principal's alone, 403 for an area approver) and `edits.allow: true` (a training card only, 422 otherwise; the principal from a provable request, 403 otherwise), finishing `approved_with_edit` when a field changed.",
"mermaid": null,
- "generated_at": "2026-10-27T19:45:00Z"
+ "generated_at": "2026-10-27T21:31:05Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
index ffb5e6a1..4619f510 100644
--- a/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
+++ b/packages/core/openexecutive/architecture/prebuilt/lifecycle.json
@@ -1,7 +1,7 @@
{
"section_id": "lifecycle",
"title": "Request Lifecycle",
- "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn opens with a `<current_time>` hint: the day, date, time and zone in the workspace's timezone (`workspace_settings.get_user_timezone`, as the briefs use), so relative dates resolve against today instead of a guess; it is in the user turn because it changes every turn. It carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section — and a `<lessons>` block when a lesson the conversation review learned from a miss matches the message, `memory/lessons.py`; see the memory section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). A `<pending_followups>` block lists, for a verified speaker, the follow-ups they scheduled that haven't gone out (up to 10, from `correction_tools.pending_followups_block`, the same ownership rule as `list_followups`), and asks the Executive to cancel one with `cancel_followup` when the message shows it is already done or no longer needed, and say so in a line. The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10), with a short placeholder user turn first when that history opens with the Executive's own message (a chat-app conversation can start with a brief or digest it sent) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text. The history is re-read from the stored transcript at the start of every web turn, so a chat continued in a chat app and then reopened on the web or phone includes the turns the app added.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Each round's text starts a new paragraph after the text streamed before it (`executive._round_separator`), so words the model writes before a tool call never run into its answer; nothing it writes is dropped. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n **Do what it says.** Before the turn ends, its last reply is checked against the tool calls the turn made (`orchestrator/claim_check.py`). A reply with no word that can claim a change (\"done\", \"removed\", \"I'll remind you\"…) ends the turn as before. Otherwise one small forced-tool call on `ROUTING_MODEL` reads the person's message, the reply and each call with the start of its result, and reports a claim of a change no call made (or put up for approval). The claim must appear word for word in the reply, or it is ignored. The loop then gets one more round with a note in the user turn (never a cached block): make the change with the right tool, or say plainly it isn't done. Once a turn; a failed check lets the reply through. On the web chat the extra round streams after the first reply, separated by a blank line; chat apps send the whole reply at once. `CLAIM_CHECK_ENABLED` turns it off.\n **A chat several people are in.** When its owner shared a web chat (`session_shares`), every turn in it is labelled: the history is re-read with each person's message starting `[Name]: `, the current message too, and a note naming everyone in the chat rides in the user turn (`channel_context_block`, never a cached block). The Executive answers whoever wrote the latest message. Such a session is no private conversation (`Session.shared_chat`): Act as me is off there (`delegation.settings.private_conversation`), open loops are not listed as on a private surface, no one's mail is read there, the principal's included (`teammate_mail._reader_id`), what the Executive remembers about the speaker (peer memory) is not fetched, the alert digest leaves out the principal's private cards and roster requests (`briefing.context.render_and_trust`), and the principal-only tools are withheld whoever speaks (`content_trust.principal_only_withheld`), because the others write into what the principal's turn reads. A message that starts like a label (`[Alex]: …`) loses it before its sender's own goes in front. Peer memory still records each person's own words. Turns stay one at a time under the conversation's lock; the route publishes each one to the chat's live stream (`api.chat_live`) as it runs, so everyone else in the chat watches it happen. A chat of one publishes nothing.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. A verified speaker's turn is also kept for the **conversation review** (`memory.chat_review`, see Memory), which reads it once the chat has been quiet 30 minutes and fixes what the replies left undone, from the speaker's own quoted words. A turn that touched their mailbox, which teaches no other memory, is kept too, for their own review only (`record_turn(mail=...)`: tools by name, no results), with the words they typed rather than the blanked text the other passes get. A replay turn is never kept. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. While nothing else is going out — a slow tool call, a long specialist round — the route sends an SSE comment (`: keepalive`) every `CHAT_STREAM_KEEPALIVE_S` (15 s by default, 0 for none) so a browser or proxy does not drop the connection as idle; the step it waits on keeps running across it, and the whole-turn deadline is unchanged. Every call through the MCP gateway (Gmail, Calendar, Drive, Outlook, OneDrive, tool search) has its own ceiling, `MCP_TOOL_TIMEOUT_S` (120 s): past it the model gets an error saying the tool did not answer and may still have run, so it checks before calling again, and no outbound linkage is recorded for a send that timed out. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant. None of this runs for a **replay** of a graded turn (`Session.replay`, `memory/replay.py`): the loop answers its acting tools with \"done\" and records them on the session, offers no script, job or server load, and skips every post-turn pass, so the nightly replay of the misses changes nothing and reaches nobody. On a team member's turn (`department_gate.speaker`) it also refuses an alert that is not routed to them (`routed_to_person_id`), so they clear only their own items; the principal clears anything on the board. `create_alert` on such a turn ignores the `source`, `external_id` and `from_address` it was given: the alert gets the source `team_member`, a fresh id and `raised_by` (their name), so it can't pose as mail or a watch, coalesce into one, or pre-claim the id a real alert will arrive with.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.\n\n### Tracing\n\nSet `LOGFIRE_TOKEN` and every step above becomes visible as one Pydantic Logfire trace (`openexecutive.observability`): the `POST /chat` request span, a `messages.create` / `messages.stream` span per model call with its token and prompt-cache counts, a `specialist {name}` span per fan-out branch (siblings overlap, so the slowest one sets the turn's critical path), and a `knowledge retrieve` span per RAG query. Scheduler and workflow model calls appear as their own root traces. Traces record timings, model names and usage only — prompt and reply text, request bodies, path parameters (each request URL is reduced to its route template), query strings, client identity and exception messages (errors are recorded by type) never leave the process, and incoming trace headers are ignored. With the token unset, tracing is off and `get_provider()` returns the bare backend.",
+ "markdown": "A single chat message makes a full round-trip through the API, the orchestrator's tool-use loop, a parallel specialist fan-out, and synthesis — all streamed back as server-sent events.\n\n### Steps\n\n1. **Arrival** — the client mints a `client_turn_id` and posts to `POST /chat` (`openexecutive.api.routes.chat`). The turn opens with a `<current_time>` hint: the day, date, time and zone in the workspace's timezone (`workspace_settings.get_user_timezone`, as the briefs use), so relative dates resolve against today instead of a guess; it is in the user turn because it changes every turn. It carries a `<current_speaker>` hint resolved from the caller's `person_id` (followed by that person's `<working_style>` rules when they have any — see the attunement section — and a `<lessons>` block when a lesson the conversation review learned from a miss matches the message, `memory/lessons.py`; see the memory section), plus a `<briefing>` digest of current open alerts (built in parallel with RAG/episodic/peer-memory fetches) so the Executive can discuss any item shown on the `/today` briefing page. A turn arriving from a chat adapter instead of the web app also carries a `<channel>` block naming the surface and stating which approvals can be completed there; on Slack the `<briefing>` digest is gated to the principal's DMs. All three ride in the **user turn**, never a cached system block, as does a `<drive_memory>` block naming the Drive files this conversation already found or opened and the Drive searches that matched nothing (see the memory section). A `<pending_followups>` block lists, for a verified speaker, the follow-ups they scheduled that haven't gone out (up to 10, from `correction_tools.pending_followups_block`, the same ownership rule as `list_followups`), and asks the Executive to cancel one with `cancel_followup` when the message shows it is already done or no longer needed, and say so in a line. The server registers a stop switch under that id *before* the context fetch, so a Stop pressed during those first seconds halts the turn before any model call is made.\n2. **Tool-use loop** — the `Executive` calls Claude. For a cross-domain question the assistant turn emits multiple `consult_specialist` tool-use blocks at once. The call carries the conversation so far (`Session.get_recent_history`: 20 to 30 turns, its start moving in steps of 10), with a short placeholder user turn first when that history opens with the Executive's own message (a chat-app conversation can start with a brief or digest it sent) with a 1h cache marker on the previous reply, so each message reads the earlier conversation from the prompt cache and writes only what is new (see Caching); on the OpenRouter path the translator keeps that marker on the reply's text. The history is re-read from the stored transcript at the start of every web turn, so a chat continued in a chat app and then reopened on the web or phone includes the turns the app added.\n The person can keep typing while it works. A message sent then (`POST /chat/add`) joins the running turn: the loop adds it after the next round's tool results, so the answer follows it, and it is saved as its own message before the reply. One that arrives while the final answer is being written becomes the next turn instead. A conversation runs one turn at a time.\n3. **Parallel fan-out** — `openexecutive.orchestrator.router.route_parallel` dispatches those calls concurrently, bounded by `MAX_PARALLEL_SPECIALISTS`; calls past the cap get a skip tool_result. A specialist that raises (a timeout, an overloaded model) or returns no text no longer fails the batch: its tool_result says it is unavailable and tells the Executive not to invent its view, the others' results stand, and the turn goes on. It does not count as consulted, so it takes no committee seat and no department memory records the turn, and its documents are left out of the answer's sources. On the web chat the reply need not mention the gap, because the app shows it under the answer; on every other channel the tool_result asks the Executive to say in one sentence that part of the analysis is missing. A knowledge retrieval that fails likewise leaves that specialist without context rather than failing the turn.\n4. **Per-specialist RAG** — each specialist runs its own domain-filtered ChromaDB query, then reasons over the retrieved chunks and returns analysis as a tool_result. Its user turn also carries a `<company_stage>` tag from the session's company profile, so stage-sensitive advice (venture benchmarks vs. cash-first for a bootstrapped company) does not depend on the Executive remembering to mention it. Once the batch is done, the documents each answering specialist's retrieval returned are named, in call order, into the turn's `TurnSources` (`orchestrator/answer_sources.py`), which the web chat route owns and which also holds its own search's documents. Synced Google Drive files are recorded as `drive` sources with their Drive link, and the web chat lists them under **Google Drive**.\n5. **Synthesis** — the Executive feeds the tool_results back to Claude and streams one coherent reply. Each round's text starts a new paragraph after the text streamed before it (`executive._round_separator`), so words the model writes before a tool call never run into its answer; nothing it writes is dropped. Every tool round — not just a specialist one — emits an `activity` event naming what is running, immediately followed by a `thinking` keepalive. The label names the *activity*, never the internal agent: \"Putting time on the calendar…\", \"Looking up people…\", or, for a connected (MCP) tool, plain words for what it does (\"Searching Drive…\"), from the same table (`orchestrator/tool_labels.py`) that names the finished chip (\"Searched Drive\"). The raw `server__tool` name never reaches the user. Under the reply, repeats of the same action collapse into one chip with a count, and tapping it lists what each run looked at. A round that really does fan out collapses to the generic \"Consulting specialists…\" — the one voice holds even in the progress line. The keepalive carries no tool information of its own; it used to drive a hardcoded \"Consulting specialists…\" string, so an MCP or calendar round misreported itself as a fan-out.\n **After pushback.** Before the loop starts, `orchestrator/pushback.py` decides whether this message pushes back on the last answer: a 👎 on the chat's last saved reply (or a typed \"thumbs down\" / 👎), words that say it missed (\"that's not what I asked\", \"why can't you\", \"try again\"), the same ask as the last message (≥16 chars, ≥0.85 similar), or a `claim_check` audit row between the last message and its reply. If so and a pushback model is set (the Executive's Council pick, else `PUSHBACK_MODEL`; empty or `off` = off) and differs from the normal one, this one turn runs on it, with a `pushback_model` audit row (reason + model). The next turn goes back to the normal model. Word matching and reads of rows the chat already wrote only, so no model call; it fails open. The model switch writes that model's prompt cache once, so an escalated answer costs that model's cold first call.\n **Do what it says.** Before the turn ends, its last reply is checked against the tool calls the turn made (`orchestrator/claim_check.py`). A reply with no word that can claim a change (\"done\", \"removed\", \"I'll remind you\"…) ends the turn as before. Otherwise one small forced-tool call on `ROUTING_MODEL` reads the person's message, the reply and each call with the start of its result, and reports a claim of a change no call made (or put up for approval). The claim must appear word for word in the reply, or it is ignored. The loop then gets one more round with a note in the user turn (never a cached block): make the change with the right tool, or say plainly it isn't done. Once a turn; a failed check lets the reply through. On the web chat the extra round streams after the first reply, separated by a blank line; chat apps send the whole reply at once. `CLAIM_CHECK_ENABLED` turns it off.\n **A chat several people are in.** When its owner shared a web chat (`session_shares`), every turn in it is labelled: the history is re-read with each person's message starting `[Name]: `, the current message too, and a note naming everyone in the chat rides in the user turn (`channel_context_block`, never a cached block). The Executive answers whoever wrote the latest message. Such a session is no private conversation (`Session.shared_chat`): Act as me is off there (`delegation.settings.private_conversation`), open loops are not listed as on a private surface, no one's mail is read there, the principal's included (`teammate_mail._reader_id`), what the Executive remembers about the speaker (peer memory) is not fetched, the alert digest leaves out the principal's private cards and roster requests (`briefing.context.render_and_trust`), and the principal-only tools are withheld whoever speaks (`content_trust.principal_only_withheld`), because the others write into what the principal's turn reads. A message that starts like a label (`[Alex]: …`) loses it before its sender's own goes in front. Peer memory still records each person's own words. Turns stay one at a time under the conversation's lock; the route publishes each one to the chat's live stream (`api.chat_live`) as it runs, so everyone else in the chat watches it happen. A chat of one publishes nothing.\n6. **Optional committee review** — when enabled, `Executive.stream_chat_with_committee()` runs a silent draft, parallel reviewer critiques, then a streamed revision pass.\n7. **Side effects** — after the reply, every rostered speaker's turn (not only the principal's) schedules a fire-and-forget **open-loop pass** (Attunement) beside the episodic extraction: a keyword prefilter, then one forced-tool call that may open or close loops, every item quote-gated against the speaker's own words. A verified speaker's turn is also kept for the **conversation review** (`memory.chat_review`, see Memory), which reads it once the chat has been quiet 30 minutes and fixes what the replies left undone, from the speaker's own quoted words. A turn that touched their mailbox, which teaches no other memory, is kept too, for their own review only (`record_turn(mail=...)`: tools by name, no results), with the words they typed rather than the blanked text the other passes get. A replay turn is never kept. The user message is persisted with `sender_person_id` — the resolved speaker, never the principal fallback a Discord / Telegram session uses for ownership — and the session records the speaker for the turn (`Session.caller_person_id`), which `close_open_loop` reads. A DM sent while proactive work is tagged (`attunement.outcomes.tag_proactive` — scheduler dispatch, reflection, research, alert review) also opens an outcome-ledger row at `_record_outbound_context`; a user's own turn is never tagged. A tagged DM is also subject to the recipient's own notification settings: in their quiet hours, or when they chose *In my briefs*, the send handler stores it (`outbound_guard.check_hold`, `people.held_messages`) and returns `{\"status\": \"held\"}` instead of sending (see Org). Any side-effecting tool call surfaces an `action_taken` chip, which unlike the ephemeral `activity` label is persisted with the assistant message; once the reply is over — also when it was stopped or timed out — the web chat route sends one `sources` event: the documents and web pages the turn looked at (its own search, each specialist that answered, web search results, and the pages the reply cites, which are always kept) and the areas (\"finance\", never a specialist) it had to go without. The web chat shows it under the reply, and it is persisted with the assistant message as `chat_messages.sources`; other channels don't collect it. The stream closes with a `done` event — preceded by a `stopped` event when the user halted the turn, in which case the partial reply is still persisted and flagged so it reads as cut short rather than complete, and is mirrored into the live in-memory session so the next turn's prompt matches what was saved. The stream still ends with `done` event. While nothing else is going out — a slow tool call, a long specialist round — the route sends an SSE comment (`: keepalive`) every `CHAT_STREAM_KEEPALIVE_S` (15 s by default, 0 for none) so a browser or proxy does not drop the connection as idle; the step it waits on keeps running across it, and the whole-turn deadline is unchanged. Every call through the MCP gateway (Gmail, Calendar, Drive, Outlook, OneDrive, tool search) has its own ceiling, `MCP_TOOL_TIMEOUT_S` (120 s): past it the model gets an error saying the tool did not answer and may still have run, so it checks before calling again, and no outbound linkage is recorded for a send that timed out. One side-effecting tool is gated server-side rather than by its description: `ack_alert` will only accept an `alert_id` from the live alert board the server itself derived this turn — the whole live set, not only the rows the `<briefing>` digest printed, since `/today` renders more cards than the digest lists and every one of them is Discuss-able — and it fails closed, so an id it cannot even parse is refused rather than waved through to the handler's own parse. That check runs on **every** session. It used to run only on turns that arrived from a chat channel, keyed on `origin_channel`, which the browser never sets — so the web, the surface the principal actually uses, was unchecked and the model could ack any id, including one quoted out of an alert body by the briefing page's Discuss handoff. What that buys is bounded and worth stating plainly: an id that is invented, closed, snoozed or expired is refused, including one quoted out of an attacker-written alert body; the model being argued into acking the wrong *live* card is not prevented. The one way to widen that set is `find_alerts`, for an item the principal names that has left the live board (already opened, snoozed, older than the board): a keyword search over alerts of every status whose own results — never an id the model supplies — join the trusted set. It runs only in a turn where `render_and_trust` showed the principal their own board (`Session.principal_board_shown`: the verified principal, and on a channel only in their DM), never merely because the session has a set — every `Session` starts with an empty one, and that empty set is how a Google Chat turn, someone else's DM or an unattended pass refuses every ack — and not on the principal's turn in a shared Slack or Discord thread either, where others read the reply and write into what the model reads. It trusts only rows still open (`unread`, `read`), never a roster-request card, and at most 25 ids per turn across calls, and refuses a query with no word of three or more letters. It also moves the admitted limit outward: a model argued into the wrong search can now reach up to 25 open alerts that are off the board, not only live ones. The board is recorded on the turn's `Session`, and the route binds that session for the **whole** SSE body (`schedule_tools.set_session`, alongside `set_turn`) rather than letting `stream_chat` bind it from inside its own generator. `_sse_body` drives the executive with `asyncio.wait_for(stream.__anext__())`, which runs each step in a fresh Task holding a *copy* of the context, so a binding made inside the generator is discarded with the step that made it: step one sees the session and every later step sees `None`. The tool-call loop runs on those later steps, so the whole guard read an empty set and refused every ack on the web — on live, open cards — until the binding moved out to the route. Anything reading `current_session` mid-turn has the same requirement, and two of them needed more than the binding to behave. `schedule_followup`'s seen-`channel_ref` anti-spam gate refuses a send to an address the session has not seen; with no session it skipped itself, so a web turn could schedule to **any** address, and with an empty one it refused even the principal's own. The route now seeds the caller's own addresses onto the session, so on web the gate means what it means on every other surface. Reply linkage (`_record_outbound_context`, read back by `inbound_hydration` to quote the originating conversation into the turn handling a recipient's reply) is the other: it was never reachable on web, and rather than switch that on for the principal's broadest surface as a side effect it is held back, keyed on an explicit `Session.from_web_chat` flag. Not on an empty `origin_channel` — alert review, the CLI and the unattended workflows all leave it empty while legitimately recording linkage, as does the email poller under its own `email` tag. `scheduled_actions` rows also take their `session_id` from the session. A session that was shown no board has an empty trusted set and can ack nothing, so the unattended passes (the nightly reflection, the research synthesis) are refused by default — they also still withhold the tool outright, which is belt-and-braces rather than the only thing stopping them. After the stream closes, the turn is also handed to the episodic memory extractor (`memory.episodic.schedule_extraction`, fire-and-forget) — on every turn where the principal said anything at all, and only the principal: a turn naming an `origin_channel` must resolve to a person marked `is_principal`, because the quote validator downstream cannot tell whose words it is checking. Both this path and the committee path call the same `should_extract` predicate, and it applies no length floor: the gate used to sum in the assistant's reply, which let a verbose answer drag a trivial turn in and discarded the short, decisive instructions that are the whole point of extracting. A user-side floor would fare no better — \"Do B.\" and \"Done\" are one character apart. See **Memory** for what that cost on a live tenant. None of this runs for a **replay** of a graded turn (`Session.replay`, `memory/replay.py`): the loop answers its acting tools with \"done\" and records them on the session, offers no script, job or server load, and skips every post-turn pass, so the nightly replay of the misses changes nothing and reaches nobody. On a team member's turn (`department_gate.speaker`) it also refuses an alert that is not routed to them (`routed_to_person_id`), so they clear only their own items; the principal clears anything on the board. `create_alert` on such a turn ignores the `source`, `external_id` and `from_address` it was given: the alert gets the source `team_member`, a fresh id and `raised_by` (their name), so it can't pose as mail or a watch, coalesce into one, or pre-claim the id a real alert will arrive with.\n8. **Tool failures** — a handler that raises instead of returning its JSON error is isolated: both tool gathers run with `return_exceptions=True`, the model gets an error `tool_result` naming only the exception's TYPE — a message can carry a filesystem path, a validation error echoing the input, or a third-party HTTP body, and anything in model context can be quoted back to the user, so the full repr stays in the log and the audit row — and the failure is audited with `ok=false`. Only `CancelledError` is re-raised, so turn-timeout and client-disconnect handling still work. Before this one crashing tool aborted the whole turn, which reached the user as an unexplained apology with no audit row (#136).\n\nWeb search, when invoked on the Anthropic path, executes inside the Anthropic API itself (`web_search_20250305`) and returns within the same generation; for any model routed via OpenRouter the same tool becomes OpenRouter's `openrouter:web_search` server tool, which also runs inside the generation with the same search cap and domain lists.\n\nThe install's workspace mode (solo or team, see Org) is read fresh at the start of each turn by `memory.workspace_settings.pin_turn_workspace_mode(session)` and pinned on the session for that turn only (`Session.turn_workspace_mode`): the persona, the org block, the tool list and every tool handler in the turn then agree, and a switch made mid-turn applies from the next turn. A session can instead carry an explicit override, `Session.workspace_mode` (`None` by default), which wins over both — so a caller that runs many conversations concurrently on one Executive, such as evals, can pick the mode per session rather than flipping the install-wide setting. Everything reads it through `effective_workspace_mode(session)` (override, then the turn's pin, then the setting). The principal's role is pinned the same way (`pin_turn_principal_role(session, mode)` → `Session.turn_principal_role`: in solo the `Session.principal_role` override, else the workspace settings read fresh; in team an empty role). The org block renders it, each specialist batch gets it as a `<principal_role>` user-turn tag, and a workflow the turn starts reads the same pin through `effective_principal_role` (override, then the pin, then the setting), so a role edited mid-turn applies from the next turn; a team turn sends none.\n\nAct as me is pinned beside them: `delegation.settings.pin_turn_delegation(session, speaker_text)` records on `Session.turn_delegation` whether the speaker has it on, whether `ghostwrite_email` is offered this turn (the principal, or a team member once the owner lets them, on a verified surface, in a conversation private to them, attended), and the speaker's own words. The pin is also held in a context variable for the turn's task, so two turns running at once on one session each read their own. The tool list, the tool handler and the turn's audit privacy all read that one pin, so a switch flipped mid-turn applies from the next turn. Once the tool touches the speaker's mailbox, the conversation is the speaker's alone (`session_store.mark_mail_private`, the principal included when it isn't theirs), the rest of the turn's audit rows are private (a team member's theirs alone) and the turn teaches no memory: no extraction, open-loop, working-style or Honcho pass runs on it. Later turns of that conversation stay private the same way; the pin also records whether the reading turn is still in the history the model is shown (`mail_in_view`, from `sessions.mail_read_at` against `session.history_window_start`), and links, scripts, workflows and posts to everyone stay withheld only while it is.\n\n### Tracing\n\nSet `LOGFIRE_TOKEN` and every step above becomes visible as one Pydantic Logfire trace (`openexecutive.observability`): the `POST /chat` request span, a `messages.create` / `messages.stream` span per model call with its token and prompt-cache counts, a `specialist {name}` span per fan-out branch (siblings overlap, so the slowest one sets the turn's critical path), and a `knowledge retrieve` span per RAG query. Scheduler and workflow model calls appear as their own root traces. Traces record timings, model names and usage only — prompt and reply text, request bodies, path parameters (each request URL is reduced to its route template), query strings, client identity and exception messages (errors are recorded by type) never leave the process, and incoming trace headers are ignored. With the token unset, tracing is off and `get_provider()` returns the bare backend.",
"mermaid": "sequenceDiagram\n participant C as Client\n participant API as FastAPI /chat\n participant E as Executive\n participant CL as Claude\n participant S as Specialists\n participant KB as ChromaDB\n C->>API: POST /chat message\n API->>E: start turn\n E->>CL: messages (tool-use loop)\n CL-->>E: consult_specialist calls\n E->>S: route_parallel fan-out\n S->>KB: domain-filtered RAG\n KB-->>S: chunks\n S-->>E: analysis tool_results\n E->>CL: synthesize\n CL-->>E: streamed reply\n E-->>API: SSE chunks then done\n API-->>C: streamed response",
- "generated_at": "2026-10-26T13:22:39.814989+00:00"
+ "generated_at": "2026-10-27T21:30:41Z"
}
diff --git a/packages/core/openexecutive/config.py b/packages/core/openexecutive/config.py
index dabbe683..3e309677 100644
--- a/packages/core/openexecutive/config.py
+++ b/packages/core/openexecutive/config.py
@@ -132,6 +132,13 @@ class Settings(BaseSettings):
# off) instead of Opus is the dominant cost lever for the workflow.
# Set RESEARCH_MODEL=claude-opus-5-5 to restore the prior behavior.
research_model: str = Field("claude-sonnet-5-5", alias="RESEARCH_MODEL")
+ # The Executive's model for the one answer after someone pushes back on
+ # the last one (a thumbs down, "that's not what I asked", the same ask
+ # again, or a reply the claim check caught); the answer after that goes
+ # back to the normal model (orchestrator.pushback). Empty = off, every
+ # answer on the normal model. The Executive's Council card can set its
+ # own pick, which wins over this.
+ pushback_model: str = Field("", alias="PUSHBACK_MODEL")
vector_store_path: Path = Field(_ROOT / "chroma_db", alias="VECTOR_STORE_PATH")
company_profile_path: Path = Field(
diff --git a/packages/core/openexecutive/guide/prebuilt/council.json b/packages/core/openexecutive/guide/prebuilt/council.json
index 5751d781..31f11ab3 100644
--- a/packages/core/openexecutive/guide/prebuilt/council.json
+++ b/packages/core/openexecutive/guide/prebuilt/council.json
@@ -1,7 +1,7 @@
{
"section_id": "council",
"title": "Agent Council",
- "markdown": "**What it is:** The settings page for the agents behind the Executive. You choose how thorough answers are, add instructions to any agent, and change each agent's model and prompt. Changes apply to everyone who uses this Executive.\n\n**What it does:**\n\n- **Quality** sets every agent's model and deep reasoning at once: **Fast**, **Balanced** or **Thorough**.\n- Add **Additional instructions** to any agent, such as \"Quote figures in EUR\".\n- Change an agent's role, model, deep reasoning, system prompt and research focus.\n- Write or edit voice personas for the Executive.\n- Test unsaved settings with a one-off question before you save.\n- Restore an earlier version, or reset an agent to its built-in settings.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Agent Council**.\n2. Pick a preset under **Quality**:\n - **Fast**: a small, fast model for every agent, with deep reasoning off.\n - **Balanced**: each agent's built-in model and deep-reasoning setting.\n - **Thorough**: 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.\n A confirmation asks first. Prompts and instructions are not changed, and the earlier settings move to each agent's history. A preset is greyed out when this install offers none of its models. If you change one agent's model by hand, a **Custom** badge appears next to **Quality**.\n3. Under **Your agents**, each card shows the agent's name, its area and a status line: the model name, **Custom ·** followed by the model name when its model differs from the preset, or **Has your instructions** when you changed its instructions, prompt, role or research focus. **Show all agents** adds the internal and helper agents. **Show fewer agents** hides them again.\n4. Click a card to open the agent in a side panel. It opens on **Additional instructions** (up to 4,000 characters). They are added after the agent's built-in prompt on every call, so the agent keeps getting updates to that prompt. Clear the box to remove them.\n5. Click **Save**. The change applies on the next message. **Cancel** drops your edits. Closing the panel another way with unsaved edits asks \"Discard your unsaved changes to this agent?\"\n\n**Advanced settings:**\n\nClick **Advanced settings** in the agent's panel to see every setting. The panel widens into tabs. Your browser remembers this choice for every agent. **Simple view** goes back, and unsaved edits carry over. The two helper agents that are only a model setting (the fast utility model and the research model) always open here.\n\n- **Model** tab: **Role** (its one-line job), **Model** (pick a provider, then a model; the agent's default is marked *(default)*), and **Deep reasoning** (slower, more thorough thinking; not available on Haiku models). The fast utility model has no deep-reasoning switch.\n- **Instructions** tab: the same **Additional instructions** box as the simple view.\n- **Prompt** tab: **System prompt**, the agent's full instructions. Editing it replaces the built-in prompt, so later updates to that prompt will not reach this agent. **Restore default prompt in editor** puts the original back. Specialists also have **Research focus**, the topics they watch in background research scans, with **Restore default research focus in editor**.\n- **Test** tab: under **Test this draft**, type a question and click **Run test**. It uses the unsaved settings in the tabs and saves nothing. The fast utility model has no Test tab.\n- **History** tab: earlier versions of the agent's settings. Click **Restore** on one to go back to it (a confirmation asks first).\n- The **⋯** menu at the bottom of the panel has **Reset to default**. It clears all your changes to that agent and moves them to its history. It is greyed out when the agent has no changes.\n\n**Voice:**\n\nPick the Executive's voice under **Voice** on **Settings → Your Executive**. The Council links there. To write your own voice, open the **Executive** card, click **Advanced settings** and go to the **Prompt** tab. In **Voice Persona**:\n\n- **Active persona** picks the voice. It is saved with the panel's **Save** button.\n- Edit the display name and **Persona body**, then click **Save persona**.\n- **Reset to built-in** undoes your edits to a built-in persona.\n- **Duplicate** makes a copy of the current persona and selects it.\n- **Delete** removes a persona you created (built-in ones cannot be deleted).\n- **+ New** asks for a display name and a persona body. Click **Create**.\n\n**Example persona body:**\n\n```\n- Direct and brief; lead with the recommendation, then the reasoning\n- Plain English, no jargon or buzzwords\n- Numbers over adjectives\n- End with the one decision you need from me\n```\n\n*Note: changes take effect on the next message. No restart is needed.*",
+ "markdown": "**What it is:** The settings page for the agents behind the Executive. You choose how thorough answers are, add instructions to any agent, and change each agent's model and prompt. Changes apply to everyone who uses this Executive.\n\n**What it does:**\n\n- **Quality** sets every agent's model and deep reasoning at once: **Fast**, **Balanced** or **Thorough**.\n- Add **Additional instructions** to any agent, such as \"Quote figures in EUR\".\n- Change an agent's role, model, deep reasoning, system prompt and research focus.\n- Write or edit voice personas for the Executive.\n- Test unsaved settings with a one-off question before you save.\n- Restore an earlier version, or reset an agent to its built-in settings.\n\n**How to use:**\n\n1. Open **Settings → Advanced → Agent Council**.\n2. Pick a preset under **Quality**:\n - **Fast**: a small, fast model for every agent, with deep reasoning off.\n - **Balanced**: each agent's built-in model and deep-reasoning setting.\n - **Thorough**: 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.\n A confirmation asks first. Prompts and instructions are not changed, and the earlier settings move to each agent's history. A preset is greyed out when this install offers none of its models. If you change one agent's model by hand, a **Custom** badge appears next to **Quality**.\n3. Under **Your agents**, each card shows the agent's name, its area and a status line: the model name, **Custom ·** followed by the model name when its model differs from the preset, or **Has your instructions** when you changed its instructions, prompt, role or research focus. **Show all agents** adds the internal and helper agents. **Show fewer agents** hides them again.\n4. Click a card to open the agent in a side panel. It opens on **Additional instructions** (up to 4,000 characters). They are added after the agent's built-in prompt on every call, so the agent keeps getting updates to that prompt. Clear the box to remove them.\n5. Click **Save**. The change applies on the next message. **Cancel** drops your edits. Closing the panel another way with unsaved edits asks \"Discard your unsaved changes to this agent?\"\n\n**Advanced settings:**\n\nClick **Advanced settings** in the agent's panel to see every setting. The panel widens into tabs. Your browser remembers this choice for every agent. **Simple view** goes back, and unsaved edits carry over. The two helper agents that are only a model setting (the fast utility model and the research model) always open here.\n\n- **Model** tab: **Role** (its one-line job), **Model** (pick a provider, then a model; the agent's default is marked *(default)*), and **Deep reasoning** (slower, more thorough thinking; not available on Haiku models). The fast utility model has no deep-reasoning switch. The Executive also has **Model after pushback**: when someone gives the last answer a thumbs down, says it's not what they asked, asks the same thing again, or the answer claimed something it didn't do, the next answer uses this model, and the one after goes back to the normal model. **Same as normal answers** turns it off.\n- **Instructions** tab: the same **Additional instructions** box as the simple view.\n- **Prompt** tab: **System prompt**, the agent's full instructions. Editing it replaces the built-in prompt, so later updates to that prompt will not reach this agent. **Restore default prompt in editor** puts the original back. Specialists also have **Research focus**, the topics they watch in background research scans, with **Restore default research focus in editor**.\n- **Test** tab: under **Test this draft**, type a question and click **Run test**. It uses the unsaved settings in the tabs and saves nothing. The fast utility model has no Test tab.\n- **History** tab: earlier versions of the agent's settings. Click **Restore** on one to go back to it (a confirmation asks first).\n- The **⋯** menu at the bottom of the panel has **Reset to default**. It clears all your changes to that agent and moves them to its history. It is greyed out when the agent has no changes.\n\n**Voice:**\n\nPick the Executive's voice under **Voice** on **Settings → Your Executive**. The Council links there. To write your own voice, open the **Executive** card, click **Advanced settings** and go to the **Prompt** tab. In **Voice Persona**:\n\n- **Active persona** picks the voice. It is saved with the panel's **Save** button.\n- Edit the display name and **Persona body**, then click **Save persona**.\n- **Reset to built-in** undoes your edits to a built-in persona.\n- **Duplicate** makes a copy of the current persona and selects it.\n- **Delete** removes a persona you created (built-in ones cannot be deleted).\n- **+ New** asks for a display name and a persona body. Click **Create**.\n\n**Example persona body:**\n\n```\n- Direct and brief; lead with the recommendation, then the reasoning\n- Plain English, no jargon or buzzwords\n- Numbers over adjectives\n- End with the one decision you need from me\n```\n\n*Note: changes take effect on the next message. No restart is needed.*",
"mermaid": null,
- "generated_at": "2026-10-15T21:00:00Z"
+ "generated_at": "2026-10-27T21:31:05Z"
}
diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.py
index 4641fe93..1676af93 100644
--- a/packages/core/openexecutive/orchestrator/executive.py
+++ b/packages/core/openexecutive/orchestrator/executive.py
@@ -50,6 +50,7 @@ from openexecutive.orchestrator import (
take_the_lead,
tool_groups,
)
+from openexecutive.orchestrator import pushback as pushback_mod
from openexecutive.orchestrator.action_card_tools import (
ACTION_CARD_TOOL_HANDLERS,
ACTION_CARD_TOOLS,
@@ -885,6 +886,44 @@ def _artifact_row_owner(tool_name: str) -> int | None:
return current_viewer().person_id
+def _pushback_for_turn(
+ settings: Any, session: Session, text: str, normal_model: str
+) -> pushback_mod.Pushback | None:
+ """The pushback model for this turn, when the person pushed back on the
+ last answer (``orchestrator.pushback``). The Executive's Council pick
+ wins over ``PUSHBACK_MODEL``. None runs the turn on ``normal_model``."""
+ try:
+ from openexecutive.agents.overrides import EXECUTIVE_AGENT_ID, get_override
+
+ ov = get_override(EXECUTIVE_AGENT_ID)
+ return pushback_mod.for_turn(
+ session_id=session.session_id,
+ text=text,
+ history=session.conversation_history,
+ normal_model=normal_model,
+ override_pick=ov.pushback_model if ov is not None else None,
+ default=getattr(settings, "pushback_model", "") or "",
+ )
+ except Exception:
+ logger.warning("pushback: couldn't pick the turn's model", exc_info=True)
+ return None
+
+
+def _log_pushback(
+ pushback: pushback_mod.Pushback | None, session: Session, turn_id: str
+) -> None:
+ if pushback is None:
+ return
+ audit_log(
+ "pushback_model",
+ f"Pushback on the last answer ({pushback.reason}); this answer on {pushback.model}",
+ session_id=session.session_id,
+ turn_id=turn_id,
+ actor="executive",
+ details={"reason": pushback.reason, "model": pushback.model},
+ )
+
+
def _speaker_text(memory_text: str | None, user_message: str) -> str:
"""The speaker's own words for this turn, which every post-turn pass reads
instead of the prompt — episodic extraction, open loops and peer memory:
@@ -1362,6 +1401,12 @@ class Executive:
)
except Exception:
logger.exception("Failed to load executive override; using defaults")
+ # Pushback on the last answer: this one answer on the pushback model.
+ pushback = _pushback_for_turn(
+ self._settings, session, _speaker_text(memory_text, user_message), effective_model
+ )
+ if pushback is not None:
+ effective_model = pushback.model
# Solo / team, resolved once per turn and pinned on the session, so the
# persona, the org block, the toolkit the loop offers and every tool
# handler agree even if the setting flips mid-turn (Session override →
@@ -1406,6 +1451,7 @@ class Executive:
t0 = time.monotonic()
full_response = ""
with set_turn(session_id=session.session_id, turn_id=turn_id):
+ _log_pushback(pushback, session, turn_id)
# Per-person prefetch from Honcho. Runs once per turn (NOT inside
# the tool-call loop) so a long multi-tool turn doesn't accrue
# multiple round trips. The wrapper enforces a hard timeout and
@@ -1732,6 +1778,12 @@ class Executive:
)
except Exception:
logger.exception("Failed to load executive override; using defaults")
+ # Pushback on the last answer: this one answer on the pushback model.
+ pushback = _pushback_for_turn(
+ self._settings, session, _speaker_text(memory_text, user_message), effective_model
+ )
+ if pushback is not None:
+ effective_model = pushback.model
workspace_mode = pin_turn_workspace_mode(session)
principal_role = pin_turn_principal_role(session, workspace_mode)
@@ -1778,6 +1830,7 @@ class Executive:
# refactor adds a raising step in this window, wrap that step in
# try/finally with clear_turn() or migrate to `with set_turn`.
bind_turn(session_id=session.session_id, turn_id=turn_id)
+ _log_pushback(pushback, session, turn_id)
# Per-person prefetch from Honcho (see stream_chat for rationale).
# Skip when caller pre-resolved (e.g. parallel context fetch in route).
diff --git a/packages/core/openexecutive/orchestrator/pushback.py b/packages/core/openexecutive/orchestrator/pushback.py
new file mode 100644
index 00000000..7784ace6
--- /dev/null
+++ b/packages/core/openexecutive/orchestrator/pushback.py
@@ -0,0 +1,227 @@
+"""After pushback, a stronger model for one answer.
+
+When someone pushes back on the Executive's last answer, the next answer runs
+on the pushback model (``PUSHBACK_MODEL``, or the Executive's Council pick),
+and the one after that goes back to the normal model. Pushback is any of:
+
+- ``thumbs_down``: a 👎 on the last reply, or a typed "thumbs down" / 👎 as
+ the message (chat apps have no reaction on the reply),
+- ``said_wrong``: words that say the last answer missed ("that's not what I
+ asked", "why can't you", "try again"),
+- ``asked_again``: the same ask as the last message, word for word or nearly,
+- ``claimed``: the claim check caught the last reply claiming a change no
+ tool made (``orchestrator.claim_check``).
+
+All of it is word matching and reads of rows the chat already wrote, so it
+adds no model call. Never raises: anything it can't read counts as no
+pushback, and the turn runs on its normal model.
+"""
+from __future__ import annotations
+
+import logging
+import re
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from difflib import SequenceMatcher
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# Stored as the Executive's pushback pick to turn it off even when
+# PUSHBACK_MODEL names a model. None (no pick) follows PUSHBACK_MODEL.
+PUSHBACK_OFF = "off"
+
+REASONS: tuple[str, ...] = ("thumbs_down", "said_wrong", "asked_again", "claimed")
+
+# Phrases, not single words: "wrong" alone also opens "what went wrong with
+# the deal?", which is a question, not pushback.
+SAID_WRONG_RE = re.compile(
+ r"\b(?:"
+ r"(?:that'?s|that is|this is|it'?s|you'?re) (?:not|still not) (?:what i|right|correct|it)|"
+ r"not what i (?:asked|wanted|meant|said)|"
+ r"(?:that'?s|that is|this is|it'?s|you'?re|still) (?:wrong|incorrect)|"
+ r"why (?:can'?t|cannot|couldn'?t|didn'?t|won'?t|wouldn'?t|aren'?t|haven'?t) you|"
+ r"you (?:should be able|still (?:haven'?t|didn'?t|can'?t)|didn'?t (?:do|answer|read|listen)|"
+ r"missed|got (?:it|that) wrong|keep (?:saying|telling|asking))|"
+ r"try (?:it )?again|do it again|"
+ r"(?:doesn'?t|didn'?t|does not|did not) work|"
+ r"(?:useless|makes? no sense|not helpful|unhelpful)"
+ r")\b",
+ re.IGNORECASE,
+)
+
+# The same ask twice: long enough that "go" / "yes" twice isn't one, and
+# nearly the same words.
+_ASKED_AGAIN_MIN_CHARS = 16
+_ASKED_AGAIN_RATIO = 0.85
+
+_VOICE_PREFIX = "[Voice note, transcribed]"
+_THUMB_RE = re.compile(r"^(?:thumbs?[ -]?down|👎(?:[\U0001F3FB-\U0001F3FF])?)$", re.IGNORECASE)
+
+
+@dataclass(frozen=True)
+class Pushback:
+ model: str
+ reason: str
+
+
+def _clean(text: str) -> str:
+ text = text.strip()
+ if text.startswith(_VOICE_PREFIX):
+ text = text[len(_VOICE_PREFIX):]
+ return " ".join(text.split())
+
+
+def _typed_thumbs_down(text: str) -> bool:
+ return _THUMB_RE.match(text.strip(" \t\n.!")) is not None
+
+
+def said_wrong(text: str) -> bool:
+ return SAID_WRONG_RE.search(text.replace("’", "'")) is not None
+
+
+def _text_of(content: Any) -> str:
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ return " ".join(
+ str(b.get("text", ""))
+ for b in content
+ if isinstance(b, dict) and b.get("type") == "text"
+ )
+ return ""
+
+
+def last_user_text(history: list[dict[str, Any]]) -> str:
+ """The person's last message in the chat before this one."""
+ for msg in reversed(history):
+ if msg.get("role") != "user":
+ continue
+ text = _clean(_text_of(msg.get("content")))
+ # Tool results ride in user turns; skip those to the real message.
+ if text:
+ return text
+ return ""
+
+
+def asked_again(text: str, previous: str) -> bool:
+ a, b = text.lower(), previous.lower()
+ if len(a) < _ASKED_AGAIN_MIN_CHARS or len(b) < _ASKED_AGAIN_MIN_CHARS:
+ return False
+ return a == b or SequenceMatcher(None, a, b).ratio() >= _ASKED_AGAIN_RATIO
+
+
+def _when(text: Any) -> datetime | None:
+ try:
+ when = datetime.fromisoformat(str(text).replace("Z", "+00:00"))
+ except (TypeError, ValueError):
+ return None
+ return when if when.tzinfo is not None else when.replace(tzinfo=UTC)
+
+
+def _last_exchange(session_id: str, db_path: Path | None) -> tuple[Any, Any]:
+ """The chat's last saved reply and the message it answered, as rows
+ (either None when the chat has none)."""
+ from openexecutive.memory.episodic import _get_conn, _resolve_db_path
+
+ resolved = _resolve_db_path(db_path)
+ if not resolved.exists():
+ return None, None
+ with _get_conn(resolved) as conn:
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(chat_messages)")}
+ if "feedback" not in cols:
+ return None, None
+ reply = conn.execute(
+ "SELECT id, created_at, feedback FROM chat_messages "
+ "WHERE session_id = ? AND role = 'assistant' ORDER BY id DESC LIMIT 1",
+ (session_id,),
+ ).fetchone()
+ if reply is None:
+ return None, None
+ asked = conn.execute(
+ "SELECT id, created_at FROM chat_messages "
+ "WHERE session_id = ? AND role = 'user' AND id < ? ORDER BY id DESC LIMIT 1",
+ (session_id, reply["id"]),
+ ).fetchone()
+ return reply, asked
+
+
+def _claim_caught(session_id: str, start: datetime | None, end: datetime | None) -> bool:
+ """Whether the claim check caught a reply in this chat between the last
+ message and its reply."""
+ if end is None:
+ return False
+ from openexecutive.audit.logger import get_audit_logger
+
+ events = get_audit_logger().query(
+ event_type="claim_check", session_id=session_id, limit=20, all_owners=True
+ )
+ for event in events:
+ ts = _when(getattr(event, "ts", None))
+ if ts is not None and ts <= end and (start is None or ts >= start):
+ return True
+ return False
+
+
+def reason_for(
+ session_id: str | None,
+ text: str,
+ history: list[dict[str, Any]],
+ *,
+ db_path: Path | None = None,
+) -> str | None:
+ """Why this message is pushback on the last answer (one of ``REASONS``),
+ or None. Never raises."""
+ try:
+ text = _clean(text)
+ if _typed_thumbs_down(text):
+ return "thumbs_down"
+ reply, asked = _last_exchange(session_id, db_path) if session_id else (None, None)
+ if reply is not None and reply["feedback"] == "down":
+ return "thumbs_down"
+ if said_wrong(text):
+ return "said_wrong"
+ if asked_again(text, last_user_text(history)):
+ return "asked_again"
+ if reply is not None and session_id and _claim_caught(
+ session_id,
+ _when(asked["created_at"]) if asked is not None else None,
+ _when(reply["created_at"]),
+ ):
+ return "claimed"
+ except Exception:
+ logger.warning("pushback: couldn't read the last answer", exc_info=True)
+ return None
+
+
+def pushback_model(override_pick: str | None, default: str) -> str | None:
+ """The model an answer after pushback runs on, or None when it's off.
+ The Executive's Council pick wins over ``PUSHBACK_MODEL``."""
+ pick = override_pick if override_pick is not None else default
+ pick = (pick or "").strip()
+ if not pick or pick == PUSHBACK_OFF:
+ return None
+ return pick
+
+
+def for_turn(
+ *,
+ session_id: str | None,
+ text: str,
+ history: list[dict[str, Any]],
+ normal_model: str,
+ override_pick: str | None,
+ default: str,
+ db_path: Path | None = None,
+) -> Pushback | None:
+ """The pushback model and why, when this turn should run on it; None
+ when it's off, the message isn't pushback, or the pick is the model the
+ turn already uses."""
+ model = pushback_model(override_pick, default)
+ if model is None or model == normal_model:
+ return None
+ reason = reason_for(session_id, text, history, db_path=db_path)
+ if reason is None:
+ return None
+ return Pushback(model=model, reason=reason)
diff --git a/packages/core/tests/unit/test_agent_overrides.py b/packages/core/tests/unit/test_agent_overrides.py
index 4315c15f..c7f4c07c 100644
--- a/packages/core/tests/unit/test_agent_overrides.py
+++ b/packages/core/tests/unit/test_agent_overrides.py
@@ -376,3 +376,21 @@ def test_analyze_appends_instructions_to_replaced_prompt(
asyncio.run(_Dummy().analyze(query="hi"))
text = create_mock.await_args.kwargs["system"][0]["text"]
assert text == ov_mod.append_instructions("OVERRIDE_PROMPT", "Use EUR.")
+
+
+def test_pushback_model_round_trips_through_history(tmp_db: Path) -> None:
+ ov_mod.set_override(
+ "executive", pushback_model="claude-opus-5-5", pushback_model_set=True, db_path=tmp_db
+ )
+ ov_mod.set_override("executive", pushback_model="off", pushback_model_set=True, db_path=tmp_db)
+ assert ov_mod.get_override("executive", db_path=tmp_db).pushback_model == "off"
+ # Another field left alone keeps the pick.
+ ov_mod.set_override("executive", role="Chief", role_set=True, db_path=tmp_db)
+ assert ov_mod.get_override("executive", db_path=tmp_db).pushback_model == "off"
+ older = [
+ e for e in ov_mod.list_history("executive", db_path=tmp_db)
+ if e.pushback_model == "claude-opus-5-5"
+ ]
+ assert older
+ ov_mod.rollback_to(older[0].id, db_path=tmp_db)
+ assert ov_mod.get_override("executive", db_path=tmp_db).pushback_model == "claude-opus-5-5"
diff --git a/packages/core/tests/unit/test_agents_route.py b/packages/core/tests/unit/test_agents_route.py
index eb3839bd..ceed19e4 100644
--- a/packages/core/tests/unit/test_agents_route.py
+++ b/packages/core/tests/unit/test_agents_route.py
@@ -359,3 +359,31 @@ def test_executive_test_endpoint_appends_instructions(client: TestClient) -> Non
assert res.status_code == 200, res.text
text = create_mock.await_args.kwargs["system"][0]["text"]
assert text == ov_mod.append_instructions("EXEC", "Sign off as Ada.")
+
+
+def test_executive_pushback_model_follows_the_setting_until_picked(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("PUSHBACK_MODEL", "claude-opus-5-5")
+ body = client.get("/agents/executive").json()
+ assert body["pushback_model"] == "claude-opus-5-5"
+ assert body["pushback_model_default"] == "claude-opus-5-5"
+
+ res = client.patch("/agents/executive", json={"pushback_model": "off"})
+ assert res.status_code == 200, res.text
+ assert res.json()["pushback_model"] == "off"
+ assert "pushback_model" in res.json()["overridden_fields"]
+
+ res = client.patch("/agents/executive", json={"pushback_model": "claude-sonnet-5-5"})
+ assert res.json()["pushback_model"] == "claude-sonnet-5-5"
+
+ # null clears the pick: back to PUSHBACK_MODEL.
+ res = client.patch("/agents/executive", json={"pushback_model": None})
+ assert res.json()["pushback_model"] == "claude-opus-5-5"
+
+
+def test_pushback_model_must_be_allowed_and_executive_only(client: TestClient) -> None:
+ res = client.patch("/agents/executive", json={"pushback_model": "no-such-model"})
+ assert res.status_code == 400
+ res = client.patch("/agents/cso", json={"pushback_model": "claude-opus-5-5"})
+ assert res.status_code == 400
diff --git a/packages/core/tests/unit/test_pushback.py b/packages/core/tests/unit/test_pushback.py
new file mode 100644
index 00000000..d61d113d
--- /dev/null
+++ b/packages/core/tests/unit/test_pushback.py
@@ -0,0 +1,188 @@
+"""The model for one answer after pushback (orchestrator.pushback)."""
+from __future__ import annotations
+
+import os
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+os.environ.setdefault("ANTHROPIC_API_KEY", "sk-test-not-used")
+
+from openexecutive.memory.episodic import initialize_db # noqa: E402
+from openexecutive.memory.session_store import ( # noqa: E402
+ create_session,
+ save_message,
+ set_message_feedback,
+)
+from openexecutive.orchestrator import pushback # noqa: E402
+
+SID = "s-pushback"
+
+
+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ path = tmp_path / "episodic.db"
+ initialize_db(path)
+ create_session(SID, "Taxes", datetime.now(UTC).isoformat(), db_path=path)
+ # No claim-check rows unless a test adds them.
+ events: list[Any] = []
+ logger = SimpleNamespace(query=lambda **_: list(events))
+ monkeypatch.setattr("openexecutive.audit.logger.get_audit_logger", lambda: logger)
+ monkeypatch.setattr(pushback, "_test_events", events, raising=False)
+ return path
+
+
+def _exchange(db: Path, asked: str = "Draft the email to Kyle", reply: str = "Done.") -> int:
+ save_message(SID, "user", asked, db_path=db)
+ return save_message(SID, "assistant", reply, db_path=db)
+
+
+ "text",
+ [
+ "That's not what I asked",
+ "that’s not what I asked for",
+ "Why can't you attach them?",
+ "You should be able to make these adjustments",
+ "try again",
+ "It didn't work",
+ "Your safety rules basically make this system useless",
+ "you still haven't sent it",
+ "No, that's wrong",
+ ],
+)
+def test_said_wrong_matches_pushback(text: str) -> None:
+ assert pushback.said_wrong(text)
+
+
+ "text",
+ [
+ "What went wrong with the St. Albans deal?",
+ "Go",
+ "Draft a reply to Andrew",
+ "Can you summarize the tax bills?",
+ "Why did the price drop?",
+ ],
+)
+def test_said_wrong_leaves_ordinary_messages(text: str) -> None:
+ assert not pushback.said_wrong(text)
+
+
+def test_asked_again_needs_the_same_longer_ask() -> None:
+ assert pushback.asked_again(
+ "Search my email for St Albans, then open foreactlabs.com",
+ "Search my email for St Albans then open foreactlabs.com",
+ )
+ assert not pushback.asked_again("go", "go")
+ assert not pushback.asked_again(
+ "Search my email for Pine View", "Draft the property tax email to Kyle"
+ )
+
+
+def test_last_user_text_skips_tool_results_and_voice_prefix() -> None:
+ history = [
+ {"role": "user", "content": "[Voice note, transcribed] Rename the PDFs please"},
+ {"role": "assistant", "content": [{"type": "text", "text": "Say go."}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "x", "content": "ok"}]},
+ ]
+ assert pushback.last_user_text(history) == "Rename the PDFs please"
+
+
+def test_typed_thumbs_down_is_pushback(db: Path) -> None:
+ assert pushback.reason_for(SID, "👎", [], db_path=db) == "thumbs_down"
+ assert pushback.reason_for(SID, "Thumbs down.", [], db_path=db) == "thumbs_down"
+
+
+def test_thumbs_down_on_the_last_reply(db: Path) -> None:
+ reply_id = _exchange(db)
+ assert pushback.reason_for(SID, "Ok, and the scans?", [], db_path=db) is None
+ set_message_feedback(SID, reply_id, "down", db_path=db)
+ assert pushback.reason_for(SID, "Ok, and the scans?", [], db_path=db) == "thumbs_down"
+
+
+def test_thumbs_down_on_an_older_reply_doesnt_count(db: Path) -> None:
+ old = _exchange(db)
+ set_message_feedback(SID, old, "down", db_path=db)
+ _exchange(db, "Thanks", "Anytime.")
+ assert pushback.reason_for(SID, "What's on tap tomorrow?", [], db_path=db) is None
+
+
+def test_asked_again_from_history(db: Path) -> None:
+ history = [
+ {"role": "user", "content": "Rename all 11 PDFs as you proposed"},
+ {"role": "assistant", "content": "Say go."},
+ ]
+ assert (
+ pushback.reason_for(SID, "Rename all 11 PDFs as you proposed.", history, db_path=db)
+ == "asked_again"
+ )
+
+
+def test_claim_check_on_the_last_reply(db: Path) -> None:
+ # The check runs while the turn is under way: after the message, before
+ # the reply is saved.
+ save_message(SID, "user", "Clear the Aprio items", db_path=db)
+ pushback._test_events.append(SimpleNamespace(ts=datetime.now(UTC).isoformat()))
+ save_message(SID, "assistant", "Closed.", db_path=db)
+ assert pushback.reason_for(SID, "Thanks", [], db_path=db) == "claimed"
+
+
+def test_claim_check_before_the_last_message_doesnt_count(db: Path) -> None:
+ pushback._test_events.append(
+ SimpleNamespace(ts=(datetime.now(UTC) - timedelta(hours=1)).isoformat())
+ )
+ _exchange(db)
+ assert pushback.reason_for(SID, "Thanks", [], db_path=db) is None
+
+
+def test_unreadable_chat_is_no_pushback(tmp_path: Path) -> None:
+ missing = tmp_path / "nope" / "x.db"
+ assert pushback.reason_for(SID, "Ok", [], db_path=missing) is None
+
+
+def test_pushback_model_pick_order() -> None:
+ assert pushback.pushback_model(None, "") is None
+ assert pushback.pushback_model(None, "claude-opus-5-5") == "claude-opus-5-5"
+ assert pushback.pushback_model("openai/gpt-6-astra", "claude-opus-5-5") == "openai/gpt-6-astra"
+ assert pushback.pushback_model(pushback.PUSHBACK_OFF, "claude-opus-5-5") is None
+
+
+def test_for_turn(db: Path) -> None:
+ kwargs: dict[str, Any] = {
+ "session_id": SID,
+ "history": [],
+ "normal_model": "claude-sonnet-5-5",
+ "override_pick": None,
+ "db_path": db,
+ }
+ hit = pushback.for_turn(text="That's not what I asked", default="claude-opus-5-5", **kwargs)
+ assert hit == pushback.Pushback(model="claude-opus-5-5", reason="said_wrong")
+ # Off, the same model, or no pushback: the normal model.
+ assert pushback.for_turn(text="That's not what I asked", default="", **kwargs) is None
+ assert pushback.for_turn(text="That's not what I asked", default="claude-sonnet-5-5", **kwargs) is None
+ assert pushback.for_turn(text="Thanks", default="claude-opus-5-5", **kwargs) is None
+
+
+def test_executive_picks_the_pushback_model(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ from openexecutive.orchestrator import executive
+ from openexecutive.orchestrator.session import Session
+
+ monkeypatch.setattr(
+ "openexecutive.agents.overrides.get_override",
+ lambda _agent: SimpleNamespace(pushback_model=None),
+ )
+ session = Session(session_id=SID)
+ settings = SimpleNamespace(pushback_model="claude-opus-5-5")
+ monkeypatch.setattr(pushback, "reason_for", lambda *a, **k: "said_wrong")
+ hit = executive._pushback_for_turn(settings, session, "Why can't you?", "claude-sonnet-5-5")
+ assert hit is not None and hit.model == "claude-opus-5-5"
+
+ monkeypatch.setattr(
+ "openexecutive.agents.overrides.get_override",
+ lambda _agent: SimpleNamespace(pushback_model=pushback.PUSHBACK_OFF),
+ )
+ assert executive._pushback_for_turn(settings, session, "Why can't you?", "claude-sonnet-5-5") is None
diff --git a/packages/ui/src/app/council/page.tsx b/packages/ui/src/app/council/page.tsx
index 2a32b1f6..1034fd49 100644
--- a/packages/ui/src/app/council/page.tsx
+++ b/packages/ui/src/app/council/page.tsx
@@ -53,6 +53,15 @@ interface DraftState {
voice_persona_slug: string | null;
research_focus: string | null;
instructions: string;
+ // The Executive's model after pushback; "" = same as normal answers.
+ pushback_model: string;
+}
+
+// "off" (stored) and "" / null (no PUSHBACK_MODEL) all mean answers stay on
+// the normal model. Mirrors PUSHBACK_OFF in orchestrator/pushback.py.
+const PUSHBACK_OFF = "off";
+function pushbackPick(model: string | null | undefined): string {
+ return !model || model === PUSHBACK_OFF ? "" : model;
}
// Mirrors INSTRUCTIONS_MAX_CHARS in api/routes/agents.py.
@@ -157,6 +166,7 @@ function detailToDraft(d: AgentDetail): DraftState {
voice_persona_slug: d.voice_persona_slug ?? null,
research_focus: d.research_focus ?? null,
instructions: d.instructions ?? "",
+ pushback_model: pushbackPick(d.pushback_model),
};
}
@@ -169,7 +179,8 @@ function draftIsDirty(d: AgentDetail | null, draft: DraftState | null): boolean
d.prompt !== draft.prompt ||
(d.voice_persona_slug ?? null) !== draft.voice_persona_slug ||
(d.research_focus ?? null) !== draft.research_focus ||
- (d.instructions ?? "") !== draft.instructions
+ (d.instructions ?? "") !== draft.instructions ||
+ pushbackPick(d.pushback_model) !== draft.pushback_model
);
}
@@ -324,12 +335,16 @@ export default function CouncilPage() {
const pickerOptions = useMemo<PickerOption[]>(() => {
const known = new Set(modelOptions.map((o) => o.id));
const extra = Array.from(
- new Set([detail?.model_default, draft?.model].filter((m): m is string => !!m))
+ new Set(
+ [detail?.model_default, draft?.model, draft?.pushback_model].filter(
+ (m): m is string => !!m
+ )
+ )
)
.filter((m) => !known.has(m))
.map((m) => unlistedOption(m, modelOptions));
return [...modelOptions, ...extra];
- }, [modelOptions, detail?.model_default, draft?.model]);
+ }, [modelOptions, detail?.model_default, draft?.model, draft?.pushback_model]);
// Provider groups in first-seen order (backend order: Anthropic first).
const providerGroups = useMemo(() => {
@@ -425,6 +440,14 @@ export default function CouncilPage() {
// Blank clears the field; the backend stores null for "".
patch.instructions = draft.instructions.trim() ? draft.instructions : null;
}
+ if (draft.pushback_model !== pushbackPick(detail.pushback_model)) {
+ // Back to PUSHBACK_MODEL's pick clears the override; "same as normal
+ // answers" against a PUSHBACK_MODEL that names a model stores "off".
+ patch.pushback_model =
+ draft.pushback_model === pushbackPick(detail.pushback_model_default)
+ ? null
+ : draft.pushback_model || PUSHBACK_OFF;
+ }
const updated = await patchAgent(selected, patch);
setDetail(updated);
setDraft(detailToDraft(updated));
@@ -863,6 +886,36 @@ export default function CouncilPage() {
</div>
</div>
+ {detail.name === "executive" && (
+ <label className="block">
+ <span className={FIELD_LABEL}>Model after pushback</span>
+ <select
+ aria-label="Model after pushback"
+ value={draft.pushback_model}
+ onChange={(e) => setDraft({ ...draft, pushback_model: e.target.value })}
+ className={`w-full ${FIELD} mt-1.5 h-11 text-[15px]`}
+ >
+ <option value="">Same as normal answers</option>
+ {providerGroups.map((g) => (
+ <optgroup key={g.provider} label={g.label}>
+ {pickerOptions
+ .filter((o) => o.provider === g.provider)
+ .map((o) => (
+ <option key={o.id} value={o.id}>
+ {o.label}
+ </option>
+ ))}
+ </optgroup>
+ ))}
+ </select>
+ <span className="text-xs text-fg-subtle mt-1 block">
+ After a thumbs down, &ldquo;that&apos;s not what I asked&rdquo;, the same ask
+ again, or a reply that claimed something it didn&apos;t do, the next answer
+ uses this model. The one after goes back to the normal model.
+ </span>
+ </label>
+ )}
+
{detail.name !== "utility_fast" && (
<label
className={`flex items-start gap-3 text-sm text-fg-muted ${
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index bb3141ae..6841af52 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -3846,6 +3846,10 @@ export interface AgentDetail {
research_focus: string | null;
research_focus_default: string | null;
instructions: string | null;
+ // The Executive only: the model for one answer after pushback ("off" or ""
+ // = same as normal answers), and PUSHBACK_MODEL's.
+ pushback_model?: string | null;
+ pushback_model_default?: string | null;
}
export interface AgentHistoryEntry {
@@ -3858,6 +3862,7 @@ export interface AgentHistoryEntry {
voice_persona_slug: string | null;
research_focus: string | null;
instructions: string | null;
+ pushback_model?: string | null;
created_at: string;
}
@@ -3869,6 +3874,7 @@ export interface AgentPatch {
voice_persona_slug?: string | null;
research_focus?: string | null;
instructions?: string | null;
+ pushback_model?: string | null;
}
// ---- Voice Personas --------------------------------------------------------