Skip to content

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

fix(memory): record only the person's own words in peer memory (#185)

Rufusc32cf49c4313
diff --git a/packages/core/openexecutive/api/models.py b/packages/core/openexecutive/api/models.py
index a2e688aa..91dcbff0 100644
--- a/packages/core/openexecutive/api/models.py
+++ b/packages/core/openexecutive/api/models.py
@@ -65,6 +65,13 @@ class ChatRequest(BaseModel):
# would contradict `_clean_client_turn_id`, which drops it and carries on.
# The max_length is a size bound, not a format check.
client_turn_id: str | None = Field(None, max_length=64)
+ # What peer memory records as the caller's words for this turn, when
+ # `message` carries text the caller did not write — a briefing handoff
+ # seeds the turn with the Executive's own card body. Absent → `message`.
+ # Recorded under the caller's own peer and, like `message` would be, in
+ # the shared memory of each department consulted that turn; it is not in
+ # the transcript, so the chat_turn audit row keeps it next to `message`.
+ memory_text: str | None = Field(None, min_length=1, max_length=2000)
class StopChatRequest(BaseModel):
diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.py
index 0b906290..eb3bc384 100644
--- a/packages/core/openexecutive/api/routes/chat.py
+++ b/packages/core/openexecutive/api/routes/chat.py
@@ -542,13 +542,16 @@ async def _run_chat_turn(
request: Request,
page_context: PageContext | None = None,
client_turn_id: str | None = None,
+ memory_text: str | None = None,
) -> StreamingResponse:
"""Shared streaming-chat handler for both the JSON and multipart routes.
`message` is the (already attachment-augmented) text the Executive will
see and that we persist as the user turn. `attachment_blocks` carries
image content blocks; document text is expected to already be inlined in
- `message` by the caller.
+ `message` by the caller. `memory_text`, when set, is what peer memory
+ records as the caller's words instead of `message` (see
+ `Executive.stream_chat`).
"""
from openexecutive.config import get_settings
from openexecutive.knowledge.retriever import retrieve
@@ -621,7 +624,10 @@ async def _run_chat_turn(
"is_first_turn": is_first_turn,
"attachment_count": len(attachment_blocks or []),
},
- full={"message": message},
+ # memory_text reaches the caller's peer AND every consulted
+ # department's shared memory, but never the transcript: keep it
+ # auditable next to the message it stood in for.
+ full={"message": message, "memory_text": memory_text},
)
# Let the caller schedule to their own addresses. Runs per turn rather than
@@ -836,6 +842,7 @@ async def _run_chat_turn(
briefing_context=briefing_context,
page_context_block=page_context_block,
turn_id=turn_id,
+ memory_text=memory_text,
).__aiter__()
else:
stream = executive.stream_chat(
@@ -850,6 +857,7 @@ async def _run_chat_turn(
briefing_context=briefing_context,
page_context_block=page_context_block,
turn_id=turn_id,
+ memory_text=memory_text,
).__aiter__()
# Whole-turn deadline, not per-chunk: a stream that drips bytes
@@ -1167,6 +1175,7 @@ async def chat_stream(body: ChatRequest, request: Request) -> StreamingResponse:
request=request,
page_context=body.page_context,
client_turn_id=body.client_turn_id,
+ memory_text=body.memory_text,
)
@@ -1225,9 +1234,11 @@ async def chat_upload(
text_parts: list[str] = []
image_blocks: list[dict[str, Any]] = []
+ filenames: list[str] = []
for upload in files:
filename = upload.filename or "attachment"
+ filenames.append(filename)
data = await upload.read()
if len(data) > _MAX_BYTES_PER_FILE:
raise HTTPException(
@@ -1265,6 +1276,9 @@ async def chat_upload(
attachment_blocks=image_blocks or None,
request=request,
client_turn_id=client_turn_id,
+ # The extracted document text is the document's words, not the
+ # caller's: recorded in peer memory it becomes facts about the caller.
+ memory_text=f"{message}\n\n[Attached: {', '.join(filenames)}]",
)
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 033f44c4..6b437864 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -1142,7 +1142,22 @@ peer_memory:
place where a person's words were misattributed to the Executive.
The async ``peer()`` is a get-or-create POST that applies a changed
configuration to an existing peer, so the flag is re-asserted on
- every sync for free. ``co_present_person_ids``
+ every sync for free.
+
+ The "person's message" is ``memory_text`` when the entry point
+ passes one (``Executive.chat`` / ``stream_chat`` /
+ ``stream_chat_with_committee``), else the LLM-facing
+ ``user_message``. Honcho derives facts about a person from every
+ message posted under their peer, and several prompts carry text the
+ person did not write. Observed in production: an inbound email's
+ framing, headers (the Executive's own address in ``To:``) and quoted
+ chain produced "<person> is associated with <exec address>" and
+ "<person> received an email from <person>"; a briefing Discuss seed
+ quoting the Executive's artifact produced "<person> assigned a
+ colleague to …". So the email poller passes ``_email_memory_text`` (subject, the
+ sender's new text, attachment filenames), ``/chat/upload`` passes
+ the typed text plus filenames, and the briefing handoffs send a short
+ ``memory_text`` line through ``POST /chat``. ``co_present_person_ids``
enumerates other humans in the conversation context (Discord
thread members, Slack thread participants, email To+Cc) so
Honcho can store them as session peers — the data shape that
@@ -3583,6 +3598,17 @@ integrations:
to-roster) instead of wasting a turn discovering the outbound
block. The outbound gate at ``mcp_gateway._check_gmail_recipients``
is the actual security boundary against auto-replying to spam.
+ Peer memory records ``_email_memory_text(raw)`` as the sender's
+ words, not the prompt: the subject, the body cut at the first quoted
+ or forwarded message (Gmail's possibly-wrapped "On … wrote:",
+ "-----Original Message-----", an Outlook From:/Sent: block, "--
+ Forwarded message --", ">" lines) and the ``--- ATTACHMENTS ---``
+ filenames — see ``honcho.sync_turn``. Only computed for a rostered
+ sender (an unrostered one has no peer). The email text is sender-
+ controlled, so attachment lines are split from the right and length-
+ capped rather than matched with one regex: a pattern with adjacent
+ ``\s+`` / ``.+?`` groups backtracked cubically on a long run of spaces
+ (30 s at 4,000), stalling the whole API process from one inbound email.
Like every other channel adapter, the poller calls
``Executive.chat`` on the standard path — it does NOT force
``committee_review=True``. Committee review is a per-request
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index 3ec088a7..b3315487 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | Skill registry CRUD and search. |\n| `evals` | `/evals/scenarios`, `/evals/runs` | Eval scenarios and run results. |\n| `memories` | `/memories/{decisions,initiatives,advice}`, `GET /memories/people` | Episodic-memory record management, plus the read-only peer-memory overview the Pulse People tab reads (`{status: ok|disabled|error, people: [...], conclusion_total}`; `?recent=` 1–50, default 5). |\n| `review` | `/review/items`, `/review/stats`, `/review/trusted-defaults`, `POST /review/curate`, `POST /review/bulk-approve` | Knowledge review queue and annotations. Shipped knowledge registers as a trusted default (`approved` with a NULL `reviewed_at`), so the queue starts empty; `curate` (`{domain, action: start|stop}`, domain required) opts one domain in or out, and `trusted-defaults` returns domain → unreviewed count. `bulk-approve` takes a non-empty `domain`, `item_ids` (max 500) or `all_pending: true`, and 400s with no selector; it returns `{approved_count, item_ids}`. |\n| `onboarding` | `/onboard/interview/start`, `/onboard/interview/message`, `/onboard/interview/draft`, `/onboard/interview/{id}`, `/onboard/interview/commit` | Conversational company setup. The `onboarding_interviewer` agent asks clarifying questions, then emits a draft profile + people + departments. **Nothing is persisted until `POST /onboard/interview/commit`** — the interview itself never writes. `start` is multipart (description + optional deck/one-pager uploads). |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
"mermaid": null,
- "generated_at": "2026-09-23T15:10:14.978268+00:00"
+ "generated_at": "2026-09-23T16:11:27Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/integrations.json b/packages/core/openexecutive/architecture/prebuilt/integrations.json
index 8b50bbe5..52d63664 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`) — IMAP poll loop; strips Reply-To, filters auto-replies.\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`) — IMAP poll loop; strips Reply-To, filters auto-replies. 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.",
"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-22T21:22:19.744247+00:00"
+ "generated_at": "2026-09-23T16:11:27Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
index df10a953..952bdf2c 100644
--- a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
+++ b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
@@ -1,7 +1,7 @@
{
"section_id": "peer_memory",
"title": "Peer Memory (Person + Department)",
- "markdown": "An external, peer-keyed memory layer gives the Executive durable cross-channel recall, sitting on top of Honcho via `openexecutive.memory.honcho_client`. The `HONCHO_ENABLED` env var gates it; when false every entry point short-circuits with `outcome=disabled` and behavior matches the pre-Honcho posture.\n\n### Two scopes\n\n- **Per-person**, keyed by `Person.id` — a user chatting from Discord, Telegram, email, or web is one peer card, so facts shared in any channel surface in the others. Each entry point resolves the caller to a `Person.id` (channel-ID lookups for adapters; `x-caller-email` for web).\n- **Per-department**, keyed by `department_<slug>` — each department accumulates an institutional voice from dept-scoped decisions, advice, committee outcomes, and dept-bound specialist turns.\n\n### Flow\n\n`prefetch` runs once per turn and injects a `<peer_memory>` block into the user turn (empty on timeout or error). `HONCHO_PREFETCH_MODE` picks how the block is produced. `representation` (the default) reads the person's peer card and the derived conclusions most relevant to the inbound message straight from Honcho (`peer.context(search_query=…)`, `HONCHO_PREFETCH_MAX_CONCLUSIONS` of them, default 20): a GET with no LLM behind it, about 100 ms self-hosted. The block keeps whole lines only, up to a size cap (a line that does not fit is dropped, never cut), strips control characters and defangs a literal closing tag, since conclusions derive from text anyone who can email the Executive wrote. A person Honcho knows nothing about yet yields no block and an `empty` audit outcome. `dialectic` asks Honcho's chat endpoint with the message as the question and injects the synthesized prose (an LLM call, seconds), where `reasoning_level` trades latency for depth. The mode applies to every per-person prefetch, committee turns included. Only `prefetch_department` (one dialectic question per consulted specialist that maps to a department, yielding `<department_memory>`) and the `ask_about_person` tool always use the chat endpoint: they are deliberate questions off the inline path, the split Honcho's own guidance draws between `context()` for per-turn grounding and `chat()` for reasoned answers. After the response, `sync_turn` and `sync_department_turn` persist the exchange as fire-and-forget background tasks that never block the user. The Executive's reply is written under an `executive` peer resolved with `observe_me=false`: the person's representation sees both sides of the exchange, but Honcho no longer derives a representation of the Executive itself, which nothing read and which is where a person's words were occasionally misattributed to the Executive. Both record the person's words only: the `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\n### Prefetch budget\n\nIn representation mode the prefetch is a single read with no LLM behind it: it runs on `HONCHO_PREFETCH_TIMEOUT_S` unscaled and `reasoning_level` is ignored. The rest of this section is the dialectic mode.\n\n`HONCHO_PREFETCH_TIMEOUT_S` is the knob for the **fast per-turn path** and is used unscaled there. The two per-turn callers pick different levels on purpose: `stream_chat` awaits the prefetch inline before the first streamed byte and defaults to `minimal`, the cheapest level, after `low` was measured hitting the ~5 s tail for peers with large representations; the chat route runs the prefetch inside the same gather as knowledge and episodic retrieval, so its `low` adds no dead air of its own and buys a fuller answer. Only the deliberate levels scale off it — `medium` 4x, `high` 5x, `max` 6x — capped by an absolute ceiling and never taken below the configured base. At the default 3s base that is 12s for `medium` with `high`/`max` at the 15s ceiling; at a 10s base every deliberate level *is* the ceiling. The multipliers only differentiate below it — the ceiling is the binding constraint at realistic bases, by design.\n\nHoncho's dialectic latency scales steeply with the level (roughly 2s at `low` against 8s at `medium`), so a single flat budget made the deeper levels unreachable: every `medium` call — the committee path — timed out and the turn silently ran with no peer memory at all, which is strictly worse than having asked for `low`. `medium` gets more headroom than its measurement alone implies because the budget spans `peer()` plus `chat()`, and a budget set at the mean still times out on half the calls.\n\nThe fast levels stay unscaled for two reasons: `prefetch` is awaited inline before the first streamed byte, so multiplying the base there would add dead air to every ordinary turn; and a multiplier above 1.0 flattens every level onto the ceiling once the base approaches it, which would make the operator's knob stop distinguishing the two paths. Each prefetch audit row records the `timeout_s` it ran under.\n\nThe SDK client's HTTP timeout is an **outer** bound, kept strictly greater than every *per-call* budget; the aggregate ceilings on whole passes are deliberately not folded in, since it applies per request and would otherwise hand every unbudgeted call a bound several times too long. Because it is no longer a tight bound, all three fire-and-forget bodies (person sync, department sync, department note) — whose individual calls are not separately budgeted — carry their own aggregate ceiling, as does the session listing in the workspace purge.\n\n### Peer identity\n\nPeers are keyed by `Person.id`, so the only identity signal Honcho gets from the key alone is a bare integer — and its dreaming agent concludes that the number *is* the person's name (observed in production as a card reading `IDENTITY: Name: 1`). Because cards are injected into the dialectic system prompt on every `chat()`, that error propagates into every later answer about that person. So both sync paths seed each person peer's card from the roster, for the sender, the department-turn originator, and co-present peers alike.\n\nThe card carries the **name only** — email and role would export roster PII to a third-party memory service, including for people who were merely cc'd, and neither is needed to fix the defect. `set_card` replaces the whole card, so only `IDENTITY:` lines are swapped and the deriver's own `ATTRIBUTE:` / `RELATIONSHIP:` lines survive; the existing card is split on physical lines first, since one list element may itself span lines and hide an identity claim on its second.\n\nRoster values are attacker-reachable — `upsert_person` is a chat tool an inbound email sender can reach — so a value is NFKC-normalised, stripped of control and format characters, whitespace-flattened, length-capped, and then held to an **allow-list** of letters, combining marks, digits and a small punctuation set, with the colon lookalikes the category allow-list would otherwise admit **stripped out** — taken from Unicode's confusables data (everything it maps to `:`), not from character names, since U+A4FD `ꓽ` is a Lisu *tone letter* whose name never says colon. They are stripped rather than grounds for refusing the value, because the visarga is the nominative ending in formal Devanagari and Gujarati names: refusing would leave those people never seeded, while stripping keeps the name as its stem form and still lets no colon shape reach the card. Modifier letters as a class stay allowed (々 in 佐々木, ー in ジョーンズ, ʻ in Hawaiʻi). A deny-list of structure tokens is not enough here: the consumer is an LLM system prompt rather than a parser, so `ATTRIBUTE :`, a fullwidth colon and a homoglyph all read the same to the model while defeating a literal match. The allow-list refuses every colon variant, which is what card structure depends on — checked by an exhaustive test over every Unicode codepoint whose name contains COLON plus an explicit test of the confusables the names miss. It does **not** stop a value that is merely persuasive prose — OE already embeds `full_name` in its own system prompt, so that exposure is pre-existing rather than introduced here.\n\nSeeding runs *after* the message write and *outside* the sync ceiling, and is audited as its own `seed_identity` row (`ok` only when no peer's attempt failed; `error` when any did, with the `failed` count on the row; `timeout` when the pass or the roster read hit its ceiling; `empty` when there was nobody to seed) — so the sync row is a pure record of the persist, emitted the instant the write lands, and a slow card round trip can neither delay nor replace it. It is bounded per peer *and* per pass, and is best-effort. It is memoized per `(workspace, person)` on the facts sent with a recheck interval — a rename re-seeds immediately, and because the deriver keeps re-deriving identity from the peer id, a one-shot memo would let `IDENTITY: Name: 1` come back unnoticed. A failed attempt is memoized separately and briefly — including every peer a pass-ceiling cut-off left in flight or unreached — so a degraded card endpoint is probed once per interval rather than once per peer per turn.\n\n### Cross-pollination & isolation\n\nWhen a person turn touches a department, the dept peer joins the person's session as a co-present peer — the hybrid peer graph that lets later queries synthesize across both timelines, with synthesis depth degrading at greater peer-graph distance. Demo fixtures run in a sacrificial `openexec-fixture-<name>` workspace so demo turns never pollute real peer cards. Every wrapper call emits a `peer_memory` audit row (`op` + `outcome`) into the per-turn flow at `/audit/session/{id}`.",
+ "markdown": "An external, peer-keyed memory layer gives the Executive durable cross-channel recall, sitting on top of Honcho via `openexecutive.memory.honcho_client`. The `HONCHO_ENABLED` env var gates it; when false every entry point short-circuits with `outcome=disabled` and behavior matches the pre-Honcho posture.\n\n### Two scopes\n\n- **Per-person**, keyed by `Person.id` — a user chatting from Discord, Telegram, email, or web is one peer card, so facts shared in any channel surface in the others. Each entry point resolves the caller to a `Person.id` (channel-ID lookups for adapters; `x-caller-email` for web).\n- **Per-department**, keyed by `department_<slug>` — each department accumulates an institutional voice from dept-scoped decisions, advice, committee outcomes, and dept-bound specialist turns.\n\n### Flow\n\n`prefetch` runs once per turn and injects a `<peer_memory>` block into the user turn (empty on timeout or error). `HONCHO_PREFETCH_MODE` picks how the block is produced. `representation` (the default) reads the person's peer card and the derived conclusions most relevant to the inbound message straight from Honcho (`peer.context(search_query=…)`, `HONCHO_PREFETCH_MAX_CONCLUSIONS` of them, default 20): a GET with no LLM behind it, about 100 ms self-hosted. The block keeps whole lines only, up to a size cap (a line that does not fit is dropped, never cut), strips control characters and defangs a literal closing tag, since conclusions derive from text anyone who can email the Executive wrote. A person Honcho knows nothing about yet yields no block and an `empty` audit outcome. `dialectic` asks Honcho's chat endpoint with the message as the question and injects the synthesized prose (an LLM call, seconds), where `reasoning_level` trades latency for depth. The mode applies to every per-person prefetch, committee turns included. Only `prefetch_department` (one dialectic question per consulted specialist that maps to a department, yielding `<department_memory>`) and the `ask_about_person` tool always use the chat endpoint: they are deliberate questions off the inline path, the split Honcho's own guidance draws between `context()` for per-turn grounding and `chat()` for reasoned answers. After the response, `sync_turn` and `sync_department_turn` persist the exchange as fire-and-forget background tasks that never block the user. The Executive's reply is written under an `executive` peer resolved with `observe_me=false`: the person's representation sees both sides of the exchange, but Honcho no longer derives a representation of the Executive itself, which nothing read and which is where a person's words were occasionally misattributed to the Executive. Both record the person's words only. Honcho derives facts about a person from everything posted under their peer, so a turn whose prompt carries text the person did not write passes `memory_text` to `Executive.chat` / `stream_chat` / `stream_chat_with_committee`, and that — not the prompt — is what both syncs post: an inbound email records its subject, the sender's new text and the attachment filenames (never the \"You have an inbound email\" framing, the headers with the Executive's own address in `To:`, the `[POLICY]` notice or the quoted chain, which held the Executive's own earlier email and taught Honcho that the sender *was* the Executive); a web upload records the typed text and filenames, not the extracted document text; a briefing handoff records a short line of what the user asked (\"Asked to discuss the flagged artifact …\"), not the Executive's card body it seeds. Without `memory_text` the prompt is recorded, as before. The `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is also stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\n### Prefetch budget\n\nIn representation mode the prefetch is a single read with no LLM behind it: it runs on `HONCHO_PREFETCH_TIMEOUT_S` unscaled and `reasoning_level` is ignored. The rest of this section is the dialectic mode.\n\n`HONCHO_PREFETCH_TIMEOUT_S` is the knob for the **fast per-turn path** and is used unscaled there. The two per-turn callers pick different levels on purpose: `stream_chat` awaits the prefetch inline before the first streamed byte and defaults to `minimal`, the cheapest level, after `low` was measured hitting the ~5 s tail for peers with large representations; the chat route runs the prefetch inside the same gather as knowledge and episodic retrieval, so its `low` adds no dead air of its own and buys a fuller answer. Only the deliberate levels scale off it — `medium` 4x, `high` 5x, `max` 6x — capped by an absolute ceiling and never taken below the configured base. At the default 3s base that is 12s for `medium` with `high`/`max` at the 15s ceiling; at a 10s base every deliberate level *is* the ceiling. The multipliers only differentiate below it — the ceiling is the binding constraint at realistic bases, by design.\n\nHoncho's dialectic latency scales steeply with the level (roughly 2s at `low` against 8s at `medium`), so a single flat budget made the deeper levels unreachable: every `medium` call — the committee path — timed out and the turn silently ran with no peer memory at all, which is strictly worse than having asked for `low`. `medium` gets more headroom than its measurement alone implies because the budget spans `peer()` plus `chat()`, and a budget set at the mean still times out on half the calls.\n\nThe fast levels stay unscaled for two reasons: `prefetch` is awaited inline before the first streamed byte, so multiplying the base there would add dead air to every ordinary turn; and a multiplier above 1.0 flattens every level onto the ceiling once the base approaches it, which would make the operator's knob stop distinguishing the two paths. Each prefetch audit row records the `timeout_s` it ran under.\n\nThe SDK client's HTTP timeout is an **outer** bound, kept strictly greater than every *per-call* budget; the aggregate ceilings on whole passes are deliberately not folded in, since it applies per request and would otherwise hand every unbudgeted call a bound several times too long. Because it is no longer a tight bound, all three fire-and-forget bodies (person sync, department sync, department note) — whose individual calls are not separately budgeted — carry their own aggregate ceiling, as does the session listing in the workspace purge.\n\n### Peer identity\n\nPeers are keyed by `Person.id`, so the only identity signal Honcho gets from the key alone is a bare integer — and its dreaming agent concludes that the number *is* the person's name (observed in production as a card reading `IDENTITY: Name: 1`). Because cards are injected into the dialectic system prompt on every `chat()`, that error propagates into every later answer about that person. So both sync paths seed each person peer's card from the roster, for the sender, the department-turn originator, and co-present peers alike.\n\nThe card carries the **name only** — email and role would export roster PII to a third-party memory service, including for people who were merely cc'd, and neither is needed to fix the defect. `set_card` replaces the whole card, so only `IDENTITY:` lines are swapped and the deriver's own `ATTRIBUTE:` / `RELATIONSHIP:` lines survive; the existing card is split on physical lines first, since one list element may itself span lines and hide an identity claim on its second.\n\nRoster values are attacker-reachable — `upsert_person` is a chat tool an inbound email sender can reach — so a value is NFKC-normalised, stripped of control and format characters, whitespace-flattened, length-capped, and then held to an **allow-list** of letters, combining marks, digits and a small punctuation set, with the colon lookalikes the category allow-list would otherwise admit **stripped out** — taken from Unicode's confusables data (everything it maps to `:`), not from character names, since U+A4FD `ꓽ` is a Lisu *tone letter* whose name never says colon. They are stripped rather than grounds for refusing the value, because the visarga is the nominative ending in formal Devanagari and Gujarati names: refusing would leave those people never seeded, while stripping keeps the name as its stem form and still lets no colon shape reach the card. Modifier letters as a class stay allowed (々 in 佐々木, ー in ジョーンズ, ʻ in Hawaiʻi). A deny-list of structure tokens is not enough here: the consumer is an LLM system prompt rather than a parser, so `ATTRIBUTE :`, a fullwidth colon and a homoglyph all read the same to the model while defeating a literal match. The allow-list refuses every colon variant, which is what card structure depends on — checked by an exhaustive test over every Unicode codepoint whose name contains COLON plus an explicit test of the confusables the names miss. It does **not** stop a value that is merely persuasive prose — OE already embeds `full_name` in its own system prompt, so that exposure is pre-existing rather than introduced here.\n\nSeeding runs *after* the message write and *outside* the sync ceiling, and is audited as its own `seed_identity` row (`ok` only when no peer's attempt failed; `error` when any did, with the `failed` count on the row; `timeout` when the pass or the roster read hit its ceiling; `empty` when there was nobody to seed) — so the sync row is a pure record of the persist, emitted the instant the write lands, and a slow card round trip can neither delay nor replace it. It is bounded per peer *and* per pass, and is best-effort. It is memoized per `(workspace, person)` on the facts sent with a recheck interval — a rename re-seeds immediately, and because the deriver keeps re-deriving identity from the peer id, a one-shot memo would let `IDENTITY: Name: 1` come back unnoticed. A failed attempt is memoized separately and briefly — including every peer a pass-ceiling cut-off left in flight or unreached — so a degraded card endpoint is probed once per interval rather than once per peer per turn.\n\n### Cross-pollination & isolation\n\nWhen a person turn touches a department, the dept peer joins the person's session as a co-present peer — the hybrid peer graph that lets later queries synthesize across both timelines, with synthesis depth degrading at greater peer-graph distance. Demo fixtures run in a sacrificial `openexec-fixture-<name>` workspace so demo turns never pollute real peer cards. Every wrapper call emits a `peer_memory` audit row (`op` + `outcome`) into the per-turn flow at `/audit/session/{id}`.",
"mermaid": "flowchart TD\n Turn[\"Executive turn\"]\n Gate{\"HONCHO_ENABLED\"}\n Pre[\"prefetch: representation read (default)<br/>or dialectic query; prefetch_department: dialectic\"]\n Inj[\"peer_memory + department_memory<br/>injected into USER turn\"]\n Sync[\"sync_turn / sync_department_turn<br/>fire-and-forget\"]\n Honcho[\"Honcho peers<br/>person + department\"]\n Audit[\"peer_memory audit row\"]\n Turn --> Gate\n Gate -->|enabled| Pre\n Pre -->|context() / chat()| Honcho\n Honcho --> Inj\n Inj --> Turn\n Turn -->|after response| Sync\n Sync -->|\"co-present peers\"| Honcho\n Pulse[\"Pulse People tab<br/>GET /memories/people (read-only)\"]\n Pulse -->|\"conclusions + card\"| Honcho\n Pre --> Audit\n Sync --> Audit\n Pulse --> Audit\n class Turn entry\n class Gate compute\n class Pre compute\n class Sync compute\n class Honcho external\n class Pulse entry\n class Audit storage\n",
- "generated_at": "2026-09-21T18:19:03Z"
+ "generated_at": "2026-09-23T15:58:35Z"
}
diff --git a/packages/core/openexecutive/integrations/email_poller.py b/packages/core/openexecutive/integrations/email_poller.py
index 961f3991..11afb083 100644
--- a/packages/core/openexecutive/integrations/email_poller.py
+++ b/packages/core/openexecutive/integrations/email_poller.py
@@ -139,6 +139,184 @@ def _parse_recipients(raw: str) -> list[str]:
return found
+# Section markers in get_gmail_message_content's text output: header lines,
+# then the body, then an optional numbered attachment list whose lines read
+# `1. <filename> (<mime type>, <size> KB)`. The attachment list is appended
+# last, so a marker-looking line inside the body is told apart by position.
+_BODY_MARKER = "--- BODY ---"
+_ATTACHMENTS_MARKER = "--- ATTACHMENTS ---"
+# What the MCP writes when a message has no text/plain part — not the
+# sender's words.
+_NO_BODY_PLACEHOLDER = "[No text/plain body found]"
+_NO_SUBJECT_PLACEHOLDER = "(no subject)"
+# An attachment line is `N. <filename> (<mime>, <size> KB)`, optionally
+# followed by ` [in attached message]`. Parsed by splitting from the right
+# rather than one regex: the filename is free text an email sender controls,
+# and a pattern with adjacent `\s+` / `.+?` groups backtracks cubically on a
+# long run of spaces — enough for one inbound email to stall the process.
+_ATTACHMENT_INDEX_RE = re.compile(r"\d+\.\s")
+_ATTACHMENT_SIZE_RE = re.compile(r"[\d.]+ KB")
+_ATTACHMENT_NESTED_SUFFIX = " [in attached message]"
+# Longer lines are not the MCP's; skipping them bounds the work per line.
+_ATTACHMENT_LINE_MAX_CHARS = 512
+# A reply attribution ("On <date>, <name> <addr> wrote:"). One on a single
+# line is trusted: what follows is the older message, quoted with ">" (then
+# skipped line by line, so text the sender wrote below it survives) or not
+# (then the scan ends there). Gmail wraps a long one over several lines; that
+# shape is only trusted when ">" lines follow, so the sender's own
+# "On Monday I'll ..." above a "... wrote:" line is never mistaken for one.
+_ATTRIBUTION_RE = re.compile(r"^On\s.+wrote:\s*$")
+_ATTRIBUTION_TAIL_RE = re.compile(r"wrote:\s*$")
+_ATTRIBUTION_MAX_LINES = 4
+# Where everything below is an older message rather than the sender's text.
+_ORIGINAL_MESSAGE_RE = re.compile(r"^-{2,}\s*Original Message\s*-{2,}", re.IGNORECASE)
+_FORWARDED_RE = re.compile(r"^-{2,}\s*Forwarded message\s*-{2,}", re.IGNORECASE)
+_OUTLOOK_RULE_RE = re.compile(r"^_{10,}\s*$")
+_OUTLOOK_HEADER_RE = re.compile(r"^From:\s")
+_OUTLOOK_SENT_RE = re.compile(r"^(Sent|Date):\s")
+# How far below an Outlook-style "From:" line its "Sent:" line may sit.
+_OUTLOOK_HEADER_SPAN = 4
+
+
+def _split_gmail_content(raw: str) -> tuple[list[str], list[str], list[str]]:
+ """Split get_gmail_message_content text into (header, body, attachment) lines.
+
+ Without a ``--- BODY ---`` marker, the body is everything after the
+ first blank line, like an RFC 822 message. The attachment list starts at
+ the LAST ``--- ATTACHMENTS ---`` line, since the MCP appends it after the
+ body and the body itself may contain that text.
+ """
+ lines = raw.splitlines()
+ stripped = [ln.strip() for ln in lines]
+ if _BODY_MARKER in stripped:
+ start = stripped.index(_BODY_MARKER)
+ header, rest = lines[:start], lines[start + 1:]
+ else:
+ blank = next((i for i, ln in enumerate(stripped) if not ln), len(lines))
+ header, rest = lines[:blank], lines[blank + 1:]
+ rest_stripped = [ln.strip() for ln in rest]
+ if _ATTACHMENTS_MARKER in rest_stripped:
+ end = len(rest_stripped) - 1 - rest_stripped[::-1].index(_ATTACHMENTS_MARKER)
+ return header, rest[:end], rest[end + 1:]
+ return header, rest, []
+
+
+def _quote_follows(body: list[str], j: int) -> bool:
+ """Whether the next non-blank line after ``body[j]`` is a ">" quote."""
+ k = j + 1
+ # Indexing, not slicing: a body of many attribution-like lines must not
+ # make this quadratic.
+ while k < len(body) and not body[k].strip():
+ k += 1
+ return k < len(body) and body[k].strip().startswith(">")
+
+
+def _attachment_name(line: str) -> str | None:
+ """The filename in one attachment-list line, or None if it isn't one."""
+ text = line.strip()
+ if len(text) > _ATTACHMENT_LINE_MAX_CHARS:
+ return None
+ index = _ATTACHMENT_INDEX_RE.match(text)
+ if index is None:
+ return None
+ text = text[index.end():].removesuffix(_ATTACHMENT_NESTED_SUFFIX)
+ if not text.endswith(")"):
+ return None
+ name, sep, meta = text[:-1].rpartition(" (")
+ _mime, comma, size = meta.rpartition(", ")
+ if not (sep and comma and _ATTACHMENT_SIZE_RE.fullmatch(size)):
+ return None
+ return name.strip() or None
+
+
+def _attribution_end(body: list[str], i: int) -> tuple[int, bool] | None:
+ """If ``body[i]`` opens a reply attribution: the index of its last line
+ and whether ">" quote lines follow it."""
+ text = body[i].strip()
+ if not text.startswith("On "):
+ return None
+ if _ATTRIBUTION_RE.match(text):
+ return i, _quote_follows(body, i)
+ for j in range(i + 1, min(i + _ATTRIBUTION_MAX_LINES, len(body))):
+ line = body[j].strip()
+ # A wrapped attribution is one unbroken run of lines: a blank, a quote
+ # or another "On ..." line means body[i] was the sender's own text
+ # ("On it, will send Friday.") and any real attribution is later.
+ if not line or line.startswith((">", "On ")):
+ return None
+ if _ATTRIBUTION_TAIL_RE.search(line):
+ return (j, True) if _quote_follows(body, j) else None
+ return None
+
+
+def _new_text_lines(body: list[str]) -> tuple[list[str], bool]:
+ """The sender's own lines, without quoted replies, stopping where an
+ older message is appended below. Returns (lines, whether a forwarded
+ message was cut off).
+
+ A reply attribution followed by ">" lines is skipped rather than ending
+ the scan, so text the sender wrote below a quote (bottom-posting or an
+ interleaved reply) is kept.
+ """
+ kept: list[str] = []
+ i = 0
+ while i < len(body):
+ text = body[i].strip()
+ if _FORWARDED_RE.match(text):
+ return kept, True
+ if _ORIGINAL_MESSAGE_RE.match(text) or _OUTLOOK_RULE_RE.match(text):
+ break
+ if _OUTLOOK_HEADER_RE.match(text) and any(
+ _OUTLOOK_SENT_RE.match(b.strip())
+ for b in body[i + 1:i + 1 + _OUTLOOK_HEADER_SPAN]
+ ):
+ break
+ attribution = _attribution_end(body, i)
+ if attribution is not None:
+ end, quoted = attribution
+ if not quoted:
+ break
+ i = end + 1
+ continue
+ if not text.startswith(">") and text != _NO_BODY_PLACEHOLDER:
+ kept.append(body[i].rstrip())
+ i += 1
+ return kept, False
+
+
+def _email_memory_text(raw: str) -> str:
+ """What peer memory should record as the sender's own words for an email.
+
+ The Executive's turn carries the whole message — the "You have an
+ inbound email" framing, any [POLICY] notice, every header (including
+ the Executive's own address in To:) and the quoted chain, which often
+ holds the Executive's earlier email. Recorded under the sender's peer,
+ Honcho reads all of that as the sender speaking and concludes the sender
+ *is* the Executive ("received an email from <sender>", "is associated
+ with <exec address>"). So memory gets only the subject, the sender's new
+ text and the attachment filenames.
+ """
+ header, body, attachments = _split_gmail_content(raw)
+ subject = next(
+ (ln.split(":", 1)[1].strip() for ln in header if ln.lower().startswith("subject:")),
+ "",
+ )
+ new_lines, forwarded = _new_text_lines(body)
+ new_text = "\n".join(new_lines).strip()
+ names = [name for name in map(_attachment_name, attachments) if name]
+
+ parts: list[str] = []
+ if subject and subject != _NO_SUBJECT_PLACEHOLDER:
+ parts.append(f"Subject: {subject}")
+ if new_text:
+ parts.append(new_text)
+ if forwarded:
+ parts.append("[Forwarded an earlier message]")
+ if names:
+ parts.append(f"[Attached: {', '.join(names)}]")
+ return "\n\n".join(parts)
+
+
def _parse_search_results(raw: str) -> list[dict[str, str]]:
"""Parse plain-text search_gmail_messages response into [{message_id, thread_id}].
@@ -421,6 +599,9 @@ async def _run_executive(
episodic_context=format_for_prompt(),
person_id=person_id,
co_present_person_ids=co_present_person_ids or None,
+ # Only the sender's own words reach peer memory — see _email_memory_text.
+ # An unrostered sender has no peer to record into, so skip the parse.
+ memory_text=_email_memory_text(raw_email) if person_id is not None else None,
)
diff --git a/packages/core/openexecutive/memory/honcho_client.py b/packages/core/openexecutive/memory/honcho_client.py
index f27ccd79..392fa580 100644
--- a/packages/core/openexecutive/memory/honcho_client.py
+++ b/packages/core/openexecutive/memory/honcho_client.py
@@ -1448,11 +1448,15 @@ def sync_turn(
own retention is best-effort and we don't want a sync error to
surface after the user already has their answer.
- ``user_message`` is recorded as the person's own words, so the
- ``<outbound_reply_context>`` block inbound hydration prepends for the
- LLM turn is stripped first. Left in, Honcho's deriver attributes the
- Executive's own DM to the person who replied to it ("<person> created
- the tracker", "<person>'s email is the Executive's").
+ ``user_message`` is recorded as the person's own words, so callers pass
+ what the person actually wrote rather than the framed prompt the LLM saw
+ (see ``memory_text`` on ``Executive.stream_chat``): an inbound email's
+ headers, a briefing card's body or an attachment's extracted text
+ recorded here teach Honcho that the person did what the Executive did.
+ The ``<outbound_reply_context>`` block inbound hydration prepends for the
+ LLM turn is still stripped here as a backstop. Left in, Honcho's deriver
+ attributes the Executive's own DM to the person who replied to it
+ ("<person> created the tracker", "<person>'s email is the Executive's").
"""
if person_id is None:
_emit_peer_memory(op="sync_turn", person_id=None, outcome="no_person")
diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.py
index 317493b1..e6483ea9 100644
--- a/packages/core/openexecutive/orchestrator/executive.py
+++ b/packages/core/openexecutive/orchestrator/executive.py
@@ -347,6 +347,13 @@ _ALL_SKILL_HANDLERS = {
}
+def _peer_memory_text(memory_text: str | None, user_message: str) -> str:
+ """What the post-turn syncs record as the person's words: the caller's
+ ``memory_text`` when given (``""`` included — it means "nothing the
+ person wrote"), else the prompt itself."""
+ return memory_text if memory_text is not None else user_message
+
+
def _sync_consulted_departments_to_honcho(
consulted_specialists: list[str],
user_message: str,
@@ -640,6 +647,7 @@ class Executive:
channel_context_block: str = "",
page_context_block: str = "",
turn_id: str | None = None,
+ memory_text: str | None = None,
) -> AsyncIterator[str | dict[str, Any]]:
"""Stream a response from the Executive, routing to specialists as needed.
@@ -663,6 +671,13 @@ class Executive:
``"low"`` was hitting the ~5s tail consistently for power-user
peers as their representations grew. The committee path keeps
``"medium"`` since it already pays the deep-review latency cost.
+
+ ``memory_text`` is what peer memory records as the person's words
+ for this turn; ``None`` records ``user_message``. Pass it whenever
+ ``user_message`` carries text the person did not write (an inbound
+ email's headers and quoted chain, a briefing card's body, an
+ attachment's extracted text): Honcho derives facts about the
+ person from everything recorded under their peer.
"""
logger.info(
"chat turn: %s",
@@ -868,8 +883,9 @@ class Executive:
# extraction can update the peer card. Fire-and-forget; the
# wrapper no-ops when person_id is None or Honcho is disabled.
from openexecutive.memory.honcho_client import sync_turn as _honcho_sync
+ peer_memory_text = _peer_memory_text(memory_text, user_message)
_honcho_sync(
- user_message,
+ peer_memory_text,
full_response,
person_id=person_id,
session_id=session.session_id,
@@ -880,7 +896,7 @@ class Executive:
# syncs are visible in the audit log as a related pair.
_sync_consulted_departments_to_honcho(
consulted,
- user_message,
+ peer_memory_text,
full_response,
person_id=person_id,
session_id=session.session_id,
@@ -904,6 +920,7 @@ class Executive:
channel_context_block: str = "",
page_context_block: str = "",
turn_id: str | None = None,
+ memory_text: str | None = None,
) -> AsyncIterator[str | dict[str, Any]]:
"""Committee-reviewed variant of stream_chat.
@@ -1306,8 +1323,9 @@ class Executive:
# Mirror the completed exchange into Honcho (see stream_chat for
# rationale). Fire-and-forget; no-ops when person_id is None.
from openexecutive.memory.honcho_client import sync_turn as _honcho_sync
+ peer_memory_text = _peer_memory_text(memory_text, user_message)
_honcho_sync(
- user_message,
+ peer_memory_text,
final_response,
person_id=person_id,
session_id=session.session_id,
@@ -1315,7 +1333,7 @@ class Executive:
)
_sync_consulted_departments_to_honcho(
consulted,
- user_message,
+ peer_memory_text,
final_response,
person_id=person_id,
session_id=session.session_id,
@@ -1839,6 +1857,7 @@ class Executive:
peer_memory_context: str | None = None,
briefing_context: str = "",
channel_context_block: str = "",
+ memory_text: str | None = None,
) -> str:
"""Non-streaming chat — collects and returns the full response.
@@ -1858,6 +1877,8 @@ class Executive:
for details. ``peer_memory_reasoning_level=None`` (default)
keeps each underlying entry point's own default (``"minimal"``
for the streaming path, ``"medium"`` for the committee path).
+ ``memory_text`` overrides what peer memory records as the person's
+ words (see ``stream_chat``).
"""
# Build the kwargs dict so we can conditionally include the
# reasoning_level only when caller specified one — otherwise
@@ -1874,6 +1895,7 @@ class Executive:
"co_present_person_ids": co_present_person_ids,
"briefing_context": briefing_context,
"channel_context_block": channel_context_block,
+ "memory_text": memory_text,
}
if peer_memory_reasoning_level is not None:
common_kwargs["peer_memory_reasoning_level"] = peer_memory_reasoning_level
diff --git a/packages/core/tests/unit/test_chat_route_memory_text.py b/packages/core/tests/unit/test_chat_route_memory_text.py
new file mode 100644
index 00000000..8ad95fd0
--- /dev/null
+++ b/packages/core/tests/unit/test_chat_route_memory_text.py
@@ -0,0 +1,156 @@
+"""The web chat routes hand ``memory_text`` to the Executive.
+
+``/chat`` forwards the client's ``memory_text`` — a briefing handoff seeds
+the turn with the Executive's own card body, and sends a short line of what
+the user actually asked for peer memory to record instead. ``/chat/upload``
+records the typed text plus the filenames, never the extracted document text,
+which is the document's words and not the caller's.
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes import chat as chat_route
+from openexecutive.memory import episodic, session_store
+from openexecutive.memory.company_profile import CompanyProfile
+from openexecutive.people import store as people_store
+
+
[email protected](autouse=True)
+def _reset_route_state() -> None:
+ chat_route._sessions.clear()
+ chat_route._last_turn_events.clear()
+ chat_route._last_turn_meta.clear()
+
+
+def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ monkeypatch.chdir(tmp_path)
+ db_path = Path("./episodic_memory.db").resolve()
+ monkeypatch.setattr(episodic, "DB_PATH", db_path)
+ monkeypatch.setattr(session_store, "DB_PATH", db_path)
+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")
+ episodic.initialize_db(db_path)
+ people_store.initialize_db()
+ people_store.upsert_person(full_name="Alex Rivera", role="CEO", is_principal=True)
+
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ from openexecutive.knowledge import retriever
+ from openexecutive.onboarding import profile_builder
+
+ monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: CompanyProfile())
+ monkeypatch.setattr(retriever, "retrieve", lambda *a, **k: "")
+
+ app = FastAPI()
+ app.include_router(chat_route.router)
+ return TestClient(app)
+
+
+def captured(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ from openexecutive.orchestrator import executive as exec_mod
+
+ calls: dict[str, Any] = {}
+
+ class _CapturingExecutive:
+ _THINKING = exec_mod.Executive._THINKING
+
+ def __init__(self, **_kwargs: Any) -> None:
+ pass
+
+ async def stream_chat(self, **kwargs: Any) -> AsyncIterator[str]:
+ calls["stream_chat"] = kwargs
+ yield "ok"
+
+ async def stream_chat_with_committee(self, **kwargs: Any) -> AsyncIterator[str]:
+ calls["stream_chat_with_committee"] = kwargs
+ yield "ok"
+
+ monkeypatch.setattr(exec_mod, "Executive", _CapturingExecutive)
+ return calls
+
+
+SEED = "Let's discuss this artifact you flagged for my review:\n\n# Plan\n\nAssign Sam to sign."
+LINE = 'Asked to discuss the flagged artifact "Plan".'
+
+
+ ("committee", "entry"),
+ [(False, "stream_chat"), (True, "stream_chat_with_committee")],
+)
+def test_chat_forwards_memory_text(
+ client: TestClient, captured: dict[str, Any], committee: bool, entry: str
+) -> None:
+ resp = client.post(
+ "/chat", json={"message": SEED, "memory_text": LINE, "committee_review": committee}
+ )
+ assert resp.status_code == 200
+ _ = resp.text
+ assert captured[entry]["memory_text"] == LINE
+ assert captured[entry]["user_message"] == SEED
+
+
+def test_chat_without_memory_text_forwards_none(
+ client: TestClient, captured: dict[str, Any]
+) -> None:
+ resp = client.post("/chat", json={"message": "hi"})
+ assert resp.status_code == 200
+ _ = resp.text
+ assert captured["stream_chat"]["memory_text"] is None
+
+
[email protected]("bad", ["", "x" * 2001])
+def test_chat_rejects_empty_or_oversized_memory_text(
+ client: TestClient, captured: dict[str, Any], bad: str
+) -> None:
+ resp = client.post("/chat", json={"message": "hi", "memory_text": bad})
+ assert resp.status_code == 422
+ assert captured == {}
+
+
+def test_upload_records_typed_text_and_filenames_not_document_text(
+ client: TestClient, captured: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ chat_route,
+ "build_attachment_output",
+ lambda filename, data, content_type: (f"[{filename}] EXTRACTED DOCUMENT TEXT", []),
+ )
+ resp = client.post(
+ "/chat/upload",
+ data={"message": "Summarise these"},
+ files=[
+ ("files", ("appraisal (1).pdf", b"%PDF-1.4", "application/pdf")),
+ ("files", ("notes.txt", b"hello", "text/plain")),
+ ],
+ )
+ assert resp.status_code == 200
+ _ = resp.text
+ kwargs = captured["stream_chat"]
+ assert kwargs["memory_text"] == "Summarise these\n\n[Attached: appraisal (1).pdf, notes.txt]"
+ # The Executive still sees the extracted text.
+ assert "EXTRACTED DOCUMENT TEXT" in kwargs["user_message"]
+
+
+def test_memory_text_is_kept_in_the_chat_turn_audit_row(
+ client: TestClient, captured: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """memory_text reaches peer and department memory but not the transcript,
+ so the audit row is its only record."""
+ rows: list[dict[str, Any]] = []
+
+ def _audit(event_type: str, summary: str, **kwargs: Any) -> None:
+ rows.append({"event_type": event_type, **kwargs})
+
+ monkeypatch.setattr(chat_route, "audit_log", _audit)
+ resp = client.post("/chat", json={"message": SEED, "memory_text": LINE})
+ assert resp.status_code == 200
+ _ = resp.text
+ turn = next(r for r in rows if r["event_type"] == "chat_turn")
+ assert turn["full"] == {"message": SEED, "memory_text": LINE}
diff --git a/packages/core/tests/unit/test_email_poller_memory_text.py b/packages/core/tests/unit/test_email_poller_memory_text.py
new file mode 100644
index 00000000..98f2bf85
--- /dev/null
+++ b/packages/core/tests/unit/test_email_poller_memory_text.py
@@ -0,0 +1,298 @@
+"""Peer memory records only the sender's own words for an inbound email.
+
+The Executive's turn carries the whole message — the "You have an inbound
+email" framing, every header (the Executive's own address in To:), the
+quoted chain (often the Executive's own earlier email) and the attachment
+listing. Recorded under the sender's peer, Honcho concluded the sender *was*
+the Executive: "<sender> is associated with <exec address>", "<sender>
+received an email from <sender>", "<sender> had requested the report from
+<sender>". ``_email_memory_text`` keeps the subject, the new text and the
+attachment filenames, and ``_run_executive`` passes it as ``memory_text``.
+"""
+from __future__ import annotations
+
+import asyncio
+import time
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import openexecutive.integrations.email_poller as poller
+from openexecutive.integrations.email_poller import _email_memory_text
+
+
+# Shaped like the Gmail MCP's get_gmail_message_content output for the
+# reply that surfaced the bug: a short reply, Gmail's two-line wrapped
+# attribution, the quoted request, and one attachment whose name has
+# parentheses of its own.
+REPLY = f"""Message ID: 18c0ffee00000001
+Subject: Q3 appraisal
+From: Sam Lee <[email protected]>
+Date: Wed, 23 Sep 2026 11:21:18 -0400
+Message-ID: <[email protected]>
+To: {EXEC}
+
+--- BODY ---
+Here you go.
+
+Sam
+
+On Wed, Sep 23, 2026 at 11:00 AM Open Executive <
+{EXEC}> wrote:
+> Sam, can you send me the appraisal?
+> Thanks
+
+--- ATTACHMENTS ---
+1. Harbor Point appraisal (1).pdf (application/pdf, 3996.2 KB)
+ Attachment ID: ANGjdJ8
+ Use get_gmail_attachment_content(message_id='18c0ffee00000001', attachment_id='ANGjdJ8') to download
+"""
+
+
+def _email(body: str, *, subject: str = "Status", attachments: str = "") -> str:
+ raw = f"Subject: {subject}\nFrom: [email protected]\nTo: {EXEC}\n\n--- BODY ---\n{body}\n"
+ if attachments:
+ raw += f"\n--- ATTACHMENTS ---\n{attachments}\n"
+ return raw
+
+
+def test_reply_keeps_subject_new_text_and_attachment_only() -> None:
+ assert _email_memory_text(REPLY) == (
+ "Subject: Q3 appraisal\n\n"
+ "Here you go.\n\nSam\n\n"
+ "[Attached: Harbor Point appraisal (1).pdf]"
+ )
+
+
+def test_reply_drops_everything_that_made_the_sender_look_like_the_executive() -> None:
+ text = _email_memory_text(REPLY)
+ for leaked in (EXEC, "From:", "To:", "Message ID", "wrote:", "can you send me", "Attachment ID"):
+ assert leaked not in text
+
+
+def test_single_line_attribution_without_quote_marks_ends_the_new_text() -> None:
+ """Some clients quote without ">": everything after the attribution is
+ the older message."""
+ raw = _email("Sounds good.\n\nOn Tue, Sep 22, 2026, Exec <[email protected]> wrote:\nOld text")
+ assert _email_memory_text(raw) == "Subject: Status\n\nSounds good."
+
+
+def test_quoted_lines_without_attribution_are_dropped() -> None:
+ raw = _email("> earlier line\nMy answer is yes.")
+ assert _email_memory_text(raw) == "Subject: Status\n\nMy answer is yes."
+
+
+def test_outlook_original_message_block_is_cut() -> None:
+ raw = _email("Approved.\n\n-----Original Message-----\nFrom: Exec\nSent: Monday\nPlease approve")
+ assert _email_memory_text(raw) == "Subject: Status\n\nApproved."
+
+
+def test_outlook_from_sent_header_block_is_cut() -> None:
+ raw = _email(
+ "Will do.\n\n________________________________\n"
+ "From: Exec <[email protected]>\nSent: Monday\nTo: Sam\nSubject: Status\n\nOld"
+ )
+ assert _email_memory_text(raw) == "Subject: Status\n\nWill do."
+
+
+def test_bare_from_sent_block_without_rule_is_cut() -> None:
+ raw = _email("Will do.\n\nFrom: Exec <[email protected]>\nSent: Monday\n\nOld request")
+ assert _email_memory_text(raw) == "Subject: Status\n\nWill do."
+
+
+def test_a_from_line_in_the_senders_own_text_is_kept() -> None:
+ """Only a From: followed by Sent:/Date: is a quoted header block."""
+ raw = _email("From: the lender's side, all clear.\nMore detail here.")
+ assert "From: the lender's side, all clear." in _email_memory_text(raw)
+
+
+def test_forwarded_message_is_replaced_by_a_note() -> None:
+ raw = _email(
+ "FYI see below.\n\n---------- Forwarded message ---------\nFrom: Bank\nDate: Mon\n\nRate is 5%",
+ subject="Fwd: Rates",
+ )
+ assert _email_memory_text(raw) == (
+ "Subject: Fwd: Rates\n\nFYI see below.\n\n[Forwarded an earlier message]"
+ )
+
+
+def test_multiple_attachments_are_listed_by_name() -> None:
+ raw = _email(
+ "Both attached.",
+ attachments=(
+ "1. a.pdf (application/pdf, 10.0 KB)\n Attachment ID: x\n"
+ "2. b (final).xlsx (application/vnd.ms-excel, 2.5 KB) [in attached message]\n"
+ " Attachment ID: y"
+ ),
+ )
+ assert _email_memory_text(raw).endswith("[Attached: a.pdf, b (final).xlsx]")
+
+
+def test_attachment_only_email_records_subject_and_names() -> None:
+ raw = _email(
+ "[No text/plain body found]\n\nOn Mon, Exec <[email protected]> wrote:\n> send it",
+ subject="Appraisal",
+ attachments="1. appraisal.pdf (application/pdf, 1.0 KB)",
+ )
+ # The MCP's placeholder is not the sender's words.
+ assert _email_memory_text(raw) == "Subject: Appraisal\n\n[Attached: appraisal.pdf]"
+
+
+def test_no_subject_placeholder_is_not_recorded() -> None:
+ assert _email_memory_text(_email("Thanks!", subject="(no subject)")) == "Thanks!"
+
+
+def test_bottom_posted_reply_keeps_text_below_the_quote() -> None:
+ raw = _email(
+ "On Mon, Sep 22, 2026, Exec <[email protected]> wrote:\n"
+ "> Can you send the appraisal?\n\nAttached — numbers updated."
+ )
+ assert _email_memory_text(raw) == "Subject: Status\n\nAttached — numbers updated."
+
+
+def test_interleaved_reply_keeps_every_answer() -> None:
+ raw = _email(
+ "On Mon, Exec <[email protected]> wrote:\n> Rate?\nFixed at 5%.\n> Term?\nTen years."
+ )
+ assert _email_memory_text(raw) == "Subject: Status\n\nFixed at 5%.\nTen years."
+
+
+def test_attribution_wrapped_over_four_lines_does_not_leak_the_exec_address() -> None:
+ raw = _email(
+ "Here you go.\n\n"
+ "On Wednesday, September 23, 2026 at 11:00 AM Open Executive Chief of\n"
+ "Staff <\[email protected]>\nwrote:\n> send it"
+ )
+ text = _email_memory_text(raw)
+ assert text == "Subject: Status\n\nHere you go."
+ assert EXEC not in text
+
+
+def test_senders_own_on_line_before_a_wrote_line_is_kept() -> None:
+ """Not an attribution: no quoted lines follow the "wrote:" line."""
+ raw = _email("On Monday I'll send the deck.\nHere's what the lender wrote:\nRate lock expires Friday.")
+ assert _email_memory_text(raw) == (
+ "Subject: Status\n\n"
+ "On Monday I'll send the deck.\nHere's what the lender wrote:\nRate lock expires Friday."
+ )
+
+
+def test_reply_starting_with_on_above_a_real_attribution_is_kept() -> None:
+ for body in (
+ "On it, will send Friday.\n\nOn Mon, Jan 5, 2026, Bob <[email protected]> wrote:\n\n> can you send it?",
+ "On it.\nOn Mon, Jan 5, 2026, Bob <[email protected]> wrote:\n> can you send it?",
+ "On second thought, skip it.\n> old line\n> Alice wrote:\n> more",
+ ):
+ text = _email_memory_text(_email(body))
+ assert text.startswith("Subject: Status\n\nOn "), body
+ assert "wrote:" not in text and "can you send it" not in text
+
+
+def test_attachments_marker_inside_the_body_is_body_text() -> None:
+ raw = _email(
+ "See list:\n--- ATTACHMENTS ---\n1. I approved it (x, 1 KB)\nThanks",
+ attachments="1. real.pdf (application/pdf, 2.0 KB)",
+ )
+ text = _email_memory_text(raw)
+ assert text.endswith("[Attached: real.pdf]")
+ assert "Thanks" in text
+
+
+def test_attachment_line_of_spaces_parses_in_linear_time() -> None:
+ """A sender-controlled "attachment" line of whitespace once took cubic
+ time (30 s at 4,000 spaces) and would stall the whole process."""
+ for filler in (" " * 5000, "\u00a0" * 5000):
+ raw = _email("Hi", attachments=f"1. {filler}x ({filler}, 1 KB")
+ started = time.monotonic()
+ assert _email_memory_text(raw) == "Subject: Status\n\nHi"
+ assert time.monotonic() - started < 0.5
+
+
+def test_overlong_attachment_line_is_ignored() -> None:
+ raw = _email("Hi", attachments=f"1. {'a' * 600}.pdf (application/pdf, 1.0 KB)")
+ assert _email_memory_text(raw) == "Subject: Status\n\nHi"
+
+
+def test_non_attachment_lines_in_the_list_are_ignored() -> None:
+ raw = _email(
+ "Hi",
+ attachments=(
+ "1. ok.pdf (application/pdf, 1.0 KB)\n Attachment ID: z\n"
+ "2. no size (application/pdf)\n3. bad size (x, lots KB)"
+ ),
+ )
+ assert _email_memory_text(raw).endswith("[Attached: ok.pdf]")
+
+
+def test_many_on_lines_parse_in_linear_time() -> None:
+ """An attacker-shaped body of attribution-like lines must not go quadratic."""
+ raw = _email("On x wrote:\n> q\n" * 20000 + "tail")
+ started = time.monotonic()
+ assert _email_memory_text(raw) == "Subject: Status\n\ntail"
+ assert time.monotonic() - started < 2.0
+
+
+def test_without_body_marker_the_body_follows_the_first_blank_line() -> None:
+ raw = f"Subject: Hi\nFrom: [email protected]\nTo: {EXEC}\n\nQuick question.\n> quoted"
+ assert _email_memory_text(raw) == "Subject: Hi\n\nQuick question."
+
+
+def test_empty_email_records_nothing() -> None:
+ assert _email_memory_text("") == ""
+
+
+def _settings() -> Any:
+ return SimpleNamespace(exec_email_address=EXEC, email_poll_interval_seconds=60)
+
+
+def _run(find_person: Any) -> dict[str, Any]:
+ captured: dict[str, Any] = {}
+
+ class _Exec:
+ def __init__(self, **_kw: Any) -> None:
+ pass
+
+ async def chat(self, **kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "ok"
+
+ with (
+ patch("openexecutive.orchestrator.executive.Executive", new=_Exec),
+ patch(
+ "openexecutive.onboarding.profile_builder.load_or_create_profile",
+ return_value=SimpleNamespace(is_empty=lambda: True),
+ ),
+ patch("openexecutive.knowledge.retriever.retrieve", new=lambda **_k: ""),
+ patch("openexecutive.memory.episodic.format_for_prompt", new=lambda: ""),
+ patch("openexecutive.people.store.find_person_by_email", new=find_person),
+ patch.object(poller, "get_settings", return_value=_settings()),
+ ):
+ asyncio.run(
+ poller._run_executive(
+ gateway=AsyncMock(),
+ raw_email=REPLY,
+ message_id="18c0ffee00000001",
+ thread_id="t1",
+ from_addr="[email protected]",
+ )
+ )
+ return captured
+
+
+def test_run_executive_passes_memory_text_and_keeps_the_full_prompt() -> None:
+ sam = SimpleNamespace(id=7)
+ captured = _run(lambda addr: sam if addr == "[email protected]" else None)
+ assert captured["person_id"] == 7
+ assert captured["memory_text"] == _email_memory_text(REPLY)
+ # The Executive still sees the whole email, framing included.
+ assert "You have an inbound email" in captured["user_message"]
+ assert "can you send me" in captured["user_message"]
+
+
+def test_run_executive_skips_the_parse_for_an_unrostered_sender() -> None:
+ """No peer to record into, so attacker-shaped mail from a stranger is
+ never parsed for memory at all."""
+ captured = _run(lambda _addr: None)
+ assert captured["person_id"] is None
+ assert captured["memory_text"] is None
diff --git a/packages/core/tests/unit/test_executive_memory_text.py b/packages/core/tests/unit/test_executive_memory_text.py
new file mode 100644
index 00000000..e00f55ec
--- /dev/null
+++ b/packages/core/tests/unit/test_executive_memory_text.py
@@ -0,0 +1,132 @@
+"""``memory_text`` decides what peer memory records as the person's words.
+
+A turn's ``user_message`` often carries text the person did not write: an
+inbound email's framing, headers and quoted chain, or a briefing card's
+body. Recorded under the person's peer, Honcho derives facts about the
+person from it ("<person> is associated with <the Executive's address>").
+Every entry point must hand ``memory_text`` — not the prompt — to both the
+person sync and the per-department sync, and fall back to ``user_message``
+when it is not given.
+"""
+from __future__ import annotations
+
+import asyncio
+import os
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+os.environ.setdefault("ANTHROPIC_API_KEY", "sk-test-not-used")
+
+PROMPT = "You have an inbound email (message_id=m1).\n\nTo: [email protected]\n\nHere you go."
+MEMORY = "Subject: Q3 appraisal\n\nHere you go."
+
+
[email protected](autouse=True)
+def _no_audit_writes(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Keep this module's audit rows out of the default episodic DB (the
+ audit-log pollution trap in CLAUDE.md)."""
+ monkeypatch.setattr(
+ "openexecutive.audit.log_event", lambda *a, **kw: None, raising=False
+ )
+ # executive.py binds its own name at import time, which the patch above
+ # does not reach.
+ monkeypatch.setattr(
+ "openexecutive.orchestrator.executive.audit_log", lambda *a, **kw: None
+ )
+
+
+def _make_stream_cm(final_msg: object) -> MagicMock:
+ cm = MagicMock()
+ cm.__aenter__ = AsyncMock(return_value=cm)
+ cm.__aexit__ = AsyncMock(return_value=None)
+
+ async def _aiter():
+ # One streamed text delta, so the committee path has a non-empty
+ # draft to review and reaches its post-turn sync.
+ yield SimpleNamespace(
+ type="content_block_delta",
+ delta=SimpleNamespace(type="text_delta", text="done"),
+ )
+
+ cm.__aiter__ = lambda self=cm: _aiter()
+ cm.get_final_message = AsyncMock(return_value=final_msg)
+ return cm
+
+
+def _provider() -> SimpleNamespace:
+ final = SimpleNamespace(
+ content=[SimpleNamespace(type="text", text="done")], stop_reason="end_turn"
+ )
+ return SimpleNamespace(
+ messages_stream=lambda **_kw: _make_stream_cm(final),
+ messages_create=AsyncMock(
+ return_value=SimpleNamespace(
+ content=[SimpleNamespace(type="text", text="ok")],
+ stop_reason="end_turn",
+ )
+ ),
+ )
+
+
+def _drive(entry: str, **kwargs: Any) -> tuple[list[str], list[str]]:
+ """Run one turn through ``entry`` and return (person-sync texts,
+ department-sync texts)."""
+ from openexecutive.orchestrator.executive import Executive
+ from openexecutive.orchestrator.session import Session
+
+ person_texts: list[str] = []
+ dept_texts: list[str] = []
+
+ def _sync_turn(user_message: str, *_a: Any, **_k: Any) -> None:
+ person_texts.append(user_message)
+
+ def _dept_sync(_consulted: Any, user_message: str, *_a: Any, **_k: Any) -> None:
+ dept_texts.append(user_message)
+
+ exec_ = Executive()
+
+ async def _run() -> None:
+ session = Session(session_id=f"t-memtext-{entry}")
+ if entry == "chat":
+ await exec_.chat(PROMPT, session, person_id=42, peer_memory_context="", **kwargs)
+ return
+ stream = getattr(exec_, entry)(
+ PROMPT, session, person_id=42, peer_memory_context="", **kwargs
+ )
+ async for _ in stream:
+ pass
+
+ with (
+ patch("openexecutive.orchestrator.executive.get_provider", return_value=_provider()),
+ patch("openexecutive.memory.honcho_client.sync_turn", new=_sync_turn),
+ patch(
+ "openexecutive.orchestrator.executive._sync_consulted_departments_to_honcho",
+ new=_dept_sync,
+ ),
+ ):
+ asyncio.run(_run())
+ return person_texts, dept_texts
+
+
[email protected]("entry", ["stream_chat", "stream_chat_with_committee", "chat"])
+def test_memory_text_is_what_peer_memory_records(entry: str) -> None:
+ person, dept = _drive(entry, memory_text=MEMORY)
+ assert person == [MEMORY]
+ assert dept == [MEMORY]
+
+
[email protected]("entry", ["stream_chat", "stream_chat_with_committee", "chat"])
+def test_without_memory_text_the_message_is_recorded(entry: str) -> None:
+ person, dept = _drive(entry)
+ assert person == [PROMPT]
+ assert dept == [PROMPT]
+
+
+def test_empty_memory_text_is_honoured_not_replaced_by_the_prompt() -> None:
+ """An email with no subject, body or attachment yields "" — that must
+ record nothing for the person, not fall back to the framed prompt."""
+ person, _ = _drive("stream_chat", memory_text="")
+ assert person == [""]
diff --git a/packages/ui/scripts/briefing-memory.test.mjs b/packages/ui/scripts/briefing-memory.test.mjs
new file mode 100644
index 00000000..2b2c8ca8
--- /dev/null
+++ b/packages/ui/scripts/briefing-memory.test.mjs
@@ -0,0 +1,29 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { MEMORY_LINE_MAX_CHARS, briefingMemoryLine } from "../src/lib/briefing-memory.ts";
+
+test("names the action and the item, not the card body", () => {
+ assert.equal(
+ briefingMemoryLine("Asked to discuss the flagged artifact", "Harbor Point disposition plan"),
+ 'Asked to discuss the flagged artifact "Harbor Point disposition plan".',
+ );
+});
+
+test("collapses whitespace so a multi-line headline stays one line", () => {
+ assert.equal(
+ briefingMemoryLine("Approved the proposal", " Renew\n\n the lease "),
+ 'Approved the proposal "Renew the lease".',
+ );
+});
+
+test("clips long subjects well under the backend's 2000-char bound", () => {
+ const line = briefingMemoryLine("Asked to dig into the briefing item", "x".repeat(5000));
+ const quoted = line.slice(line.indexOf('"') + 1, line.lastIndexOf('"'));
+ assert.equal(quoted.length, MEMORY_LINE_MAX_CHARS);
+ assert.ok(quoted.endsWith("…"));
+ assert.ok(line.length < 2000);
+});
+
+test("an empty subject still yields a non-empty line", () => {
+ assert.equal(briefingMemoryLine("Asked about the proposal", " "), "Asked about the proposal.");
+});
diff --git a/packages/ui/src/app/page.tsx b/packages/ui/src/app/page.tsx
index f4e598e8..6be02533 100644
--- a/packages/ui/src/app/page.tsx
+++ b/packages/ui/src/app/page.tsx
@@ -44,6 +44,8 @@ export default function HomePage() {
// Seeded into Chat's input when the user enters chat mode from a briefing
// item. Cleared on every mode transition so it doesn't leak between turns.
const [pendingPrompt, setPendingPrompt] = useState<string | undefined>(undefined);
+ // Companion to pendingPrompt: what peer memory records for the handoff turn.
+ const [pendingMemoryText, setPendingMemoryText] = useState<string | undefined>(undefined);
useEffect(() => {
fetch("/api/backend/health")
@@ -75,6 +77,7 @@ export default function HomePage() {
setMobileNavOpen(false);
setMode("chat");
setPendingPrompt(undefined);
+ setPendingMemoryText(undefined);
} catch {
// ignore — session may not exist yet
}
@@ -89,18 +92,20 @@ export default function HomePage() {
setMobileNavOpen(false);
setMode("chat");
setPendingPrompt(undefined);
+ setPendingMemoryText(undefined);
}, []);
// Continue a briefing thread in chat — invoked when the user clicks a
// Department card, proposal, or activity row. Switches mode to "chat"
// and seeds the input with the briefing context. The user can edit
// before sending, or just hit send.
- const handleContinueFromBriefing = useCallback((prompt: string) => {
+ const handleContinueFromBriefing = useCallback((prompt: string, memoryText?: string) => {
setActiveSessionId(undefined);
setActiveMessages([]);
setDebugEvents([]);
setMode("chat");
setPendingPrompt(prompt);
+ setPendingMemoryText(memoryText);
}, []);
// Reset to the briefing view from anywhere. Used by the sidebar
@@ -111,6 +116,7 @@ export default function HomePage() {
setDebugEvents([]);
setMode("briefing");
setPendingPrompt(undefined);
+ setPendingMemoryText(undefined);
setMobileNavOpen(false);
}, []);
@@ -372,6 +378,7 @@ export default function HomePage() {
// ments, not drafts, so auto-fire the first turn instead of
// making the user hit Send again.
autoSubmitInitialInput={Boolean(pendingPrompt)}
+ initialMemoryText={pendingMemoryText}
onTurnComplete={handleTurnComplete}
onTurnStart={() => setIsTurnInFlight(true)}
/>
diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsx
index f96c9720..8fc4788a 100644
--- a/packages/ui/src/components/Briefing.tsx
+++ b/packages/ui/src/components/Briefing.tsx
@@ -21,6 +21,7 @@ import {
type ProposalItem,
type Today,
} from "@/lib/api";
+import { briefingMemoryLine } from "@/lib/briefing-memory";
import { clientCountsSummary, renewalBadge } from "@/lib/practice";
import {
HANDLED_REOPENABLE,
@@ -108,7 +109,7 @@ interface BriefingProps {
// its main view from briefing → chat and seed the input with `prompt`.
// When omitted, items render as plain navigation links so the standalone
// /today page still works.
- onContinue?: (prompt: string) => void;
+ onContinue?: ContinueHandler;
// Set to true when this Briefing is the root landing surface — adds a
// "Here's where we are" header. The standalone /today page already
// gets the global AppShell breadcrumb, so it omits this prop.
@@ -131,7 +132,7 @@ function formatRelTime(iso: string): string {
}
interface ClickableProps {
- onContinue?: (prompt: string) => void;
+ onContinue?: ContinueHandler;
prompt: string;
href: string;
className: string;
@@ -171,6 +172,11 @@ function nodeToPlainText(node: unknown): string {
return "";
}
+// Hands a briefing item to chat. `memoryText` is what peer memory records as
+// the user's words for that turn; omit it when `prompt` is already just the
+// user's own ask.
+type ContinueHandler = (prompt: string, memoryText?: string) => void;
+
// Seed prompt for a clicked narrative bullet. The Executive receives the
// open-alert digest as a <briefing> block on every chat turn, so the seed only
// needs to name the item — the exec matches it by headline. No alert_id is
@@ -199,7 +205,7 @@ function buildMonitoringSeed(proposal: ProposalItem): string {
);
}
-function DeptCard({ dept, onContinue, dimmed = false }: { dept: DepartmentBriefItem; onContinue?: (p: string) => void; dimmed?: boolean }) {
+function DeptCard({ dept, onContinue, dimmed = false }: { dept: DepartmentBriefItem; onContinue?: ContinueHandler; dimmed?: boolean }) {
const hasIssues = dept.at_risk_count > 0 || dept.off_track_count > 0;
const prompt = `Tell me about ${dept.title} — what's the current status?`;
// Problem goals beyond the inline cap fall to the department page.
@@ -510,7 +516,7 @@ function buildProposalLifecycle({
}: {
proposal: ProposalItem;
assignee: PersonBriefItem | null | undefined;
- onContinue?: (p: string) => void;
+ onContinue?: ContinueHandler;
busy: boolean;
}): {
reviewLine: React.ReactNode;
@@ -585,6 +591,7 @@ const moveButton = (() => {
onClick={() => onContinue(
`Nudge ${who} about this item — it has gone quiet: ${proposal.headline}\n\n` +
`Send a short, friendly check-in via message_person and tell me what you sent.`,
+ briefingMemoryLine(`Asked to nudge ${who} about`, proposal.headline),
)}
disabled={busy}
className="text-xs font-medium text-indigo-300 hover:text-indigo-200 px-2 py-1 rounded border border-indigo-500/30 transition-colors disabled:opacity-50"
@@ -622,7 +629,7 @@ function ProposalCard({
}: {
proposal: ProposalItem;
people: PersonBriefItem[];
- onContinue?: (p: string) => void;
+ onContinue?: ContinueHandler;
onApprove?: (p: ProposalItem) => void;
onDismiss?: (p: ProposalItem) => void;
onApproveWithEdits?: (p: ProposalItem, editedBody: string) => void;
@@ -755,6 +762,16 @@ function ProposalCard({
);
return `Tell me about this proposal:\n\n${text}${suggested}${primer}`;
})();
+ const handoffMemory = briefingMemoryLine(
+ isArtifact
+ ? "Asked to discuss the flagged artifact"
+ : isMonitoring
+ ? "Asked about the monitored signal"
+ : isDecision
+ ? "Asked to talk through the proposed meeting"
+ : "Asked about the proposal",
+ proposal.headline,
+ );
// Suggested-action block: visually promoted so the user reads it as a
// commitment ("if I approve, the exec will do THIS") rather than a
// footnote. Renders only when suggested_action is non-empty — and never
@@ -945,7 +962,7 @@ function ProposalCard({
const contentArea = onContinue ? (
<button
type="button"
- onClick={() => onContinue(handoffPrompt)}
+ onClick={() => onContinue(handoffPrompt, handoffMemory)}
className="block w-full text-left cursor-pointer transition-colors"
>
{content}
@@ -979,7 +996,7 @@ function ProposalCard({
{onContinue && (
<button
type="button"
- onClick={() => onContinue(handoffPrompt)}
+ onClick={() => onContinue(handoffPrompt, handoffMemory)}
disabled={busy}
className="text-xs text-fg-muted hover:text-indigo-300 px-2 py-1 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
@@ -1162,7 +1179,7 @@ function MonitoringRow({
onDismiss,
}: {
proposal: ProposalItem;
- onContinue?: (p: string) => void;
+ onContinue?: ContinueHandler;
onDismiss?: (p: ProposalItem) => void;
}) {
const seed = buildMonitoringSeed(proposal);
@@ -1183,7 +1200,7 @@ function MonitoringRow({
{onContinue ? (
<button
type="button"
- onClick={() => onContinue(seed)}
+ onClick={() => onContinue(seed, briefingMemoryLine("Asked about the monitored signal", proposal.headline))}
className="block w-full text-left pr-8 cursor-pointer focus:outline-none focus:ring-1 focus:ring-indigo-500/40"
>
{inner}
@@ -1218,7 +1235,7 @@ function MonitoringPanel({
id,
}: {
proposals: ProposalItem[];
- onContinue?: (p: string) => void;
+ onContinue?: ContinueHandler;
onDismiss?: (p: ProposalItem) => void;
onBulkDismiss?: (ids: number[]) => void;
id?: string;
@@ -1483,6 +1500,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
`call schedule_followup so I get a fresh check at the right time. Do NOT just ` +
`summarize what you would do, file it for later, or assign it to someone — ` +
`the assignment IS to you.\n\nProposal:\n${text}${action}`,
+ briefingMemoryLine("Approved the proposal", proposal.headline),
);
}
} catch (e) {
@@ -1589,6 +1607,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
`call ack_alert. Use the text below VERBATIM when you deliver the message: do not ` +
`rephrase, summarize, or restructure it. Then go execute (send the DM/email, ` +
`schedule any follow-up via schedule_followup) and tell me what you did.\n\n${editedBody}`,
+ briefingMemoryLine("Approved the proposal with edits", proposal.headline),
);
}
} catch (e) {
@@ -1814,7 +1833,7 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:
<li className="list-none">
<button
type="button"
- onClick={() => onContinue(buildNarrativeSeed(text))}
+ onClick={() => onContinue(buildNarrativeSeed(text), briefingMemoryLine("Asked to dig into the briefing item", text))}
aria-label={`Discuss: ${text}`}
className="group flex w-full items-start gap-2 text-left cursor-pointer rounded -mx-1.5 px-1.5 py-0.5 transition hover:bg-indigo-500/10 focus:outline-none focus:ring-1 focus:ring-indigo-500/40"
>
diff --git a/packages/ui/src/components/Chat.tsx b/packages/ui/src/components/Chat.tsx
index 0c5ab6cc..6b615a02 100644
--- a/packages/ui/src/components/Chat.tsx
+++ b/packages/ui/src/components/Chat.tsx
@@ -40,6 +40,10 @@ interface ChatProps {
// already committed by clicking the action; making them hit Send again
// is friction. One-shot per mount; ignored on subsequent prop updates.
autoSubmitInitialInput?: boolean;
+ // Sent with the auto-submitted `initialInput` only: the short line peer
+ // memory records instead of the seed, which quotes the Executive's own
+ // briefing card. Typed messages record exactly what was typed.
+ initialMemoryText?: string;
onTurnComplete?: (sessionId: string) => void;
onTurnStart?: () => void;
}
@@ -66,7 +70,7 @@ function endsOnReply(messages: ChatMessage[] | undefined): boolean {
const FALLBACK_SUBTITLE =
"Pick up where we left off — decisions to revisit, drafts to push forward, people to pull in.";
-export default function Chat({ onDebugEvent, initialMessages, initialSessionId, initialInput, autoSubmitInitialInput, onTurnComplete, onTurnStart }: ChatProps) {
+export default function Chat({ onDebugEvent, initialMessages, initialSessionId, initialInput, autoSubmitInitialInput, initialMemoryText, onTurnComplete, onTurnStart }: ChatProps) {
const { data: session } = useSession();
const firstName = session?.user?.name?.trim().split(/\s+/)[0];
@@ -189,13 +193,18 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
}, [isLoading, handleStop]);
const didAutoSubmitRef = useRef(false);
+ // A handoff turn stopped before any output is returned to the composer as
+ // its seed. Resent unchanged it is still the Executive's text, so it keeps
+ // recording the short memory line; anything else sent next (an edit, a
+ // new question, a suggestion chip) records its own text. Cleared on send.
+ const restoredHandoffRef = useRef<{ seed: string; memoryText: string } | undefined>(undefined);
useEffect(() => {
if (didAutoSubmitRef.current) return;
if (!autoSubmitInitialInput) return;
const seed = (initialInput ?? "").trim();
if (!seed) return;
didAutoSubmitRef.current = true;
- handleSend(seed);
+ handleSend(seed, initialMemoryText);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -209,9 +218,14 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
setSessionId(id);
}
- async function handleSend(text?: string) {
+ async function handleSend(text?: string, memoryText?: string) {
const message = (text ?? input).trim();
if ((!message && pendingFiles.length === 0) || isLoading) return;
+ const restored = restoredHandoffRef.current;
+ restoredHandoffRef.current = undefined;
+ const turnMemoryText =
+ memoryText ??
+ (text === undefined && restored?.seed === message ? restored.memoryText : undefined);
const filesForTurn = pendingFiles;
const userBubbleContent = filesForTurn.length
@@ -255,6 +269,7 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
files: filesForTurn,
clientTurnId,
signal,
+ memoryText: turnMemoryText,
})) {
if (item.type === "debug_event") {
onDebugEvent?.(item);
@@ -320,6 +335,9 @@ export default function Chat({ onDebugEvent, initialMessages, initialSessionId,
: prev,
);
setInput(message);
+ restoredHandoffRef.current = turnMemoryText
+ ? { seed: message, memoryText: turnMemoryText }
+ : undefined;
}
} else if (accumulated || turnActions.length > 0) {
setMessages((prev) => [
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index e1e4f74d..9f5d29fe 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -145,6 +145,11 @@ export interface StreamChatOptions {
// Client-minted id for this turn, so it can be addressed by `stopChat`.
// Omit it and the turn simply isn't stoppable.
clientTurnId?: string;
+ // What peer memory records as the user's words for this turn, when
+ // `message` carries text they did not write (a briefing handoff seeds the
+ // Executive's own card body). JSON route only; the multipart route derives
+ // its own from the typed text and filenames.
+ memoryText?: string;
// Safety net only. The normal stop path leaves the stream open and lets the
// server wind down and send `stopped` + `done`; this aborts the fetch
// outright if that never arrives.
@@ -182,6 +187,7 @@ export async function* streamChat(
committee_review: committeeReview,
page_context: opts?.pageContext ?? undefined,
client_turn_id: opts?.clientTurnId ?? undefined,
+ memory_text: opts?.memoryText ?? undefined,
}),
signal: opts?.signal,
});
diff --git a/packages/ui/src/lib/briefing-memory.ts b/packages/ui/src/lib/briefing-memory.ts
new file mode 100644
index 00000000..02083a4b
--- /dev/null
+++ b/packages/ui/src/lib/briefing-memory.ts
@@ -0,0 +1,16 @@
+// Most briefing handoff seeds quote the Executive's own card (an artifact's
+// body, a proposal, a monitoring signal). Peer memory records a turn's user
+// message as the user's own words, so recording the seed would credit the
+// user with what the Executive wrote ("<user> assigned a colleague to …"). Those
+// handoffs send this short line as the turn's memory text instead.
+
+// Well under the backend's 2000-char `ChatRequest.memory_text` bound, so a
+// long narrative bullet can never 422 the whole turn.
+export const MEMORY_LINE_MAX_CHARS = 300;
+
+export function briefingMemoryLine(action: string, subject: string): string {
+ const s = subject.trim().replace(/\s+/g, " ");
+ const clipped =
+ s.length > MEMORY_LINE_MAX_CHARS ? `${s.slice(0, MEMORY_LINE_MAX_CHARS - 1)}…` : s;
+ return clipped ? `${action} "${clipped}".` : `${action}.`;
+}