AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
feat(artifacts): deliver artifacts by message link or email attachment (#209)
Rufus212cfafc2c2e
diff --git a/packages/core/openexecutive/api/routes/artifacts.py b/packages/core/openexecutive/api/routes/artifacts.pyindex 139afef4..ddf60e05 100644--- a/packages/core/openexecutive/api/routes/artifacts.py+++ b/packages/core/openexecutive/api/routes/artifacts.py@@ -35,24 +35,20 @@ Endpoints:from __future__ import annotationsimport logging-import refrom collections.abc import Callablefrom typing import Annotated, Literalfrom fastapi import APIRouter, HTTPException, Query, Responsefrom pydantic import BaseModel-from openexecutive.orchestrator.artifact_formats import (- ARTIFACT_FORMATS,- EXPORT_TARGETS,- get_format,-)+from openexecutive.orchestrator.artifact_formats import get_formatfrom openexecutive.orchestrator.artifact_records import (ArtifactNotFound,ArtifactRecord,MalformedArtifactId,+ artifact_downloads,load_artifact,- parse_artifact_id,+ render_artifact_file,)from openexecutive.orchestrator.artifact_records import (delete_artifact as delete_artifact_record,@@ -72,8 +68,6 @@ _DEFAULT_LIMIT = 200# Chars of body shown as a card preview. Unrelated to _DEFAULT_LIMIT despite# the shared value — keep them as separate named knobs._PREVIEW_CHARS = 200-_FILENAME_MAX = 60-_FILENAME_BAD = re.compile(r"[^a-z0-9]+")class ArtifactSummary(BaseModel):@@ -133,26 +127,20 @@ async def download_artifact() -> Response:"""The artifact as a file. `?as=docx` exports a Markdown artifact to Word."""rec = _load(composite_id)- targets = _downloads(rec)- target = (as_ or (targets[0] if targets else "")).strip().lower()- if not targets or target not in targets:- raise HTTPException(- status_code=404,- detail=f"Artifact {composite_id!r} has no {target or 'file'} download",- )- fmt = ARTIFACT_FORMATS[target]- assert fmt.render_file is not None and fmt.extension is not Nonetry:- content = fmt.render_file(rec.stored or "")+ file = render_artifact_file(rec, as_)+ except ArtifactNotFound as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from excexcept Exception as exc:- logger.exception("artifact download render failed for %s as %s", composite_id, target)+ logger.exception(+ "artifact download render failed for %s as %s", composite_id, as_ or rec.format+ )raise HTTPException(status_code=500, detail="Could not render the file") from exc- filename = f"{_filename_stem(rec)}.{fmt.extension}"return Response(- content=content,- media_type=fmt.mime,+ content=file.content,+ media_type=file.mime,headers={- "Content-Disposition": f'attachment; filename="{filename}"',+ "Content-Disposition": f'attachment; filename="{file.filename}"',"X-Content-Type-Options": "nosniff","Content-Security-Policy": "sandbox","Cache-Control": "no-store",@@ -218,12 +206,6 @@ def _mutate(action: Callable[[], ArtifactRecord]) -> ArtifactRecord:raise HTTPException(status_code=404, detail=str(exc)) from exc-def _downloads(rec: ArtifactRecord) -> list[str]:- own = get_format(rec.format)- if own.render_file is None:- return []- return [own.name, *EXPORT_TARGETS.get(own.name, ())]-def _summary(rec: ArtifactRecord) -> ArtifactSummary:fmt = get_format(rec.format)@@ -240,16 +222,8 @@ def _summary(rec: ArtifactRecord) -> ArtifactSummary:archived_at=rec.archived_at,format=fmt.name,format_label=rec.link_label if fmt.name == "link" and rec.link_label else fmt.label,- downloads=_downloads(rec),+ downloads=artifact_downloads(rec),external_url=rec.url,link_label=rec.link_label,supersedes_id=rec.supersedes_id,)---def _filename_stem(rec: ArtifactRecord) -> str:- stem = _FILENAME_BAD.sub("-", rec.title.lower()).strip("-")[:_FILENAME_MAX].strip("-")- if stem:- return stem- kind, native_id = parse_artifact_id(rec.id)- return f"{kind}-{native_id[:12]}"diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 21e90447..c75af87d 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -584,6 +584,25 @@ routing:neutral because an artifact can quote injected email/web text and mustnot come back with the Executive's own authority. Company switches / fixture resets clear`type=artifact` chunks alongside `type=recent_research`.+ Delivery (vendor-neutral core, provider adapters optional):+ - `message_person(person_id, text, artifact_id?)`+ (`schedule_tools._artifact_link_line`) appends `📄 <title> —+ <UI_BASE_URL>/artifacts/<id>` after resolving the id through+ `artifact_records` (unknown / non-artifact ids error, nothing sent).+ The link rides the normal DM path, outbound guard included; it only+ opens for people with Open Executive access.+ - Gmail send / draft through the MCP gateway may attach+ `{"artifact_id", "as"?}`; `mcp_gateway._expand_artifact_attachments`+ renders it with `artifact_records.render_artifact_file` (shared with+ `/download`) into workspace-mcp's `{content, filename, mime_type}`+ shape, AFTER the recipient gate passes. Normalises a stringified or+ single-object `attachments` first (an unexpanded artifact entry would be+ silently skipped by workspace-mcp). Refuses unknown / non-artifact ids,+ links, extra keys, more than 5 distinct artifacts (repeats dropped) and+ over 15 MB rendered in total; renders via `asyncio.to_thread`. Audits+ `artifact_attachment_refused` on refusal and `artifact_attached` only+ after a non-error send, both with recipients. Other attachment entries+ are untouched.Side-effecting (`draft_artifact` only): a `tool_invocation` audit row(actor="executive", details carry `format`, `supersedes`) and an`action_taken` chip ("Drafted artifact for review: {title}") linking todiff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex c2b22a1f..b16e252f 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.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. 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. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine 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| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\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\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\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`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Beside it the Executive carries its skill tools (`search_skills`, `load_skill`, `create_skill`, `update_skill`, `delete_skill` — shown to users as **playbooks**; `create_skill` / `update_skill` / `delete_skill` never change the library — they save a draft (`knowledge/skill_drafts.py`) that a person approves on the Playbooks tab, and the reply links to it; `update_skill` / `delete_skill` (and `create_skill`, for a name a workflow still follows) refuse any built-in name (including a company's customized copy) and any company playbook a workflow (even a switched-off custom one) follows — workflows read playbooks at run time, approved scheduled ones included, and this loop also runs on inbound email and chat, so only a person on the Playbooks tab can change what a workflow follows; a hidden built-in is invisible to search and load; each `search_skills` hit lists the `workflows` that follow it, and the persona routes \"the finished deliverable\" to that workflow and quick or partial asks to the playbook inline); Tool calls made while proactive work is tagged (scheduler dispatch, reflection, research, alert review) feed the Attunement outcome ledger. 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. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine 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| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. The Council picks a model in two steps: a **Provider** dropdown (Anthropic, OpenAI, Google, Meta, DeepSeek, xAI, Local, …), then a **Model** dropdown limited to that provider, with readable names (\"Claude Opus 5.5\") and the raw id and serving route shown underneath. The Anthropic group combines the direct Claude models (`claude-fable-5-1`, `claude-opus-5-5`, `claude-opus-5`, `claude-sonnet-5`, `claude-haiku-4-5`) with any Claude generation that exists only on OpenRouter, and never lists a model twice. With `OPENROUTER_ENABLED`, the non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Eight Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments), `workflow_designer` (runs the conversational New workflow wizard on `/jobs/new`: searches the available tools, asks clarifying questions, then drafts a validated dynamic-workflow definition for the user to review), and `workflow_actor` (runs a workflow's `action` steps: a bounded tool-use loop limited to the tools the user approved for that step). `fixture_generator`, `engagement_intake` and `onboarding_interviewer` share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\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\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\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`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nDeliverables are first-class too. `orchestrator.artifact_tools` gives the Executive three tools: `draft_artifact` publishes a memo, web page (`html`), Word document (`docx`), spreadsheet (`xlsx`, from structured `sheets`) or a `link` to something it created in one of the principal's connected apps through the generic MCP gateway (`search_tools` → `call_tool`, any server — no vendor is named), and returns the artifact's id and link; `list_artifacts` and `get_artifact` let it find and reread its own past work (drafts and workflow outputs alike, through the same `artifact_records` read model the API uses). Revising is `draft_artifact(supersedes=<id>)`, which archives the earlier version. When the principal asks for a deliverable the tool is always used; the \"quiet is the right default\" bar applies only to unprompted drafts. The format enum is a hard-coded sorted tuple so the cached tool schema stays byte-stable. Delivery: `message_person(person_id, text, artifact_id?)` appends the artifact's title and a `UI_BASE_URL/artifacts/<id>` link (through the same outbound guard as any DM; the link needs Open Executive access), and a Gmail send/draft can attach the file itself by `artifact_id` — see Integrations.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.","mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / triage\"]\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 Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",- "generated_at": "2026-09-24T17:10:12.016539+00:00"+ "generated_at": "2026-09-24T17:52:47.993540+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.jsonindex 75e3ae5f..35d1d15d 100644--- a/packages/core/openexecutive/architecture/prebuilt/integrations.json+++ b/packages/core/openexecutive/architecture/prebuilt/integrations.json@@ -1,7 +1,7 @@{"section_id": "integrations","title": "Integrations",- "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.",+ "markdown": "External channels connect callers to the Executive. Each inbound adapter resolves the sender to a Person via `find_person_by_{slack,discord,telegram,email}_id` and threads `person_id` into `Executive.chat()`.\n\n### Inbound channels\n\n- **Slack** (`integrations.slack_bot`) — async Bolt socket-mode (`AsyncApp` + `AsyncSocketModeHandler`) embedded in the lifespan; responds to `@mention`s, DMs, and thread continuations, with per-conversation session memory (see **Conversation state** below). Text only: there is no interactivity endpoint and no Block Kit, so nothing Slack sends carries a button.\n- **Discord** (`integrations.discord_bot`) — discord.py gateway embedded in the lifespan; per-thread auto-titling, session-scoped memory, author attribution, configurable `@mention` thread promotion.\n- **Telegram** — webhook gating + per-chat history.\n- **Google Chat** — webhook + service-account auth. It resolves no approval gates and has no roster gate (the webhook authenticates Google, not the sender), and it never populates the session's trusted alert ids, so `ack_alert`'s trust check — which now runs on every session rather than only those declaring an `origin_channel` — refuses there by default, and its `<channel>` block says plainly that a sign-off cannot be answered from it.\n- **Email** (`integrations.email_poller`) — Gmail poll loop over the Google Workspace MCP (it starts only once the MCP gateway is up); strips Reply-To, filters auto-replies. While the Executive is paused (`scheduler.pause`) it skips each poll and leaves the inbox unread, so held mail is processed on the first poll after resume; the chat adapters above are not paused. The Executive sees the whole message; peer memory records only `_email_memory_text` — the subject, the sender's new text (cut at the first quoted or forwarded message) and the attachment filenames — parsed without backtracking-prone regexes, since the text is sender-controlled, and only for a rostered sender, the only kind with a peer to record into.\n\nSlack, Discord, and Telegram are roster-gated on inbound: an unrostered sender's message is silently dropped (`details.outcome=\"rejected_unknown_sender\"`). Email is not inbound-gated — non-roster mail flows through with a `[POLICY]` notice so triage can classify it. Slack/Discord thread continuations pass the shared `integrations.response_gate` (utility-fast model, biased toward replying).\n\n### Conversation state\n\nEvery adapter keys a deterministic `session_id` off the conversation surface and replays that session's stored turns into `Session.conversation_history`, so a follow-up (\"yes, go ahead\") lands with the question still in context. Slack's ids are `slack:dm:{user}`, `slack:thread:{channel}:{thread_ts}`, and `slack:channel:{channel}:{user}` for a mention that starts a thread; because the bot's reply roots a Slack thread at that message's `ts`, the turn is double-written to that thread's session too, so the first continuation inside it is not cold. A reply inside a thread THAT PERSON ROOTED also offers the parent `slack:channel:{channel}:{user}` id when matching an approval gate, since a gate raised on the mention recorded that session while the answer arrives under the thread's. The root-author check is load-bearing: widening on \"threaded and not a DM\" alone offered one person's channel session inside any thread in that channel, so a remark they made to a colleague could resolve their open gate and post the run's title into that colleague's thread. Discord has the same shape — its auto-thread router promotes a mention reply into a bot-owned thread — and the same alias. An @-mention inside a DM is handled once, by the DM path: Slack fires both events, and taking both forked the conversation across two session ids. The same id is the audit grouping key and the scope passed to `format_for_prompt`. A per-session `asyncio.Lock` serializes turns within one conversation — the inflight semaphore caps fan-out across the workspace, which does nothing to stop two messages in the same thread from both reading history before either writes it. Persistence happens after the reply is sent and its failure is logged, never surfaced: the user already has their answer.\n\nThis was absent on Slack until #136. Every message built a fresh `Session` and minted a per-*message* id (`thread_ts` falls back to the message's own `ts`, so a DM never repeated one), which meant a multi-turn confirmation could not work: the Executive asked whether to send a briefing to Slack, the user said yes, and the next turn had no record of the question.\n\n### What the model is told about the channel\n\nChat adapters pass a `<channel>` block (`integrations.channel_context`) in the **user turn** — never a cached system block. It names the surface, states that the person cannot see the app's cards or buttons, and draws the line the assistant kept crossing: briefing proposals and alerts are actioned on the briefing page; a proposal that books something can only be approved there; a workflow sign-off the Executive is explicitly waiting on *can* be answered in the conversation. The principal's DMs on Slack, Discord and Telegram also receive the open-alert digest (`briefing.context.format_open_alerts_for_prompt`) as the `<briefing>` block, gated to DMs because the board is company-wide and a shared channel must not pull it in. That digest is the ONLY trusted source of an `alert_id` for `ack_alert`. The briefing page's `[Discuss mode — alert_id=N]` primer is a pointer to which item is under discussion, not authority on its own: the server accepts that id only if it is also on the live board it derived itself. An id appearing anywhere else, including inside an alert's own body, is not trusted: alerts are minted from inbound email and chat, so their bodies are attacker-controlled. Two mechanisms enforce that rather than one prompt rule. Every field the digest interpolates is collapsed to a single line, because a newline in an attacker-written headline, suggested action, tag or review note would otherwise forge a whole extra `[N]` line — a fabricated instruction to clear somebody else's alert. And the live board the server derived is recorded on the session, so `ack_alert` refuses any id outside it — on EVERY session, web included; the web previously had no check at all. The recorded set is the whole live board (the cap `/today` renders as cards), not just the rows the digest printed, so a card past the digest's 30-row render cap is still ackable rather than sending the principal back to the page. Be precise about what this buys: it stops an id that is invented, closed, snoozed or expired, including one quoted out of an attacker-written alert body. It does NOT stop the model being argued into acking the wrong LIVE card — one alert's body can still make a case about another id that is genuinely open. Scoping trust to the single item under discussion would need the primer id carried server-side, which it is not.\n\n### Handler failures\n\nAn adapter's catch-all replies \"I encountered an error processing your request.\" On Slack that used to be the whole story — one uncorrelated log line, no audit row, and an unguarded error-send that could itself escape into Bolt. It now logs with the session, sender, channel, thread and mode, and writes an `integration_inbound` row with `details.outcome=\"handler_error\"`, joining the inbound row under the same `session_id`. Upstream, a single crashing tool handler no longer takes the turn down at all: the orchestrator's tool gathers use `return_exceptions=True`, hand the model an error `tool_result`, and audit it with `ok=false` (cancellation is re-raised, not swallowed).\n\n### Attachments\n\n`integrations.attachments` handles web chat, Discord, and Telegram. Images become Anthropic vision blocks; documents (PDF/DOCX/TXT/MD/CSV) are inlined into the turn that carried them and indexed into the ChromaDB `inbound_attachments` collection. 20 MB/file cap; web chat uses `POST /chat/upload`.\n\nIndexed chunks are keyed on `attachment:<bare filename>` and tagged `type=attachment`. An attachment's name is chosen by whoever sent the message and the name is the chunk-id namespace, so without the prefix an inbound `strategy-2026.md` would upsert over the curated company document of that name. The prefix separates inbound content from curated uploads and keeps provenance visible; it does not separate senders from one another.\n\nIsolation is the **collection**: `retriever.retrieve` never queries `inbound_attachments` at all, so an attachment cannot resurface as company knowledge in a later, unrelated turn. Attachment processing is roster-gated on Discord too — it previously ran before the gate, so an unrostered sender's file was downloaded and indexed before their message was dropped. These rows still have no operator surface: they are never written to `company/docs/`, so `GET /documents` does not list them.\n\nThis replaced a domain-based scheme that did not work. The chunks lived in `company_docs` under a domain outside the specialist set, on the premise that an unrecognised domain matched no filter. It matched every one — `ChromaDBStore.query` attaches a `where` clause only when a domain filter is present, and an Executive-level retrieval passes none — so attachments came back under “From your company documents”, top-ranked and indistinguishable from a curated upload. Legacy rows are migrated across on boot.\n\n### MCP gateway & outbound\n\nMCP runs in **both directions**. As a *client*, `orchestrator.mcp_gateway.MCPGateway` proxies MCP servers (Gmail, Calendar, Drive — whatever `mcp_servers.json` configures) as Executive tools, with egress gating on Gmail recipients, Calendar attendees, and Drive share grantees against the roster (and a refusal of public / whole-domain Drive sharing). The Google Workspace server (`workspace-mcp`) behind those Gmail/Calendar/Drive tools runs **co-located inside the API** as a stdio child of the gateway — fitting the single-tenant model (one install = one company = one exec Google account), so there's no separate service to operate. It's baked into the API image and launched by `docker/workspace-mcp-launch.sh`, which selects single-user OAuth (token persisted at `/data/google_credentials`) or service-account domain-wide delegation from `GWORKSPACE_AUTH_MODE`. The gateway forwards the Google secrets to the child via `_FORWARDED_ENV_VARS`. As a *server*, `openexecutive.mcp_server` exposes OE's own company context and specialist council to external MCP clients at `/mcp` — the inverse direction; see the dedicated **MCP Server** section. The gateway launches extensible-mcp as a `uvx` subprocess whose fastembed tool-search index uses an embedding model baked into the API image and loaded offline, so it no longer re-downloads that model from the Hugging Face Hub on every cold start. extensible-mcp is pinned twice over: to a commit, which fixes its own code, and with `--exclude-newer`, which fixes the resolution of its dependencies — without the cutoff uvx re-resolves them against PyPI on every networked start, so a new release of any of them would reach running deployments on restart. Both live in `_EXTENSIBLE_MCP_LAUNCH_ARGS` in `orchestrator/mcp_gateway.py`, the Dockerfile's pre-warm uses the same arguments (a unit test enforces the match), so an image whose pre-warm succeeded starts the gateway with no network. The pre-warm is best-effort (`|| true`): an image built while GitHub was unreachable fetches the pinned commit on its first start instead. Updating the gateway is a deliberate bump of the commit and cutoff; `uv` itself is not pinned. Because the MCP stdio client does not inherit the parent environment, `MCPGateway.start()` explicitly forwards the embedding-cache/offline env vars (`FASTEMBED_CACHE_PATH`, `HF_HUB_OFFLINE`, …) into the child.\n\n**Emailing an artifact.** A Gmail send or draft may carry `attachments=[{\"artifact_id\": \"alert:12\", \"as\"?: \"docx\"}]`. `call_tool` runs the recipient gate first; only if it passes does `_expand_artifact_attachments` replace each such entry with the rendered file (`content` base64 + `filename` + `mime_type`, workspace-mcp's own attachment shape), produced by `artifact_records.render_artifact_file` — the same renderer as `/artifacts/{id}/download`. Only artifact rows resolve (never an arbitrary alert), links have no file, and an entry mixing `artifact_id` with other keys is refused. A stringified or single-object `attachments` is normalised first, so an artifact entry can never reach workspace-mcp unexpanded (it would silently drop it). At most 5 distinct artifacts per email (repeats are dropped) and 15 MB rendered in total; rendering runs off the event loop via `asyncio.to_thread`. A refusal writes `artifact_attachment_refused`; a successful send writes `artifact_attached` — both carry the recipients. Other attachment entries pass through unchanged.\n\n**Enablement, and why it degrades instead of dying.** `MCP_ENABLED` left unset is inferred from the presence of `mcp_servers_config_path` — dropping an `mcp_servers.json` next to `profile.yaml` turns MCP on with no further configuration. An **explicit** setting always wins in both directions: `MCP_ENABLED=false` keeps MCP off with the file still in place. It did not: `_resolve_mcp` tested `not self.mcp_enabled`, which cannot tell \"never set\" from \"set to false\", so the file's presence silently overrode the operator. The file is probed through `config.mcp_config_file_present`, never `Path.exists` directly — that re-raises an EACCES on a parent directory, and from inside a validator that comes out of `Settings()` itself, which `api/main.py` calls at module level. The check now reads `model_fields_set` (the fields the env actually supplied) and stores that on a private attr behind the read-only `mcp_auto_enabled` property, because the validator's own assignment joins that set and would otherwise make every auto-enable look explicit downstream.\n\nStartup is **best-effort**, in `main._start_mcp_gateway`. Two checks come before the subprocess: MCP off is a no-op, and a config defining no servers under `mcpServers` is logged and skipped — extensible-mcp's own loader raises on that and exits, and because the child is already gone the only thing that surfaces is anyio's \"Attempted to exit cancel scope in a different task\" from `stdio_client` unwinding, a traceback naming nothing about configuration. The start is also bounded (120s, generous because that child may still clone extensible-mcp on a cold start if the image's pre-warm failed): `ClientSession` carries no `read_timeout_seconds`, so `initialize()` waits forever on a child that is *alive but silent*, and an unbounded wait is a lifespan that never yields — the same healthcheck-never-passes symptom, which no `except` can see. A gateway that fails anyway is logged at ERROR with the config path, the servers it named, and whether the config file or an explicit `MCP_ENABLED` turned MCP on, then torn down under its own timeout; the API boots **without MCP tools and without the email poller** rather than refusing to boot. The guard catches `BaseException`, not `Exception`, re-raising a bare `CancelledError` first: the original failure came from anyio, which wraps a task group's failures in `BaseExceptionGroup` as soon as one is a `BaseException` — and that group is not an `Exception`, so `except Exception` would miss the very shape this contains. The teardown is contained too, since it runs from inside that `except` and would otherwise replace the actionable log with the crash it prevents. `configured_server_names` never raises either, and deliberately catches broadly: it reads an operator-owned path during startup, where an exception is the crash loop rather than a bug report — `Path.is_file` re-raises an EACCES on a parent directory, and `json.loads` answers deeply-nested input with `RecursionError`, which is not a `ValueError`. It tests `is_file()` so a directory or a symlink to a FIFO is never opened, and caps the read at 1 MiB. That exception used to propagate out of the lifespan and kill the container — under `restart: unless-stopped`, a crash loop whose only outward symptom was a healthcheck that never passed. Outbound tools: per-Person DMs (`send_slack_dm`, `send_discord_dm`, `send_telegram_message`) plus room-targeted `send_department_message` and `send_company_broadcast`. The per-Person DMs are additionally rate-limited and de-duplicated by the outbound anti-spam guard (below).\n\n### Outbound anti-spam guard\n\nEvery per-Person DM passes a deterministic guard (`orchestrator.outbound_guard.check_outbound_allowed`) after the roster gate and recipient-id recovery but before the network send — the single chokepoint **all** proactive DM paths reach (ad-hoc chat sends, the scheduler's followup/nudge dispatch, principal-brief delivery, the reflection turn, and research-finding routing). On a violation it returns a human-readable reason and the handler **suppresses** the send (`{\"status\":\"suppressed\",\"reason\":…}`), writes a `tool_invocation` audit row with `suppressed=true`, and writes **no** `done` activity row — so a blocked attempt never counts toward its own rate cap, and the Executive can read the reason and hold or `schedule_followup` for the recipient's next window. Three controls: **content dedup** (a near-identical message — whitespace/case-normalized, first 160 chars — already sent to the same recipient within `OUTBOUND_DEDUP_WINDOW_MINUTES`, default 360); a **per-recipient rate cap** (`OUTBOUND_MAX_PER_RECIPIENT_PER_WINDOW`, default 5, over `OUTBOUND_RATE_WINDOW_MINUTES`, default 60); and **quiet hours / availability** (`OUTBOUND_RESPECT_QUIET_HOURS`, default on — refuse while the recipient is on leave or outside their `people.channel` availability windows, surfacing the next open window). Delivery history is read from the existing `status='done'` `scheduled_actions` rows (`episodic.recent_sends_for_channel_ref`), so there is no new table. The guard is **fail-open**: any internal lookup error returns \"allow\", so it can never turn a working send into a crash or a silently-dropped message. Principal briefs and the internal heartbeat kinds use the `__internal__` channel and never reach these handlers, so they are unaffected.\n\n### Calendar & Google Meet\n\nThe Executive books meetings through two typed tools over the Calendar MCP. `create_calendar_event` schedules a **future** meeting (propose→approve by default, or auto-execute once that decision class is promoted) and may be used proactively when a stalled goal warrants a sync. `create_instant_meeting` spins up an **impromptu call starting now**, auto-executing without the approval step and skipping the business-hours/horizon caps, so the Executive can hand back a join link immediately. Both attach a **Google Meet** link by default (`add_google_meet`; opt out for in-person), parsed from the created event's `conferenceData` and surfaced to the caller plus persisted on the decision ledger. Either way the caps that matter still hold — roster membership, principal-protection, max attendees, and a daily booking ceiling.\n\n**Around-the-meeting participation.** The Executive doesn't join the call as a live voice; instead, on every successful booking it schedules a best-effort post-meeting follow-up (~5 min after the end) that DMs a human attendee asking for a quick recap — key decisions and action items. The reply flows back through the same cross-session DM context linkage described below, so the Executive can act on it (summarize, follow up) in a later turn. No meeting-transcript or Drive integration is required.\n\n### Cross-session DM context\n\nWhen the principal says \"DM Alex about X\" in one session, OE sends the DM and — if a live conversation is active — records an `outbound_context` linkage row (recipient, full outbound text, originating session id). Email is covered too but recorded one layer deeper — there is no `send_email` tool, so the linkage is written in `orchestrator.mcp_gateway` after a successful `google_workspace__send_gmail_message`, one row per `to`/`cc` recipient keyed by the bare lowercased address (OE's own address skipped). When Alex later replies on the 1:1 DM path — or by email — the shared helper `integrations.inbound_hydration.hydrate_user_message` (called by the Discord, Telegram, and Slack handlers, and by the email poller keyed on the sender address) looks up the most-recent `open` linkage for that sender within 72h and prepends an `<outbound_reply_context>` block — the outbound text plus a backstory excerpt from the originating session — to the message handed to `Executive.chat()`. So OE knows what the reply is about instead of starting from an empty per-person session. The block is context for the LLM turn only: peer memory strips it before recording what the person said (`strip_outbound_reply_context`, applied in `sync_turn`, `sync_department_turn` and to the prefetch query), so the Executive's own DM is never attributed to the person who replied to it. The block lands in the user turn (caching rule) and is injected into a copy only — the pristine reply is persisted to history. The linkage is one-shot (consumed on first matched reply, race-safe) so an unrelated later DM isn't re-hydrated. This is deterministic and independent of the per-person `peer_memory` (Honcho) layer.\n\nEvery adapter that persists a turn (Slack, Discord, Telegram, and the web route) records the message's **resolved sender** on `chat_messages.sender_person_id` — the rostered Person the adapter matched, or NULL for an unrostered sender — independently of the session owner, which falls back to the principal on Discord and Telegram so those threads stay visible. Attunement's open loops and feedback rely on this so an outsider's words are never read as someone on the roster's.","mermaid": "flowchart TD\n Channels[\"Slack / Discord<br/>Telegram / GChat / Email\"]\n Resolve[\"find_person_by_*_id\"]\n Gate[\"roster gate\"]\n Drop[\"drop unrostered\"]\n Exec[\"Executive.chat()\"]\n Attach[\"attachments<br/>(vision / inbound_attachments)\"]\n MCP[\"MCP gateway\"]\n Guard[\"outbound anti-spam guard<br/>(dedup / rate cap / quiet hours)\"]\n Out[\"DM / department<br/>/ broadcast tools\"]\n Channels --> Resolve\n Resolve --> Gate\n Gate -- \"unknown sender\" --> Drop\n Gate -- \"Person\" --> Exec\n Gate --> Attach\n Attach --> Exec\n Exec --> MCP\n Exec --> Guard\n Guard -- \"suppress\" --> Drop\n Guard -- \"allow\" --> Out\n Out --> Channels\n class Channels entry\n class Resolve compute\n class Gate compute\n class Drop external\n class Exec hot\n class Attach compute\n class MCP external\n class Guard compute\n class Out compute",- "generated_at": "2026-09-24T14:41:02.752633+00:00"+ "generated_at": "2026-09-24T17:40:22.177514+00:00"}diff --git a/packages/core/openexecutive/evals/_scenarios/artifacts_003.yaml b/packages/core/openexecutive/evals/_scenarios/artifacts_003.yamlnew file mode 100644index 00000000..182a8136--- /dev/null+++ b/packages/core/openexecutive/evals/_scenarios/artifacts_003.yaml@@ -0,0 +1,28 @@+id: artifacts_003+domain: artifacts+description: "Principal asks to send an existing artifact to a teammate; Executive shares it with message_person(artifact_id=...) instead of pasting the document into the DM."+company_context:+ stage: "Series A"+ industry: "B2B SaaS"+ headcount: 45+ arr: 3500000+# Exercises artifact delivery: the Executive finds the artifact+# (list_artifacts), resolves the teammate (lookup_person), and shares it with+# message_person(person_id, text, artifact_id) so the DM carries the title and+# a link, rather than dumping the full document into chat. With Google+# Workspace connected it may instead email the file as an attachment+# ({"artifact_id": ...}). `expected_tool_calls` is documentation for now+# (matches mcp_tool_call_001.yaml convention).+query: "Send Dana the pricing comparison spreadsheet you made yesterday — she needs it before the vendor call."+expected_tool_calls:+ - list_artifacts+ - lookup_person+ - message_person+expected_topics:+ - identifies_pricing_spreadsheet+ - shares_with_dana+ - confirms_sent+quality_criteria:+ shares_link_not_full_document: true+ does_not_ask_for_artifact_id: true+ brief: truediff --git a/packages/core/openexecutive/guide/prebuilt/artifacts.json b/packages/core/openexecutive/guide/prebuilt/artifacts.jsonindex 98213cb5..98deae6d 100644--- a/packages/core/openexecutive/guide/prebuilt/artifacts.json+++ b/packages/core/openexecutive/guide/prebuilt/artifacts.json@@ -1,7 +1,7 @@{"section_id": "artifacts","title": "Artifacts",- "markdown": "**What it is:** Your library of finished deliverables — memos, web pages, Word documents, spreadsheets, links to things the Executive created in your own apps, and the outputs of workflow runs — in one place.\n\n**What it does:**\n\n- See all active artifacts, filtered by kind (drafts vs workflow outputs). Anything that isn't a plain document shows a small badge: *Web page*, *Word document*, *Spreadsheet*, or the app a link opens.\n- Open any artifact to read it. Web pages display in a locked-down frame that can't run scripts or load anything from the internet; spreadsheets show as tables; links open straight into the app they live in.\n- Download it in its own format (.md, .html, .docx, .xlsx). Any Markdown document — including every workflow output — can also be downloaded as a Word file.\n- **Revise in chat**: opens a new chat about that artifact. The Executive rereads it, writes the new version, and archives the old one; the new version links back to the one it replaced.\n- The Executive remembers what it has written: it can list and reread its artifacts, and past artifacts surface in its answers when relevant.\n- Archive an artifact to tuck it away (with a quick undo) and restore it later.\n- Permanently delete one when you're sure, with a confirmation step.\n- Switch between **Active** and **Archived** views.\n\n**How to use:**\n\n1. Get something in here. Ask the Executive for a deliverable and say the format if you care — *\"as a Word doc\"*, *\"as a spreadsheet\"*, *\"as a one-page web page\"*, or *\"in my Google Sheets / Notion / OneDrive\"*. When you ask, it always publishes the result and replies with a link. For your own apps it uses whatever you've connected; with nothing connected it makes the file itself. It also drafts things unprompted when a finding is worth your time. Drafts appear as a card in the Briefing's **Needs you** lane, and every workflow run adds its output here automatically.\n2. Open **Artifacts** in the sidebar. Filter by **Drafts** or **Workflows**, and switch between **Active** and **Archived**.\n3. Click an artifact to read it; use **Copy** or a **Download** button to take it elsewhere, or **Revise in chat** to ask for changes.\n4. Hover over a row to **Archive** it (an **Undo** appears for a moment), **Restore** it from the Archived view, or **Delete permanently** (you'll be asked to confirm).\n\n**Example:** *\"Put the vendor pricing comparison in a spreadsheet for me.\"* A spreadsheet lands in **Needs you** and in **Artifacts**, previewed as tables with a **Download .xlsx** button. Later: *\"Add a column for contract length to that pricing spreadsheet\"* — the Executive rereads it, publishes the revised version, and archives the first one.\n\n*Note: archiving is a soft-delete — nothing is lost until you explicitly delete it.*",+ "markdown": "**What it is:** Your library of finished deliverables — memos, web pages, Word documents, spreadsheets, links to things the Executive created in your own apps, and the outputs of workflow runs — in one place.\n\n**What it does:**\n\n- See all active artifacts, filtered by kind (drafts vs workflow outputs). Anything that isn't a plain document shows a small badge: *Web page*, *Word document*, *Spreadsheet*, or the app a link opens.\n- Open any artifact to read it. Web pages display in a locked-down frame that can't run scripts or load anything from the internet; spreadsheets show as tables; links open straight into the app they live in.\n- Download it in its own format (.md, .html, .docx, .xlsx). Any Markdown document — including every workflow output — can also be downloaded as a Word file.\n- **Send it to someone**: ask the Executive to share an artifact with a person. It messages them the title and a link on their usual channel (the link opens in Open Executive, so it's for people who have access), or — if Google Workspace is connected — emails the file itself as an attachment (Word, Excel, web page or Markdown).\n- **Revise in chat**: opens a new chat about that artifact. The Executive rereads it, writes the new version, and archives the old one; the new version links back to the one it replaced.\n- The Executive remembers what it has written: it can list and reread its artifacts, and past artifacts surface in its answers when relevant.\n- Archive an artifact to tuck it away (with a quick undo) and restore it later.\n- Permanently delete one when you're sure, with a confirmation step.\n- Switch between **Active** and **Archived** views.\n\n**How to use:**\n\n1. Get something in here. Ask the Executive for a deliverable and say the format if you care — *\"as a Word doc\"*, *\"as a spreadsheet\"*, *\"as a one-page web page\"*, or *\"in my Google Sheets / Notion / OneDrive\"*. When you ask, it always publishes the result and replies with a link. For your own apps it uses whatever you've connected; with nothing connected it makes the file itself. It also drafts things unprompted when a finding is worth your time. Drafts appear as a card in the Briefing's **Needs you** lane, and every workflow run adds its output here automatically.\n2. Open **Artifacts** in the sidebar. Filter by **Drafts** or **Workflows**, and switch between **Active** and **Archived**.\n3. Click an artifact to read it; use **Copy** or a **Download** button to take it elsewhere, or **Revise in chat** to ask for changes.\n4. Hover over a row to **Archive** it (an **Undo** appears for a moment), **Restore** it from the Archived view, or **Delete permanently** (you'll be asked to confirm).\n\n**Example:** *\"Put the vendor pricing comparison in a spreadsheet for me.\"* A spreadsheet lands in **Needs you** and in **Artifacts**, previewed as tables with a **Download .xlsx** button. Later: *\"Add a column for contract length to that pricing spreadsheet\"* — the Executive rereads it, publishes the revised version, and archives the first one.\n\n*Note: archiving is a soft-delete — nothing is lost until you explicitly delete it.*","mermaid": null,- "generated_at": "2026-09-24T16:18:23.102858+00:00"+ "generated_at": "2026-09-24T17:32:29.068328+00:00"}diff --git a/packages/core/openexecutive/orchestrator/artifact_records.py b/packages/core/openexecutive/orchestrator/artifact_records.pyindex dacba797..100779d8 100644--- a/packages/core/openexecutive/orchestrator/artifact_records.py+++ b/packages/core/openexecutive/orchestrator/artifact_records.py@@ -13,6 +13,7 @@ route maps them to 400 / 404."""from __future__ import annotations+import refrom dataclasses import dataclassfrom typing import Any, Literal@@ -26,7 +27,11 @@ from openexecutive.alerts.store import (from openexecutive.alerts.store import (initialize_db as initialize_alerts_db,)-from openexecutive.orchestrator.artifact_formats import get_format+from openexecutive.orchestrator.artifact_formats import (+ ARTIFACT_FORMATS,+ EXPORT_TARGETS,+ get_format,+)from openexecutive.workflows.persistence import (delete_run,get_run,@@ -66,6 +71,58 @@ class ArtifactRecord:supersedes_id: str | None = None+@dataclass(frozen=True)+class ArtifactFile:+ """A rendered download: what `/download` serves and email attaches."""++ content: bytes+ filename: str+ mime: str+++_FILENAME_MAX = 60+_FILENAME_BAD = re.compile(r"[^a-z0-9]+")+++def artifact_downloads(rec: ArtifactRecord) -> list[str]:+ """Download targets for an artifact; the first is its own format.++ Empty for formats with no file (links)."""+ own = get_format(rec.format)+ if own.render_file is None:+ return []+ return [own.name, *EXPORT_TARGETS.get(own.name, ())]+++def render_artifact_file(rec: ArtifactRecord, as_: str | None = None) -> ArtifactFile:+ """Render `rec` as a file in its own format, or as export target `as_`.++ Raises `ArtifactNotFound` when the artifact has no such download (a link,+ or a target outside `artifact_downloads`). Rendering errors propagate.+ """+ targets = artifact_downloads(rec)+ target = (as_ or (targets[0] if targets else "")).strip().lower()+ if not targets or target not in targets:+ raise ArtifactNotFound(+ f"Artifact {rec.id!r} has no {target or 'file'} download"+ )+ fmt = ARTIFACT_FORMATS[target]+ assert fmt.render_file is not None and fmt.extension is not None+ return ArtifactFile(+ content=fmt.render_file(rec.stored or ""),+ filename=f"{_filename_stem(rec)}.{fmt.extension}",+ mime=fmt.mime,+ )+++def _filename_stem(rec: ArtifactRecord) -> str:+ stem = _FILENAME_BAD.sub("-", rec.title.lower()).strip("-")[:_FILENAME_MAX].strip("-")+ if stem:+ return stem+ kind, native_id = parse_artifact_id(rec.id)+ return f"{kind}-{native_id[:12]}"++def parse_artifact_id(composite_id: str) -> tuple[str, str]:"""Split `"{kind}:{native_id}"`, or raise `MalformedArtifactId`."""kind, sep, native_id = (composite_id or "").strip().partition(":")@@ -172,12 +229,15 @@ def delete_artifact(composite_id: str) -> ArtifactRecord:__all__ = ["DRAFT_SOURCE_LABEL",+ "ArtifactFile","ArtifactNotFound","ArtifactRecord","MalformedArtifactId",+ "artifact_downloads","delete_artifact","list_artifacts","load_artifact","parse_artifact_id",+ "render_artifact_file","set_archived",]diff --git a/packages/core/openexecutive/orchestrator/artifact_tools.py b/packages/core/openexecutive/orchestrator/artifact_tools.pyindex c7fee8e0..3481a985 100644--- a/packages/core/openexecutive/orchestrator/artifact_tools.py+++ b/packages/core/openexecutive/orchestrator/artifact_tools.py@@ -89,7 +89,12 @@ DRAFT_ARTIFACT_TOOL: dict[str, Any] = {"instead).\n\n""To revise an earlier artifact, read it with get_artifact, then ""publish the new version with `supersedes` set to its id; the old "- "version is archived."+ "version is archived.\n\n"+ "To deliver it: message_person(person_id, text, artifact_id) sends "+ "its title and link; to email the file itself, call the Gmail send "+ "or draft tool with attachments=[{\"artifact_id\": \"<id>\"}] (add "+ "\"as\": \"docx\" to send a Markdown artifact as Word) and it is "+ "rendered and attached for you."),"input_schema": {"type": "object",diff --git a/packages/core/openexecutive/orchestrator/mcp_gateway.py b/packages/core/openexecutive/orchestrator/mcp_gateway.pyindex dfcdbb7a..fc46ac4c 100644--- a/packages/core/openexecutive/orchestrator/mcp_gateway.py+++ b/packages/core/openexecutive/orchestrator/mcp_gateway.py@@ -1,5 +1,7 @@from __future__ import annotations+import asyncio+import base64import contextlibimport jsonimport logging@@ -260,6 +262,138 @@ def _roster_allow_set() -> set[str]:return allow+# Artifact attachments on one email. Gmail caps a message at 25 MB and base64+# inflates the payload by a third, so the rendered artifacts together stay+# well under it; the count cap bounds how much one tool call can make the+# server render (each entry is a full docx / xlsx build).+_MAX_ARTIFACT_ATTACHMENTS = 5+_MAX_ARTIFACT_ATTACHMENT_BYTES = 15 * 1024 * 1024+_ARTIFACT_ATTACHMENT_KEYS = frozenset({"artifact_id", "as"})+++def _recipients(arguments: dict[str, Any]) -> list[str]:+ """Every to/cc/bcc address on a Gmail call, for audit rows."""+ raw = [arguments.get(f) for f in _GMAIL_RECIPIENT_FIELDS]+ values = [+ str(v) for item in raw+ for v in (item if isinstance(item, list) else [item]) if v+ ]+ return [addr for _, addr in getaddresses(values) if addr]+++def _refuse_attachment(tool: str, arguments: dict[str, Any], reason: str) -> str:+ from openexecutive.audit import log_event as audit_log++ logger.warning("refused artifact attachment on %s: %s", tool, reason)+ audit_log(+ "artifact_attachment_refused",+ f"Refused an artifact attachment on {tool}: {reason[:160]}",+ actor="mcp_gateway",+ details={"tool": tool, "reason": reason, "recipients": _recipients(arguments)},+ )+ return json.dumps({"error": f"attachment: {reason}"})+++async def _expand_artifact_attachments(+ tool: str, arguments: dict[str, Any]+) -> tuple[dict[str, Any], list[str]] | str:+ """Replace `{"artifact_id": "alert:5", "as"?: "docx"}` attachment entries+ with the rendered file (`content` base64 + `filename` + `mime_type`, the+ shape workspace-mcp's Gmail tools accept).++ Lets the Executive email one of its artifacts without ever holding the+ bytes: the file is rendered server-side exactly as `/artifacts/{id}/+ download` serves it, and only artifact rows can resolve (see+ `artifact_records`). At most `_MAX_ARTIFACT_ATTACHMENTS` distinct entries+ (repeats are dropped) and `_MAX_ARTIFACT_ATTACHMENT_BYTES` in total;+ rendering runs off the event loop. Returns the (copied) arguments plus+ the attached artifact ids, or an audited JSON error string. Other+ attachment entries pass through untouched.+ """+ attachments = arguments.get("attachments")+ # Models sometimes stringify nested arguments, or send one object instead+ # of a list. Normalise both, so an artifact entry can never reach the MCP+ # unexpanded (workspace-mcp would skip it and send the mail without it).+ if isinstance(attachments, str) and "artifact_id" in attachments:+ try:+ attachments = json.loads(attachments)+ except json.JSONDecodeError:+ return _refuse_attachment(tool, arguments, "attachments is not valid JSON")+ if isinstance(attachments, dict):+ attachments = [attachments]+ if not isinstance(attachments, list) or not any(+ isinstance(a, dict) and "artifact_id" in a for a in attachments+ ):+ return arguments, []++ from openexecutive.orchestrator.artifact_records import (+ ArtifactNotFound,+ MalformedArtifactId,+ load_artifact,+ render_artifact_file,+ )++ wanted: list[tuple[str, str | None]] = []+ for entry in attachments:+ if not (isinstance(entry, dict) and "artifact_id" in entry):+ continue+ extra = set(entry) - _ARTIFACT_ATTACHMENT_KEYS+ if extra:+ return _refuse_attachment(tool, arguments, (+ "an artifact attachment takes only 'artifact_id' and an "+ f"optional 'as' format; got {sorted(extra)}"+ ))+ as_raw = entry.get("as")+ key = (str(entry.get("artifact_id") or "").strip(),+ str(as_raw).strip().lower() if as_raw else None)+ if key not in wanted:+ wanted.append(key)+ if len(wanted) > _MAX_ARTIFACT_ATTACHMENTS:+ return _refuse_attachment(tool, arguments, (+ f"at most {_MAX_ARTIFACT_ATTACHMENTS} artifacts per email; got {len(wanted)}"+ ))++ rendered: dict[tuple[str, str | None], dict[str, str]] = {}+ attached: list[str] = []+ total = 0+ for artifact_id, as_ in wanted:+ try:+ rec = await asyncio.to_thread(load_artifact, artifact_id)+ file = await asyncio.to_thread(render_artifact_file, rec, as_)+ except (MalformedArtifactId, ArtifactNotFound) as exc:+ return _refuse_attachment(tool, arguments, str(exc))+ except Exception:+ logger.exception("artifact attachment render failed: %s", artifact_id)+ return _refuse_attachment(tool, arguments, f"could not render {artifact_id!r}")+ total += len(file.content)+ if total > _MAX_ARTIFACT_ATTACHMENT_BYTES:+ return _refuse_attachment(tool, arguments, (+ f"artifacts total {total} bytes, over the "+ f"{_MAX_ARTIFACT_ATTACHMENT_BYTES}-byte email limit — send "+ "a link instead"+ ))+ rendered[(artifact_id, as_)] = {+ "content": base64.b64encode(file.content).decode("ascii"),+ "filename": file.filename,+ "mime_type": file.mime,+ }+ attached.append(rec.id)++ expanded: list[Any] = []+ emitted: set[tuple[str, str | None]] = set()+ for entry in attachments:+ if not (isinstance(entry, dict) and "artifact_id" in entry):+ expanded.append(entry)+ continue+ as_raw = entry.get("as")+ key = (str(entry.get("artifact_id") or "").strip(),+ str(as_raw).strip().lower() if as_raw else None)+ if key not in emitted:+ emitted.add(key)+ expanded.append(rendered[key])+ return {**arguments, "attachments": expanded}, attached++def _check_gmail_recipients(tool: str, arguments: dict[str, Any]) -> str | None:"""Return None if all recipients are allow-listed, else a JSON error string.@@ -750,10 +884,17 @@ class MCPGateway:logger.warning("call_tool: arguments was a string but not valid JSON — using empty dict")arguments = {}tool_name = tool_input.get("name", "")+ attached_artifacts: list[str] = []if tool_name in _GATED_GMAIL_TOOLS:blocked = _check_gmail_recipients(tool_name, arguments)if blocked is not None:return blocked+ # Only after the recipients pass: render any artifact the model+ # asked to attach, so a blocked send never renders anything.+ expanded = await _expand_artifact_attachments(tool_name, arguments)+ if isinstance(expanded, str):+ return expanded+ arguments, attached_artifacts = expandedif tool_name in _GATED_CALENDAR_TOOLS:blocked = _check_calendar_attendees(tool_name, arguments)if blocked is not None:@@ -773,6 +914,19 @@ class MCPGateway:# phantom linkage that would hydrate a reply that can never come.if tool_name == "google_workspace__send_gmail_message" and not _is_error_payload(result_text):_record_email_outbound_context(arguments)+ if attached_artifacts and not _is_error_payload(result_text):+ from openexecutive.audit import log_event as audit_log++ audit_log(+ "artifact_attached",+ f"Attached {', '.join(attached_artifacts)} via {tool_name}",+ actor="mcp_gateway",+ details={+ "tool": tool_name,+ "artifact_ids": attached_artifacts,+ "recipients": _recipients(arguments),+ },+ )return result_textasync def load_mcp_server(self, tool_input: dict[str, Any]) -> str:diff --git a/packages/core/openexecutive/orchestrator/schedule_tools.py b/packages/core/openexecutive/orchestrator/schedule_tools.pyindex a6314160..f2c6ad8b 100644--- a/packages/core/openexecutive/orchestrator/schedule_tools.py+++ b/packages/core/openexecutive/orchestrator/schedule_tools.py@@ -1119,7 +1119,10 @@ MESSAGE_PERSON_TOOL: dict[str, Any] = {"and you do NOT pass any channel id, handle, or snowflake. This is the ""preferred way to DM a single person: pass person_id and text, nothing ""else. If you only know a name or role, call lookup_person first to get "- "the person_id."+ "the person_id. To share one of your artifacts, also pass its "+ "artifact_id: the message gets the artifact's title and a link to it "+ "(the link opens in Open Executive, so it only works for people with "+ "access — to hand a file to anyone else, email it as an attachment)."),"input_schema": {"type": "object",@@ -1135,6 +1138,14 @@ MESSAGE_PERSON_TOOL: dict[str, Any] = {"type": "string","description": "Message body.",},+ "artifact_id": {+ "type": "string",+ "description": (+ "Optional artifact to share, e.g. 'alert:12' or "+ "'run:ab12…' (from draft_artifact / list_artifacts). Its "+ "title and link are appended to the message."+ ),+ },},"required": ["person_id", "text"],},@@ -1169,6 +1180,14 @@ async def handle_message_person(tool_input: dict[str, Any]) -> str:if not text.strip():return json.dumps({"error": "text must not be empty"})+ artifact_id = str(tool_input.get("artifact_id") or "").strip()+ if artifact_id:+ try:+ link_line = _artifact_link_line(artifact_id, get_settings().ui_base_url)+ except LookupError as exc:+ return json.dumps({"error": f"artifact_id: {exc}"})+ text = f"{text.rstrip()}\n\n{link_line}"+person = get_person(person_id)if person is None or person.archived:return json.dumps({"error": (@@ -1235,6 +1254,30 @@ async def handle_message_person(tool_input: dict[str, Any]) -> str:return await _alert_undeliverable_person(person, person_id, text, last_error)+def _artifact_link_line(artifact_id: str, ui_base_url: str) -> str:+ """`📄 <title> — <UI_BASE_URL>/artifacts/<id>` for a real artifact.++ Resolved through `artifact_records`, so only artifact rows (never an+ arbitrary alert) can be shared this way. Raises `LookupError` for a+ malformed or unknown id.+ """+ from urllib.parse import quote++ from openexecutive.orchestrator.artifact_records import (+ ArtifactNotFound,+ MalformedArtifactId,+ load_artifact,+ )++ try:+ rec = load_artifact(artifact_id)+ except (MalformedArtifactId, ArtifactNotFound) as exc:+ raise LookupError(str(exc)) from exc+ title = " ".join(rec.title.split())+ base = ui_base_url.rstrip("/")+ return f"📄 {title} — {base}/artifacts/{quote(rec.id, safe=':')}"++async def _alert_undeliverable_person(person: Any, person_id: int, text: str, last_error: str | None) -> str:diff --git a/packages/core/tests/unit/test_artifact_delivery.py b/packages/core/tests/unit/test_artifact_delivery.pynew file mode 100644index 00000000..f6d25234--- /dev/null+++ b/packages/core/tests/unit/test_artifact_delivery.py@@ -0,0 +1,366 @@+"""Delivering artifacts to people.++Two paths, both keyed on an artifact id and both resolved through+`orchestrator.artifact_records` (so only artifact rows can ever be shared):++- `message_person(..., artifact_id=...)` appends the artifact's title and a+ `UI_BASE_URL/artifacts/<id>` link to the DM.+- a Gmail send/draft through the MCP gateway may attach+ `{"artifact_id": ..., "as"?: ...}`; the gateway renders the file exactly as+ `/artifacts/<id>/download` serves it — only after the recipient gate passes.+"""+from __future__ import annotations++import asyncio+import base64+import io+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from docx import Document+from openpyxl import load_workbook++import openexecutive.orchestrator.mcp_gateway as gw_module+from openexecutive.alerts import store as alerts_store+from openexecutive.orchestrator.mcp_gateway import MCPGateway+from openexecutive.orchestrator.schedule_tools import handle_message_person+from openexecutive.people import store as people_store+from openexecutive.workflows import persistence as wf_persistence++EXEC_ADDR = "[email protected]"+UI = "https://oe.example.com/"++[email protected](autouse=True)+def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ db_path = tmp_path / "episodic.db"+ for module in (alerts_store, people_store, wf_persistence):+ monkeypatch.setattr(module, "DB_PATH", db_path)+ alerts_store.initialize_db(db_path)+ people_store.initialize_db()+ wf_persistence.initialize_runs_db(db_path)+ monkeypatch.setattr("openexecutive.audit.log_event", lambda *a, **k: None)+ return db_path+++def _artifact(fmt: str = "markdown", body: str = "# Q3 plan\n\nHire two engineers.",+ title: str = "Q3 plan", **extra: Any) -> str:+ aid = alerts_store.insert_alert(+ source="artifact", external_id=f"{fmt}-{title}", severity="medium",+ headline=title, body=body, topic_tags=["artifact"],+ artifact_format=fmt, **extra,+ )+ assert aid is not None+ return f"alert:{aid}"+++# --------------------------------------------------------------------------- #+# message_person(artifact_id=...)+# --------------------------------------------------------------------------- #+++def _dm_settings() -> SimpleNamespace:+ return SimpleNamespace(+ slack_bot_token=None, discord_bot_token="tok", telegram_bot_token=None,+ calendar_booking_enabled=False, mcp_enabled=False, ui_base_url=UI,+ )+++def _dm(payload: dict) -> tuple[dict, AsyncMock]:+ send = AsyncMock(return_value=None)+ with (+ patch("openexecutive.config.get_settings", return_value=_dm_settings()),+ patch("openexecutive.integrations.discord_bot.send_dm", send),+ patch("openexecutive.orchestrator.schedule_tools._record_send_to_activity"),+ ):+ result = json.loads(asyncio.run(handle_message_person(payload)))+ return result, send+++def _person() -> int:+ return people_store.upsert_person(+ full_name="Dana Ops", discord_user_id="100000000000000001",+ preferred_channel="discord",+ )+++def test_message_person_appends_artifact_title_and_link() -> None:+ cid = _artifact(title="Q3 hiring\nplan")+ result, send = _dm({"person_id": _person(), "text": "Here's the plan.",+ "artifact_id": cid})+ assert result["status"] == "sent"+ sent_text = send.await_args.args[1]+ assert sent_text == (+ f"Here's the plan.\n\n📄 Q3 hiring plan — "+ f"https://oe.example.com/artifacts/{cid}"+ )+++def test_message_person_links_workflow_run_artifact() -> None:+ wf_persistence.create_run("run-7", "board_prep", "Board deck", {})+ wf_persistence.complete_run("run-7", "# Deck")+ _, send = _dm({"person_id": _person(), "text": "Deck", "artifact_id": "run:run-7"})+ assert send.await_args.args[1].endswith("https://oe.example.com/artifacts/run:run-7")++[email protected]("bad", ["alert:999", "garbage", "alert:x"])+def test_message_person_rejects_unknown_artifact_and_sends_nothing(bad: str) -> None:+ result, send = _dm({"person_id": _person(), "text": "hi", "artifact_id": bad})+ assert "artifact_id" in result["error"]+ send.assert_not_awaited()+++def test_message_person_refuses_non_artifact_alert() -> None:+ other = alerts_store.insert_alert(source="email", external_id="e", severity="low",+ headline="Private", body="secret")+ result, send = _dm({"person_id": _person(), "text": "hi",+ "artifact_id": f"alert:{other}"})+ assert "error" in result+ send.assert_not_awaited()+++def test_message_person_without_artifact_is_unchanged() -> None:+ result, send = _dm({"person_id": _person(), "text": "plain"})+ assert result["status"] == "sent"+ assert send.await_args.args[1] == "plain"+++# --------------------------------------------------------------------------- #+# Gmail attachments through the MCP gateway+# --------------------------------------------------------------------------- #+++def _gateway() -> tuple[MCPGateway, AsyncMock]:+ gateway = MCPGateway()+ session = MagicMock()+ fake_result = MagicMock()+ fake_result.content = [MagicMock(text='{"ok": true}')]+ session.call_tool = AsyncMock(return_value=fake_result)+ gateway._session = session+ return gateway, session.call_tool+++def _send(arguments: dict[str, Any],+ tool: str = "google_workspace__send_gmail_message") -> tuple[str, AsyncMock]:+ people_store.upsert_person(full_name="Alice", email="[email protected]")+ gateway, session_call = _gateway()+ settings = SimpleNamespace(exec_email_address=EXEC_ADDR, email_poll_interval_seconds=60)+ with patch.object(gw_module, "get_settings", return_value=settings):+ result = asyncio.run(gateway.call_tool({"name": tool, "arguments": arguments}))+ return result, session_call+++def _forwarded_attachments(session_call: AsyncMock) -> list[dict]:+ assert session_call.await_count == 1+ forwarded = session_call.await_args.args[1]+ return forwarded["arguments"]["attachments"]++[email protected]("tool", [+ "google_workspace__send_gmail_message", "google_workspace__draft_gmail_message",+])+def test_gmail_attaches_artifact_as_its_own_format(tool: str) -> None:+ cid = _artifact()+ result, session_call = _send({"to": "[email protected]", "subject": "Plan",+ "body": "Attached.", "attachments": [{"artifact_id": cid}]},+ tool=tool)+ assert result == '{"ok": true}'+ (att,) = _forwarded_attachments(session_call)+ assert att["filename"] == "q3-plan.md"+ assert att["mime_type"].startswith("text/markdown")+ assert base64.b64decode(att["content"]).decode() == "# Q3 plan\n\nHire two engineers."+++def test_gmail_attaches_markdown_artifact_as_word() -> None:+ cid = _artifact()+ _, session_call = _send({"to": "[email protected]", "subject": "Plan", "body": "x",+ "attachments": [{"artifact_id": cid, "as": "docx"}]})+ (att,) = _forwarded_attachments(session_call)+ assert att["filename"] == "q3-plan.docx"+ doc = Document(io.BytesIO(base64.b64decode(att["content"])))+ assert any(p.text == "Hire two engineers." for p in doc.paragraphs)+++def test_gmail_attaches_spreadsheet_and_keeps_other_attachments() -> None:+ cid = _artifact("xlsx", json.dumps({"summary": "", "sheets": [+ {"name": "Tiers", "columns": ["tier"], "rows": [["pro"]]}]}), title="Pricing")+ passthrough = {"path": "/tmp/already-downloaded.pdf"}+ _, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [passthrough, {"artifact_id": cid}]})+ first, second = _forwarded_attachments(session_call)+ assert first == passthrough+ wb = load_workbook(io.BytesIO(base64.b64decode(second["content"])))+ assert wb["Tiers"]["A2"].value == "pro"+++def test_blocked_recipient_never_renders_the_artifact(monkeypatch: pytest.MonkeyPatch) -> None:+ rendered: list[str] = []+ import openexecutive.orchestrator.artifact_records as records++ real = records.render_artifact_file++ def _spy(rec, as_=None): # noqa: ANN001, ANN202+ rendered.append(rec.id)+ return real(rec, as_)++ monkeypatch.setattr(records, "render_artifact_file", _spy)+ cid = _artifact()+ result, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": cid}]})+ assert "error" in json.loads(result)+ assert session_call.await_count == 0+ assert rendered == []++[email protected]("entry, needle", [+ ({"artifact_id": "alert:4242"}, "not found"),+ ({"artifact_id": "nonsense"}, "Malformed"),+ ({"artifact_id": "ALERT_PLACEHOLDER", "as": "xlsx"}, "no xlsx download"),+ ({"artifact_id": "ALERT_PLACEHOLDER", "path": "/etc/passwd"}, "only 'artifact_id'"),+])+def test_gmail_artifact_attachment_errors_send_nothing(entry: dict, needle: str) -> None:+ cid = _artifact()+ entry = {k: (cid if v == "ALERT_PLACEHOLDER" else v) for k, v in entry.items()}+ result, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [entry]})+ assert needle in json.loads(result)["error"]+ assert session_call.await_count == 0+++def test_gmail_refuses_non_artifact_alert_and_links() -> None:+ other = alerts_store.insert_alert(source="email", external_id="e", severity="low",+ headline="Private", body="secret")+ link = _artifact("link", "Summary", title="Sheet", artifact_url="https://x.example/s")+ for cid in (f"alert:{other}", link):+ result, session_call = _send({"to": "[email protected]", "subject": "s",+ "body": "b", "attachments": [{"artifact_id": cid}]})+ assert "error" in json.loads(result)+ assert session_call.await_count == 0+++def test_gmail_rejects_oversized_artifact(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(gw_module, "_MAX_ARTIFACT_ATTACHMENT_BYTES", 10)+ cid = _artifact()+ result, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": cid}]})+ assert "email limit" in json.loads(result)["error"]+ assert session_call.await_count == 0+++def test_gmail_without_artifact_attachments_is_untouched() -> None:+ args = {"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"path": "/tmp/x.pdf"}]}+ _, session_call = _send(dict(args))+ assert session_call.await_args.args[1]["arguments"] == args+++# --------------------------------------------------------------------------- #+# Review follow-ups: shapes, caps, dedupe, audit, fallback+# --------------------------------------------------------------------------- #+++def audit(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict]]:+ events: list[tuple[str, dict]] = []+ monkeypatch.setattr(+ "openexecutive.audit.log_event",+ lambda event, summary, **kw: events.append((event, kw.get("details", {}))),+ )+ return events++[email protected]("shape", ["json-string", "single-object"])+def test_gmail_expands_stringified_or_single_attachment(shape: str) -> None:+ cid = _artifact()+ entry = {"artifact_id": cid}+ attachments: Any = json.dumps([entry]) if shape == "json-string" else entry+ _, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": attachments})+ (att,) = _forwarded_attachments(session_call)+ assert att["filename"] == "q3-plan.md" and "artifact_id" not in att+++def test_gmail_refuses_unparseable_artifact_attachment_string() -> None:+ result, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": '[{"artifact_id": "alert:1"'})+ assert "not valid JSON" in json.loads(result)["error"]+ assert session_call.await_count == 0+++def test_gmail_normalises_as_and_dedupes_repeats() -> None:+ cid = _artifact()+ _, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": cid, "as": " DOCX "},+ {"artifact_id": cid, "as": "docx"}]})+ (att,) = _forwarded_attachments(session_call)+ assert att["filename"] == "q3-plan.docx"+++def test_gmail_caps_distinct_artifact_attachments(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(gw_module, "_MAX_ARTIFACT_ATTACHMENTS", 2)+ ids = [_artifact(title=f"Doc {i}") for i in range(3)]+ result, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": i} for i in ids]})+ assert "at most 2 artifacts" in json.loads(result)["error"]+ assert session_call.await_count == 0+++def test_gmail_total_size_cap_spans_attachments(monkeypatch: pytest.MonkeyPatch) -> None:+ one = len(b"# Q3 plan\n\nHire two engineers.")+ monkeypatch.setattr(gw_module, "_MAX_ARTIFACT_ATTACHMENT_BYTES", one + 5)+ a, b = _artifact(title="A"), _artifact(title="B")+ result, session_call = _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": a}, {"artifact_id": b}]})+ assert "email limit" in json.loads(result)["error"]+ assert session_call.await_count == 0+++def test_gmail_audits_attachment_after_successful_send(audit: list) -> None:+ cid = _artifact()+ _send({"to": "Alice <[email protected]>", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": cid}]})+ attached = [d for e, d in audit if e == "artifact_attached"]+ assert attached == [{"tool": "google_workspace__send_gmail_message",+ "artifact_ids": [cid], "recipients": ["[email protected]"]}]+++def test_gmail_does_not_audit_attachment_when_send_fails(audit: list) -> None:+ people_store.upsert_person(full_name="Alice", email="[email protected]")+ gateway, session_call = _gateway()+ session_call.return_value.content = [MagicMock(text='{"error": "quota"}')]+ settings = SimpleNamespace(exec_email_address=EXEC_ADDR, email_poll_interval_seconds=60)+ with patch.object(gw_module, "get_settings", return_value=settings):+ asyncio.run(gateway.call_tool({"name": "google_workspace__send_gmail_message",+ "arguments": {"to": "[email protected]", "subject": "s",+ "body": "b", "attachments": [+ {"artifact_id": _artifact()}]}}))+ assert not [e for e, _ in audit if e == "artifact_attached"]+++def test_gmail_refusal_is_audited_with_recipients(audit: list) -> None:+ _send({"to": "[email protected]", "subject": "s", "body": "b",+ "attachments": [{"artifact_id": "alert:4242"}]})+ refused = [d for e, d in audit if e == "artifact_attachment_refused"]+ assert len(refused) == 1 and refused[0]["recipients"] == ["[email protected]"]+++def test_undeliverable_person_alert_carries_the_link() -> None:+ cid = _artifact()+ pid = people_store.upsert_person(full_name="No Channel") # no DM ids at all+ created: list[dict] = []++ async def _fake_alert(payload: dict) -> str:+ created.append(payload)+ return json.dumps({"ok": True})++ with (+ patch("openexecutive.config.get_settings", return_value=_dm_settings()),+ patch("openexecutive.orchestrator.alert_tools.handle_create_alert", _fake_alert),+ ):+ asyncio.run(handle_message_person({"person_id": pid, "text": "FYI",+ "artifact_id": cid}))+ assert created and f"https://oe.example.com/artifacts/{cid}" in created[0]["body"]