Skip to content

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

feat(memory): show peer memory per person on the Pulse page

Rufus7e95c6b085e1
diff --git a/packages/core/openexecutive/api/routes/episodic.py b/packages/core/openexecutive/api/routes/episodic.py
index 227dc6bf..e0ecf492 100644
--- a/packages/core/openexecutive/api/routes/episodic.py
+++ b/packages/core/openexecutive/api/routes/episodic.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from fastapi import APIRouter, HTTPException, Response, status
+from fastapi import APIRouter, HTTPException, Query, Response, status
from pydantic import BaseModel
from openexecutive.memory.episodic import (
@@ -20,6 +20,7 @@ from openexecutive.memory.episodic import (
update_decision,
update_initiative,
)
+from openexecutive.memory.honcho_client import PeopleMemory, people_overview
router = APIRouter()
@@ -117,3 +118,14 @@ def remove_advice(advice_id: int) -> Response:
if not delete_advice(advice_id):
raise HTTPException(status_code=404, detail="Advice not found")
return Response(status_code=status.HTTP_204_NO_CONTENT)
+
+
+# --- People (peer memory) ---
+
+
[email protected]("/memories/people", response_model=PeopleMemory)
+async def list_people_memory(recent: int = Query(5, ge=1, le=50)) -> PeopleMemory:
+ """What peer memory knows about each rostered person: card, conclusion
+ count, last-learned time and the ``recent`` newest conclusions. Read-only
+ and LLM-free; ``status`` is ``disabled`` when peer memory is off."""
+ return await people_overview(recent=recent)
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index 506da44b..87d095b7 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -1304,6 +1304,41 @@ peer_memory:
``disabled | ok | error`` with ``latency_ms``. Intentionally does
NOT exercise the dialectic endpoint (that would cost an LLM call
per probe).
+ people_overview: |
+ ``GET /memories/people?recent=N`` (``honcho_client.people_overview``)
+ — what peer memory knows about each rostered person, for the Pulse
+ page's People tab. Read-only, no LLM call: one ``peers()`` listing
+ (every page, under one 15 s clock — the SDK walk is otherwise bounded
+ only per request), then per matched person (at most 8 in flight, each
+ under the unscaled prefetch budget, because the reads share the
+ per-loop client with the live chat prefetch) one self-conclusions
+ page (``peer.conclusions``,
+ newest first, ``recent`` of them, plus the page total) and one
+ ``get_card()`` with OE's own ``IDENTITY:`` lines removed. Peers are
+ matched to the roster by id and never created — ``peer(id)`` is a
+ get-or-create POST and a read must not mint peers for people who
+ have never talked; the ``executive`` and ``department_*`` peers and
+ archived people are skipped. Every line, timestamps included, passes
+ ``_block_safe_line``. The UI shares one in-flight request between the
+ header and the tab.
+ Response ``{status: ok|disabled|error, people: [{person_id,
+ full_name, is_principal, card, conclusion_count, last_observed_at,
+ recent: [{content, created_at}], error}], conclusion_total}``; one
+ person's failure or timeout sets that entry's ``error`` and leaves
+ the rest intact. One ``peer_memory`` row per call, ``op=overview``,
+ ``person_id`` null, ``details.people / conclusions / errors``. The
+ Pulse header adds ``conclusion_total`` to its Memories tile (hint
+ names the peer-note share; fetched apart from the gating batch so
+ the strip never waits on Honcho); the UI hides the tab when
+ ``status`` is ``disabled``. Peers match only an id spelled exactly
+ as OE writes it, once per person; within the newest page the
+ conclusions are ordered by instant (never by the rendered string,
+ which is not chronological across offsets); card elements and
+ conclusions are split on physical lines and scrubbed before the
+ identity-line filter, so a claim on an element's second line is
+ caught too. The UI is
+ read-only here: peer memory is Honcho's derived view, not the
+ Executive's own record the way decisions and advice are.
audit_filter: |
``/audit?event_type=peer_memory`` for the flat list;
``/audit/session/{id}`` for per-turn context with peer_memory
diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.json
index a89a33a7..b0c65f86 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` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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}` | Episodic-memory record management. |\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` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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-21T17:18:01.394900+00:00"
+ "generated_at": "2026-09-21T17:53:33Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/memory.json b/packages/core/openexecutive/architecture/prebuilt/memory.json
index dfd69cbf..93a25d78 100644
--- a/packages/core/openexecutive/architecture/prebuilt/memory.json
+++ b/packages/core/openexecutive/architecture/prebuilt/memory.json
@@ -1,7 +1,7 @@
{
"section_id": "memory",
"title": "Memory System",
- "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(user_message)` is true, which means only that the principal said something — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.",
+ "markdown": "The Executive's durable memory is an episodic SQLite store at `./episodic_memory.db`, managed by `openexecutive.memory.episodic`. It holds four tables:\n\n- `decisions` — choices made, with `domain`, `summary`, `rationale`, `outcome`, and `tags`.\n- `initiatives` — tracked efforts with a `status` and `summary` (idempotent upserts).\n- `advice_given` — query/advice pairs per domain.\n- `scheduled_actions` — a dispatch queue, treated separately from recall memory.\n\n### What gets extracted, and when\n\n`episodic.extract_and_store` runs after a turn and asks a utility-fast model for decisions, initiatives and advice. Every candidate must carry a `user_commitment_quote` that appears verbatim in the principal's own message (`_is_valid_user_commitment`) — the model has repeatedly tried to log the Executive's *recommendations* as the user's commitments, and that quote is the hard gate against it.\n\nA turn reaches the extractor if `should_extract(user_message)` is true, which means only that the principal said something — there is deliberately **no length floor**. There used to be one, on the combined user+assistant length, and on a live tenant it selected almost exactly the wrong turns: 9 of 16 exchanges were blocked, and the 9 held every instruction the principal gave, while the 7 admitted were long analytical exchanges with no commitment in them. The extractor ran 13 times and stored nothing.\n\nMoving that floor to the user's side would relocate the bug, not fix it. The canonical executive decision is a long analysis answered with \"Approve option B.\" (17 chars) or \"Do B.\" (5), and any floor high enough to skip \"Done\" (4) also skips those — \"Do B.\" and \"Done\" differ by one character and mean opposite things. Length cannot separate a decision from an acknowledgement; the verbatim-quote check can, so `_is_valid_user_commitment` is the gate that decides. The price is one utility-fast call on turns that propose nothing.\n\nThat quote check is only meaningful when `user_message` holds the **principal's** words, and on a chat channel it does not — `Executive.chat()` is reached from Slack, Discord, Telegram, Google Chat and the email poller. A teammate's line would be written to `decisions` with no speaker attached, indistinguishable from the principal's own; an inbound email body is text the sender chose, so a self-quote is free. Removing the length floor is what makes this bite — short channel traffic used to fall under it incidentally — so `should_extract` also takes the turn's `origin_channel` and `person_id`. No channel means the web app, the CLI or the API, all of them the principal's own authenticated surfaces, where `person_id` is legitimately null in a single-user install. A turn that names a channel must resolve to a person marked `is_principal`, and an unresolvable speaker fails closed.\n\nEach pass writes a `memory_extraction` audit row — in a `finally`, so a pass that crashed is recorded too, with the exception type as its `failure` reason: how many items the model proposed, how many were stored, a `malformed` count so a pass where the model returned only garbage does not read as one that found nothing, and a `{kind, reason}` record per drop — `bad_quote` and `missing_field` for an item the model proposed, `not_a_list`, `item_not_a_dict` and `payload_not_a_dict` for a shape that was never a usable item. Every proposed item is either stored or dropped, so `proposed == stored + item drops` is the arithmetic that says whether anything was lost silently. The tool payload is not schema-checked anywhere, so a malformed shape is counted as a drop rather than raised — it used to abort the whole pass, discarding the other two kinds with it and suppressing the row, which read exactly like \"extraction never ran\". Without it, \"the model found nothing\" and \"the model found things and every one was rejected\" are indistinguishable from outside the database — which is why the failure above survived undetected and took a SQLite session on the tenant to find. A `proposed>0, stored=0` streak is the signal to watch.\n\n### Session scoping\n\n`decisions` and `advice_given` rows carry a `session_id`, so per-thread channels (Discord, Telegram) can pull just-this-thread history without leaking cross-conversation context. A null `session_id` falls back to a global view.\n\n### Surfacing\n\n`openexecutive.memory.episodic.format_for_prompt` renders recent decisions and initiatives into a compact `<past_decisions>` block injected into the user turn — alongside `<retrieved_context>` and peer memory — never into a cached system block.\n\nThe chat route also injects a `<briefing>` block into the same user turn: a compact digest of the current open (unread) alerts, built by `openexecutive.briefing.context.format_open_alerts_for_prompt` (company-wide, `status=\"unread\"`, mirroring `/today`). This is what lets the Executive discuss a briefing item the principal clicked or named on `/today` (e.g. \"Gulf Coast Port Cyberattack\"). It is resolved in parallel with the other context fetches, omitted when there are no open alerts, and never placed in a cached system block.\n\nOn the Pulse page the Memory section shows the three lists as Decisions, Initiatives and Advice tabs, with a fourth **People** tab for peer memory (what Honcho has derived about each person, read-only, see the peer memory section). The header's Memories tile counts the three lists plus the peer notes, and says how many of the number are peer notes in its hint, since the People tab's badge counts people rather than notes.\n\n### System of record\n\nSQL is the system of record; the peer-memory service is a recall layer mirrored from it, not a replacement. When `store_decision` / `store_initiative` / `store_advice` insert a row whose `department` is non-empty and not `\"general\"`, the row is mirrored as a kind-tagged note into that department's peer via `append_department_note`. The mirror fires only after a successful INSERT, is fire-and-forget, and never rolls back the SQL row on peer-memory failure. `scheduled_actions` is never mirrored — it is a queue, not memory.",
"mermaid": "flowchart TD\n Store[\"store_decision / store_initiative / store_advice\"]\n DB[\"episodic_memory.db<br/>decisions / initiatives<br/>advice_given / scheduled_actions\"]\n Fmt[\"format_for_prompt\"]\n Turn[\"User turn<br/>past_decisions block\"]\n Mirror[\"append_department_note\"]\n Peer[\"Department peer<br/>(Honcho)\"]\n Store --> DB\n DB --> Fmt\n Fmt --> Turn\n Store -->|\"dept set & not general\"| Mirror\n Mirror -->|\"fire-and-forget\"| Peer\n class Store entry\n class DB storage\n class Fmt compute\n class Turn hot\n class Peer external\n",
- "generated_at": "2026-06-01T00:00:00+00:00"
+ "generated_at": "2026-09-21T18:09:13Z"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
index df5fa2a6..df10a953 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### 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 Pre --> Audit\n Sync --> Audit\n class Turn entry\n class Gate compute\n class Pre compute\n class Sync compute\n class Honcho external\n class Audit storage\n",
- "generated_at": "2026-09-21T13:39:40.062476+00:00"
+ "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}`.",
+ "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"
}
diff --git a/packages/core/openexecutive/memory/honcho_client.py b/packages/core/openexecutive/memory/honcho_client.py
index 05eb257d..46c792a6 100644
--- a/packages/core/openexecutive/memory/honcho_client.py
+++ b/packages/core/openexecutive/memory/honcho_client.py
@@ -42,8 +42,11 @@ import logging
import re
import time
import unicodedata
+from datetime import UTC, datetime
from typing import Any, Literal, NamedTuple
+from pydantic import BaseModel
+
from openexecutive.audit import log_event as audit_log
from openexecutive.audit.context import get_active_ids, set_turn
from openexecutive.config import get_settings
@@ -2196,3 +2199,222 @@ async def _do_append_department_note_body(
"error_msg": str(exc)[:300],
},
)
+
+
+# --------------------------------------------------------------------------- #
+# People overview — what peer memory knows about each rostered person, for the
+# Pulse page. Read-only, no LLM call: one peers listing plus, per person, one
+# conclusions page and one card read.
+# --------------------------------------------------------------------------- #
+
+
+# Bounds for the overview, matching the two precedents in this module: the
+# per-person reads share the per-loop client with the live chat prefetch, so
+# they are capped like the session purge (socket exhaustion), and the peers
+# listing walks every page, so it gets an outer clock like the sync bodies (a
+# blackholing endpoint must not pin the task for minutes).
+_OVERVIEW_CONCURRENCY = 8
+_OVERVIEW_LISTING_TIMEOUT_S = 15.0
+
+
+class PersonConclusion(BaseModel):
+ content: str
+ created_at: str
+
+
+class PersonMemory(BaseModel):
+ person_id: int
+ full_name: str
+ is_principal: bool
+ card: list[str]
+ """Peer card lines minus the identity lines OE writes itself."""
+ conclusion_count: int
+ """The server's total when it reports one, else the page length."""
+ last_observed_at: str | None
+ recent: list[PersonConclusion]
+ """Newest first."""
+ error: str | None = None
+ """Exception type name when this person's read failed; the rest is empty."""
+
+
+class PeopleMemory(BaseModel):
+ status: Literal["ok", "disabled", "error"]
+ people: list[PersonMemory]
+ conclusion_total: int
+
+
+def _overview_error(error_type: str, *, started: float) -> PeopleMemory:
+ _emit_peer_memory(
+ op="overview",
+ person_id=None,
+ outcome="error",
+ duration_ms=int((time.monotonic() - started) * 1000),
+ details={"error_type": error_type},
+ )
+ return PeopleMemory(status="error", people=[], conclusion_total=0)
+
+
+def _iso(value: Any) -> str:
+ return value.isoformat() if hasattr(value, "isoformat") else str(value)
+
+
+def _as_instant(value: Any) -> datetime:
+ """A sortable UTC instant for a ``created_at`` of any shape the server
+ might send: an aware datetime, a naive one (taken as UTC), or an ISO
+ string. Byte order on the rendered string is not chronological across
+ offsets (``13:00+05:00`` sorts after ``12:00Z`` yet is five hours older),
+ so ordering never uses the string. Unparseable values sort oldest."""
+ try:
+ if not isinstance(value, datetime):
+ value = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=UTC)
+ return value.astimezone(UTC)
+ except (ValueError, TypeError, OverflowError, OSError):
+ # Covers the conversion too: a stamp within one offset of the
+ # datetime range parses fine and overflows on `astimezone`.
+ return datetime.min.replace(tzinfo=UTC)
+
+
+def _safe_lines(text: Any) -> list[str]:
+ """Physical lines of one Honcho text value, each scrubbed, blanks dropped.
+ Split before the scrub: the scrub deletes newlines, and a value spanning
+ two lines would otherwise be glued into one that hides what its second
+ line starts with."""
+ lines = (_block_safe_line(line) for line in str(text).splitlines())
+ return [line for line in lines if line]
+
+
+async def _person_memory(person: Any, peer: Any, *, recent: int) -> PersonMemory:
+ """One person's view: the self-conclusions (observer == observed == the
+ peer, the same scope the per-turn prefetch reads) newest first, their
+ total, and the card without the identity lines the roster already
+ supplies. Every line goes through ``_block_safe_line`` because the text
+ was derived from what people wrote, inbound email included."""
+ page = await peer.conclusions.aio.list(size=recent, reverse=True)
+ # `reverse=True` asks the server for its newest page; the order within
+ # that page is sorted here by instant so the first item is the newest
+ # whatever the server's default. When the page carries no total, the
+ # count is at best the page length.
+ items = sorted(page.items, key=lambda c: _as_instant(c.created_at), reverse=True)
+ total = getattr(page, "total", None)
+ if total is None:
+ total = len(items)
+ conclusions = [
+ PersonConclusion(
+ content=" ".join(_safe_lines(c.content)),
+ created_at=_block_safe_line(_iso(c.created_at)),
+ )
+ for c in items
+ ]
+ # Split and scrub before the identity test: a control character ahead of
+ # ``IDENTITY:``, or an identity claim on the second line of one card
+ # element, would otherwise pass the test and reach the page.
+ card = [
+ line
+ for element in (await peer.aio.get_card() or [])
+ for line in _safe_lines(element)
+ if not _is_identity_line(line)
+ ]
+ return PersonMemory(
+ person_id=person.id,
+ full_name=person.full_name,
+ is_principal=person.is_principal,
+ card=card,
+ conclusion_count=int(total),
+ last_observed_at=conclusions[0].created_at if conclusions else None,
+ recent=conclusions,
+ )
+
+
+def _person_memory_failed(person: Any, exc: BaseException) -> PersonMemory:
+ return PersonMemory(
+ person_id=person.id,
+ full_name=person.full_name,
+ is_principal=person.is_principal,
+ card=[],
+ conclusion_count=0,
+ last_observed_at=None,
+ recent=[],
+ error=type(exc).__name__,
+ )
+
+
+async def people_overview(*, recent: int) -> PeopleMemory:
+ """What peer memory knows about each rostered person.
+
+ Peers are taken from the workspace listing and matched to the roster by
+ id, never created: ``client.aio.peer(id)`` is a get-or-create POST and a
+ read-only page must not mint peers for people who have never talked.
+ Non-person peers (the Executive, departments) are skipped. The listing
+ runs under one outer clock; each person is then read under the unscaled
+ prefetch budget, at most ``_OVERVIEW_CONCURRENCY`` at a time, and one
+ person's failure or timeout yields an entry with ``error`` set and
+ leaves the others intact. Principal first, then by person id. One
+ ``peer_memory`` audit row per call, ``op=overview``.
+ """
+ from openexecutive.people import registry
+
+ settings = get_settings()
+ if not settings.honcho_enabled:
+ _emit_peer_memory(op="overview", person_id=None, outcome="disabled")
+ return PeopleMemory(status="disabled", people=[], conclusion_total=0)
+
+ started = time.monotonic()
+ client = await _get_client()
+ if client is None:
+ return _overview_error("ClientConstructionFailed", started=started)
+
+ roster = {p.id: p for p in registry.list_people() if p.id is not None}
+
+ async def _matched_peers() -> list[tuple[Any, Any]]:
+ # Keyed by person: the page walk can yield a peer twice if the
+ # listing shifts under it, and a person must appear once. Only a
+ # peer id spelled exactly as OE writes it (``str(person_id)``)
+ # matches — ``int()`` would also accept "007" or non-ASCII digits,
+ # and a stray id must skip one peer, never fail the listing.
+ found: dict[int, tuple[Any, Any]] = {}
+ async for peer in await client.aio.peers():
+ peer_id = str(getattr(peer, "id", ""))
+ if not (peer_id.isascii() and peer_id.isdigit()):
+ continue
+ person_id = int(peer_id)
+ if str(person_id) == peer_id and person_id in roster and person_id not in found:
+ found[person_id] = (roster[person_id], peer)
+ return list(found.values())
+
+ try:
+ matched = await asyncio.wait_for(_matched_peers(), timeout=_OVERVIEW_LISTING_TIMEOUT_S)
+ except Exception as exc:
+ logger.warning("Honcho peers listing failed: %s", type(exc).__name__)
+ return _overview_error(type(exc).__name__, started=started)
+
+ budget = base_prefetch_timeout_s(settings.honcho_prefetch_timeout_s)
+ gate = asyncio.Semaphore(_OVERVIEW_CONCURRENCY)
+
+ async def _read(person: Any, peer: Any) -> PersonMemory:
+ async with gate:
+ return await asyncio.wait_for(_person_memory(person, peer, recent=recent), timeout=budget)
+
+ results = await asyncio.gather(
+ *(_read(person, peer) for person, peer in matched), return_exceptions=True
+ )
+ people: list[PersonMemory] = []
+ for (person, _peer), result in zip(matched, results, strict=True):
+ if isinstance(result, PersonMemory):
+ people.append(result)
+ elif isinstance(result, Exception):
+ people.append(_person_memory_failed(person, result))
+ else:
+ raise result # a BaseException (cancellation) is not ours to swallow
+ people.sort(key=lambda m: (not m.is_principal, m.person_id))
+ total = sum(m.conclusion_count for m in people)
+ errors = sum(1 for m in people if m.error)
+ _emit_peer_memory(
+ op="overview",
+ person_id=None,
+ outcome="ok",
+ duration_ms=int((time.monotonic() - started) * 1000),
+ details={"people": len(people), "conclusions": total, "errors": errors},
+ )
+ return PeopleMemory(status="ok", people=people, conclusion_total=total)
diff --git a/packages/core/tests/unit/test_memories_people_route.py b/packages/core/tests/unit/test_memories_people_route.py
new file mode 100644
index 00000000..f3e2184f
--- /dev/null
+++ b/packages/core/tests/unit/test_memories_people_route.py
@@ -0,0 +1,490 @@
+"""GET /memories/people — what peer memory knows about each rostered person.
+
+The Pulse page's People tab reads this. It must never create peers (a
+read-only page minting Honcho peers for people who have never talked would be
+a side effect nobody asked for), must skip the non-person peers that share
+the workspace, and must keep one person's failure from hiding the others.
+"""
+from __future__ import annotations
+
+import asyncio
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from openexecutive.api.routes import episodic as episodic_route
+from openexecutive.memory import honcho_client
+from openexecutive.people import registry as people_registry
+from openexecutive.people import store as people_store
+
+
[email protected](autouse=True)
+def _env(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ monkeypatch.setenv("EXEC_EMAIL_ADDRESS", "[email protected]")
+ monkeypatch.setenv("HONCHO_ENABLED", "true")
+ monkeypatch.setenv("HONCHO_API_KEY", "test-key")
+ monkeypatch.setenv("HONCHO_BASE_URL", "http://localhost:8000")
+ monkeypatch.delenv("HONCHO_PREFETCH_TIMEOUT_S", raising=False)
+ honcho_client.reset_client_for_tests()
+
+
[email protected](autouse=True)
+def audit_rows(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
+ """Every overview call writes a `peer_memory` row; capture them all so
+ none reaches the default `./episodic_memory.db` (the audit-log pollution
+ trap in CLAUDE.md)."""
+ rows: list[dict[str, Any]] = []
+
+ def _spy(event_type: str, summary: str, **kw: Any) -> None:
+ rows.append({"event_type": event_type, "summary": summary, **kw})
+
+ monkeypatch.setattr(honcho_client, "audit_log", _spy)
+ return rows
+
+
+def roster(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, int]:
+ """A principal, a teammate and an archived person; returns their ids."""
+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")
+ people_store.initialize_db()
+ people_registry.invalidate()
+ principal = people_store.upsert_person(full_name="Priya Nair", is_principal=True)
+ member = people_store.upsert_person(full_name="Sam Okafor")
+ gone = people_store.upsert_person(full_name="Left Already")
+ people_store.archive_person(gone)
+ people_registry.invalidate()
+ return {"principal": principal, "member": member, "archived": gone}
+
+
+def _client() -> TestClient:
+ app = FastAPI()
+ app.include_router(episodic_route.router)
+ return TestClient(app)
+
+
+# --------------------------------------------------------------------------- #
+# Fakes — the slice of the Honcho SDK the overview touches
+# --------------------------------------------------------------------------- #
+
+
+class _Conclusion:
+ def __init__(self, content: str, created_at: datetime) -> None:
+ self.content = content
+ self.created_at = created_at
+
+
+class _Page:
+ """`AsyncPage` as the overview uses it: `.items`, `.total`, async iteration."""
+
+ def __init__(self, items: list[Any], total: int | None = None, *, no_total: bool = False) -> None:
+ self.items = items
+ if not no_total:
+ self.total = total if total is not None else len(items)
+
+ def __aiter__(self) -> Any:
+ async def _gen() -> Any:
+ for item in self.items:
+ yield item
+ return _gen()
+
+
+class _ConclusionsAio:
+ def __init__(
+ self,
+ conclusions: list[_Conclusion],
+ total: int | None,
+ calls: list[dict[str, Any]],
+ *,
+ no_total: bool = False,
+ ) -> None:
+ self._conclusions = conclusions
+ self._total = total
+ self._calls = calls
+ self._no_total = no_total
+
+ async def list(self, page: int = 1, size: int = 50, session: Any = None, *, reverse: bool = False) -> _Page:
+ self._calls.append({"size": size, "reverse": reverse})
+ return _Page(self._conclusions[:size], self._total, no_total=self._no_total)
+
+
+class _Conclusions:
+ def __init__(self, aio: _ConclusionsAio) -> None:
+ self.aio = aio
+
+
+_IN_FLIGHT = {"now": 0, "peak": 0}
+
+
+class _PeerAio:
+ def __init__(self, card: list[str] | None, fail: BaseException | None, delay_s: float) -> None:
+ self._card = card
+ self._fail = fail
+ self._delay_s = delay_s
+
+ async def get_card(self, target: Any = None) -> list[str] | None:
+ _IN_FLIGHT["now"] += 1
+ _IN_FLIGHT["peak"] = max(_IN_FLIGHT["peak"], _IN_FLIGHT["now"])
+ try:
+ if self._delay_s:
+ await asyncio.sleep(self._delay_s)
+ if self._fail is not None:
+ raise self._fail
+ return self._card
+ finally:
+ _IN_FLIGHT["now"] -= 1
+
+
+class _Peer:
+ def __init__(
+ self,
+ peer_id: str,
+ *,
+ conclusions: list[_Conclusion] | None = None,
+ total: int | None = None,
+ card: list[str] | None = None,
+ fail: BaseException | None = None,
+ delay_s: float = 0.0,
+ calls: list[dict[str, Any]] | None = None,
+ no_total: bool = False,
+ ) -> None:
+ self.id = peer_id
+ self.calls: list[dict[str, Any]] = calls if calls is not None else []
+ self.conclusions = _Conclusions(
+ _ConclusionsAio(conclusions or [], total, self.calls, no_total=no_total)
+ )
+ self.aio = _PeerAio(card, fail, delay_s)
+
+
+class _ClientAio:
+ def __init__(
+ self, peers: list[_Peer], fail: BaseException | None = None, hang_s: float = 0.0
+ ) -> None:
+ self._peers = peers
+ self._fail = fail
+ self._hang_s = hang_s
+ self.peer_calls: list[str] = []
+
+ async def peers(self, filters: Any = None, *, page: int = 1, size: int = 50, reverse: bool = False) -> _Page:
+ if self._hang_s:
+ await asyncio.sleep(self._hang_s)
+ if self._fail is not None:
+ raise self._fail
+ return _Page(self._peers)
+
+ async def peer(self, peer_id: str, **_: Any) -> _Peer:
+ # The overview must never get-or-create; record if it does.
+ self.peer_calls.append(peer_id)
+ return _Peer(peer_id)
+
+
+class _Client:
+ def __init__(
+ self, peers: list[_Peer], fail: BaseException | None = None, hang_s: float = 0.0
+ ) -> None:
+ self.aio = _ClientAio(peers, fail, hang_s)
+
+
+def _with_client(client: _Client | None) -> Any:
+ async def _get() -> _Client | None:
+ return client
+ return patch.object(honcho_client, "_get_client", _get)
+
+
+_T1 = datetime(2026, 9, 20, 9, 0, tzinfo=UTC)
+_T2 = datetime(2026, 9, 21, 12, 18, 48, tzinfo=UTC)
+
+
+# --------------------------------------------------------------------------- #
+# Tests
+# --------------------------------------------------------------------------- #
+
+
+def test_disabled_returns_disabled_status(monkeypatch: pytest.MonkeyPatch, roster: dict[str, int]) -> None:
+ monkeypatch.setenv("HONCHO_ENABLED", "false")
+ resp = _client().get("/memories/people")
+ assert resp.status_code == 200
+ assert resp.json() == {"status": "disabled", "people": [], "conclusion_total": 0}
+
+
+def test_no_client_returns_error(roster: dict[str, int]) -> None:
+ with _with_client(None):
+ resp = _client().get("/memories/people")
+ assert resp.json()["status"] == "error"
+ assert resp.json()["people"] == []
+
+
+def test_ok_maps_rostered_peers_principal_first(
+ roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ principal = _Peer(
+ str(roster["principal"]),
+ conclusions=[_Conclusion("3 prefers a short table", _T2), _Conclusion("3 runs 48 units", _T1)],
+ total=13,
+ card=["IDENTITY: Name: Priya Nair", "Role: Managing director"],
+ )
+ member = _Peer(str(roster["member"]), conclusions=[_Conclusion("7 is on leave in October", _T1)])
+ client = _Client([_Peer("executive"), member, _Peer("department_finance"), principal])
+ with _with_client(client):
+ resp = _client().get("/memories/people?recent=2")
+
+ body = resp.json()
+ assert body["status"] == "ok"
+ assert [p["full_name"] for p in body["people"]] == ["Priya Nair", "Sam Okafor"], (
+ "principal first; the executive and department peers are not people"
+ )
+ top = body["people"][0]
+ assert top["person_id"] == roster["principal"] and top["is_principal"] is True
+ assert top["card"] == ["Role: Managing director"], "identity lines come from the roster, not the card"
+ assert top["conclusion_count"] == 13, "the page total, not the page length"
+ assert top["last_observed_at"] == _T2.isoformat()
+ assert [c["content"] for c in top["recent"]] == ["3 prefers a short table", "3 runs 48 units"]
+ assert top["error"] is None
+ assert body["conclusion_total"] == 14
+ assert principal.calls == [{"size": 2, "reverse": True}], "newest first, capped by ?recent="
+ assert client.aio.peer_calls == [], "a read-only page must never get-or-create a peer"
+
+ audit = [r for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert len(audit) == 1
+ assert audit[0]["details"]["op"] == "overview"
+ assert audit[0]["details"]["outcome"] == "ok"
+ assert audit[0]["details"]["people"] == 2
+ assert audit[0]["details"]["conclusions"] == 14
+ assert audit[0]["details"]["person_id"] is None
+
+
+def test_archived_and_unknown_people_are_skipped(roster: dict[str, int]) -> None:
+ client = _Client([
+ _Peer(str(roster["archived"]), conclusions=[_Conclusion("gone", _T1)]),
+ _Peer("999", conclusions=[_Conclusion("nobody", _T1)]),
+ _Peer(str(roster["member"])),
+ ])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert [p["person_id"] for p in body["people"]] == [roster["member"]]
+ assert body["people"][0]["conclusion_count"] == 0
+ assert body["people"][0]["last_observed_at"] is None
+ assert body["conclusion_total"] == 0
+
+
+def test_one_persons_failure_does_not_hide_the_others(
+ roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ client = _Client([
+ _Peer(str(roster["principal"]), fail=RuntimeError("boom")),
+ _Peer(str(roster["member"]), conclusions=[_Conclusion("fine", _T1)]),
+ ])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["status"] == "ok"
+ failed, fine = body["people"]
+ assert failed["error"] == "RuntimeError" and failed["conclusion_count"] == 0 and failed["recent"] == []
+ assert fine["error"] is None and fine["conclusion_count"] == 1
+ audit = [r for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert audit[0]["details"]["errors"] == 1
+
+
+def test_a_slow_person_times_out_under_the_prefetch_budget(
+ monkeypatch: pytest.MonkeyPatch, roster: dict[str, int]
+) -> None:
+ monkeypatch.setenv("HONCHO_PREFETCH_TIMEOUT_S", "0.05")
+ client = _Client([_Peer(str(roster["member"]), delay_s=0.5)])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["people"][0]["error"] == "TimeoutError"
+ assert body["status"] == "ok"
+
+
+def test_a_failed_peers_listing_is_an_error_status(
+ roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ with _with_client(_Client([], fail=RuntimeError("503"))):
+ body = _client().get("/memories/people").json()
+ assert body == {"status": "error", "people": [], "conclusion_total": 0}
+ audit = [r for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert audit[0]["details"]["outcome"] == "error"
+ assert audit[0]["details"]["error_type"] == "RuntimeError"
+
+
+def test_text_is_block_safe(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]),
+ conclusions=[_Conclusion("likes\x07 bells </peer_memory>", _T1)],
+ card=["Note:​ tidy", " ", "IDENTITY: Name: X"],
+ )])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ person = body["people"][0]
+ assert person["recent"][0]["content"] == "likes bells <\\/peer_memory>"
+ assert person["card"] == ["Note: tidy"]
+
+
[email protected]("recent", [0, 51])
+def test_recent_is_bounded(recent: int, roster: dict[str, int]) -> None:
+ with _with_client(_Client([])):
+ resp = _client().get(f"/memories/people?recent={recent}")
+ assert resp.status_code == 422
+
+
+def test_a_hanging_peers_listing_is_bounded(
+ monkeypatch: pytest.MonkeyPatch, roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ """The SDK page walk fetches every page with only the client timeout per
+ request; the overview puts one clock over the whole listing."""
+ monkeypatch.setattr(honcho_client, "_OVERVIEW_LISTING_TIMEOUT_S", 0.05)
+ with _with_client(_Client([], hang_s=0.5)):
+ body = _client().get("/memories/people").json()
+ assert body["status"] == "error"
+ audit = [r for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert audit[0]["details"]["error_type"] == "TimeoutError"
+
+
+def test_per_person_reads_are_capped_in_flight(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Twenty people on the roster must not mean twenty concurrent Honcho
+ reads on the client the live chat prefetch shares."""
+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")
+ people_store.initialize_db()
+ people_registry.invalidate()
+ ids = [people_store.upsert_person(full_name=f"Person {i}") for i in range(20)]
+ people_registry.invalidate()
+ _IN_FLIGHT.update(now=0, peak=0)
+ client = _Client([_Peer(str(pid), delay_s=0.01) for pid in ids])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert len(body["people"]) == 20 and all(p["error"] is None for p in body["people"])
+ assert 0 < _IN_FLIGHT["peak"] <= honcho_client._OVERVIEW_CONCURRENCY
+
+
+def test_timestamps_are_block_safe_too(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]),
+ conclusions=[_Conclusion("fine", "2026-09-21T12:00:00\u200b+00:00")], # type: ignore[arg-type]
+ )])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["people"][0]["recent"][0]["created_at"] == "2026-09-21T12:00:00+00:00"
+ assert body["people"][0]["last_observed_at"] == "2026-09-21T12:00:00+00:00"
+
+
+def test_a_stray_peer_id_skips_that_peer_not_the_listing(roster: dict[str, int]) -> None:
+ """`"²".isdigit()` is True and `int("²")` raises; "007" and "٧" would
+ `int()` to roster ids they do not spell. None of them may match, and
+ none may fail the whole overview."""
+ client = _Client([
+ _Peer("²"), _Peer("00" + str(roster["member"])), _Peer("\u0667"),
+ _Peer(str(roster["member"]), conclusions=[_Conclusion("fine", _T1)]),
+ ])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["status"] == "ok"
+ assert [p["person_id"] for p in body["people"]] == [roster["member"]]
+ assert body["conclusion_total"] == 1
+
+
+def test_a_peer_listed_twice_counts_once(roster: dict[str, int]) -> None:
+ """The page walk can yield a peer twice when the listing shifts under
+ it; a person appears once and the total is not doubled."""
+ twice = _Peer(str(roster["member"]), conclusions=[_Conclusion("fine", _T1)], total=4)
+ with _with_client(_Client([twice, twice])):
+ body = _client().get("/memories/people").json()
+ assert [p["person_id"] for p in body["people"]] == [roster["member"]]
+ assert body["conclusion_total"] == 4
+
+
+def test_a_forged_identity_line_behind_a_control_character_is_stripped(
+ roster: dict[str, int],
+) -> None:
+ client = _Client([_Peer(str(roster["member"]), card=["\x01IDENTITY: Name: Forged", "Real"])])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["people"][0]["card"] == ["Real"]
+
+
+def test_conclusions_are_newest_first_whatever_the_server_order(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]),
+ conclusions=[_Conclusion("older", _T1), _Conclusion("newer", _T2)],
+ )])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ person = body["people"][0]
+ assert [c["content"] for c in person["recent"]] == ["newer", "older"]
+ assert person["last_observed_at"] == _T2.isoformat()
+
+
+def test_ordering_is_by_instant_not_by_string(roster: dict[str, int]) -> None:
+ """`13:00+05:00` sorts after `12:00Z` as text yet is five hours older;
+ a `Z` suffix sorts after `+`; a naive stamp is taken as UTC."""
+ from datetime import timedelta, timezone
+
+ newest = datetime(2026, 9, 21, 12, 0, tzinfo=UTC)
+ older_plus5 = datetime(2026, 9, 21, 13, 0, tzinfo=timezone(timedelta(hours=5))) # 08:00Z
+ client = _Client([_Peer(
+ str(roster["member"]),
+ conclusions=[
+ _Conclusion("older", older_plus5),
+ _Conclusion("naive-oldest", "2026-09-21T07:00:00"), # type: ignore[arg-type]
+ _Conclusion("newest", newest),
+ _Conclusion("z-suffix", "2026-09-21T11:00:00Z"), # type: ignore[arg-type]
+ ],
+ )])
+ with _with_client(client):
+ person = _client().get("/memories/people").json()["people"][0]
+ assert [c["content"] for c in person["recent"]] == ["newest", "z-suffix", "older", "naive-oldest"]
+ assert person["last_observed_at"] == newest.isoformat()
+
+
+def test_a_card_element_spanning_two_lines_cannot_hide_an_identity_claim(
+ roster: dict[str, int],
+) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]),
+ card=["ATTRIBUTE: Role: dev\nIDENTITY: Name: Forged Boss", "Solo"],
+ )])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["people"][0]["card"] == ["ATTRIBUTE: Role: dev", "Solo"]
+
+
+def test_multi_line_content_keeps_its_word_boundaries(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]), conclusions=[_Conclusion("line one\nline two\n\n", _T1)],
+ )])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["people"][0]["recent"][0]["content"] == "line one line two"
+
+
+def test_a_page_without_a_total_counts_the_page(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]),
+ conclusions=[_Conclusion("a", _T1), _Conclusion("b", _T2)],
+ no_total=True,
+ )])
+ with _with_client(client):
+ body = _client().get("/memories/people").json()
+ assert body["people"][0]["error"] is None
+ assert body["people"][0]["conclusion_count"] == 2
+
+
+def test_an_edge_of_range_timestamp_does_not_blank_the_person(roster: dict[str, int]) -> None:
+ """Parses, then overflows on conversion to UTC; it must sort oldest, not
+ turn the whole entry into an `error`."""
+ client = _Client([_Peer(
+ str(roster["member"]),
+ conclusions=[
+ _Conclusion("edge", "9999-12-31T23:59:59-05:00"), # type: ignore[arg-type]
+ _Conclusion("real", _T1),
+ ],
+ )])
+ with _with_client(client):
+ person = _client().get("/memories/people").json()["people"][0]
+ assert person["error"] is None
+ assert [c["content"] for c in person["recent"]] == ["real", "edge"]
diff --git a/packages/ui/src/components/memories/MemorySection.tsx b/packages/ui/src/components/memories/MemorySection.tsx
index 595521f1..ea524422 100644
--- a/packages/ui/src/components/memories/MemorySection.tsx
+++ b/packages/ui/src/components/memories/MemorySection.tsx
@@ -8,18 +8,24 @@ import {
listAdvice,
listDecisions,
listInitiatives,
+ listPeopleMemory,
updateAdvice,
updateDecision,
updateInitiative,
type Advice,
type Decision,
type Initiative,
+ type PeopleMemory,
+ type PersonMemory,
} from "@/lib/api";
import { DOMAINS, STATUSES, EmptyState, formatDate } from "./shared";
-type MemoryTab = "decisions" | "initiatives" | "advice";
+type MemoryTab = "decisions" | "initiatives" | "advice" | "people";
const MEMORY_EMPTY = "No memories yet — they're extracted automatically after chats.";
+const PEOPLE_EMPTY =
+ "Nothing learned about anyone yet — peer memory fills in as people talk with the Executive.";
+const PEOPLE_UNAVAILABLE = "Peer memory is unavailable right now.";
// ---------------------------------------------------------------------------
// Section shell — the "what it knows" half of the Pulse page.
@@ -35,7 +41,12 @@ export default function MemorySection() {
decisions: null,
initiatives: null,
advice: null,
+ people: null,
});
+ // Peer memory is optional: until its status is known the People tab shows
+ // (so the bar does not jump on installs that have it); once the backend says
+ // "disabled" the tab goes away for good.
+ const [peopleEnabled, setPeopleEnabled] = useState<boolean | null>(null);
// Stable per-tab callbacks — these are passed to the (always-mounted) tabs as
// `onCount`, which lives in each tab's `refresh` useCallback deps. They MUST
// keep a constant identity across renders, or the tab's refresh→useEffect
@@ -44,12 +55,29 @@ export default function MemorySection() {
const onCountDecisions = useCallback((n: number) => setCounts((c) => ({ ...c, decisions: n })), []);
const onCountInitiatives = useCallback((n: number) => setCounts((c) => ({ ...c, initiatives: n })), []);
const onCountAdvice = useCallback((n: number) => setCounts((c) => ({ ...c, advice: n })), []);
+ const onCountPeople = useCallback(
+ (n: number | null) => setCounts((c) => ({ ...c, people: n })),
+ [],
+ );
+ const onPeopleStatus = useCallback(
+ (s: PeopleMemory["status"]) => setPeopleEnabled(s !== "disabled"),
+ [],
+ );
+
+ useEffect(() => {
+ if (peopleEnabled === false && tab === "people") setTab("decisions");
+ }, [peopleEnabled, tab]);
+
+ const tabs: MemoryTab[] =
+ peopleEnabled === false
+ ? ["decisions", "initiatives", "advice"]
+ : ["decisions", "initiatives", "advice", "people"];
return (
<div className="rounded-xl border border-line bg-surface-elevated p-4">
<div className="mb-3">
<div className="flex gap-1 p-1 bg-surface-overlay/60 rounded-xl w-fit border border-line-strong/50">
- {(["decisions", "initiatives", "advice"] as MemoryTab[]).map((t) => (
+ {tabs.map((t) => (
<button
key={t}
onClick={() => setTab(t)}
@@ -70,7 +98,7 @@ export default function MemorySection() {
</div>
</div>
- {/* One scroll region shared by all three (always-mounted) tabs, mirroring
+ {/* One scroll region shared by all (always-mounted) tabs, mirroring
the Recent activity card — the list scrolls instead of growing. */}
<div className="max-h-[32rem] overflow-y-auto pr-1">
<div className={tab === "decisions" ? "" : "hidden"}>
@@ -82,6 +110,9 @@ export default function MemorySection() {
<div className={tab === "advice" ? "" : "hidden"}>
<AdviceTab onCount={onCountAdvice} />
</div>
+ <div className={tab === "people" ? "" : "hidden"}>
+ <PeopleTab onCount={onCountPeople} onStatus={onPeopleStatus} />
+ </div>
</div>
</div>
);
@@ -550,3 +581,102 @@ function AdviceRow({
</div>
);
}
+
+// ---------------------------------------------------------------------------
+// People — peer memory. What the Executive has learned about each person,
+// derived server-side from their conversations. Read-only: unlike the three
+// lists above this is not the Executive's own record to edit, and the header
+// counts its notes alongside them.
+// ---------------------------------------------------------------------------
+
+function PeopleTab({
+ onCount,
+ onStatus,
+}: {
+ onCount: (n: number | null) => void;
+ onStatus: (s: PeopleMemory["status"]) => void;
+}) {
+ const [data, setData] = useState<PeopleMemory | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [failed, setFailed] = useState(false);
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setFailed(false);
+ try {
+ const res = await listPeopleMemory();
+ setData(res);
+ onStatus(res.status);
+ // The badge counts people, not notes (the header carries the notes).
+ // Unavailable is not zero: leave the badge blank rather than claim 0.
+ onCount(res.status === "ok" ? res.people.length : null);
+ } catch {
+ // Unlike the other tabs, an error here must not masquerade as "nothing
+ // known": the read crosses to another service.
+ setFailed(true);
+ onCount(null);
+ } finally {
+ setLoading(false);
+ }
+ }, [onCount, onStatus]);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ if (loading) return <div className="text-fg-muted text-sm">Loading…</div>;
+ if (failed || !data || data.status === "error") {
+ return <div className="text-fg-muted text-sm">{PEOPLE_UNAVAILABLE}</div>;
+ }
+ if (data.status === "disabled") return null;
+ if (data.people.length === 0) return <EmptyState message={PEOPLE_EMPTY} />;
+
+ return (
+ <div className="divide-y divide-line">
+ {data.people.map((p) => (
+ <PersonMemoryRow key={p.person_id} item={p} />
+ ))}
+ </div>
+ );
+}
+
+function PersonMemoryRow({ item }: { item: PersonMemory }) {
+ const notes = `${item.conclusion_count} ${item.conclusion_count === 1 ? "note" : "notes"}`;
+ const learned = item.last_observed_at ? ` · learned ${formatDate(item.last_observed_at)}` : "";
+ const nothingYet = !item.error && item.conclusion_count === 0 && item.card.length === 0;
+ return (
+ <div className="py-3">
+ <div className="flex items-start justify-between gap-2">
+ <div className="text-sm font-semibold text-fg flex items-center gap-2">
+ {item.full_name}
+ {item.is_principal && (
+ <span className="inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium bg-violet-500/20 text-violet-300 border-violet-500/30">
+ Principal
+ </span>
+ )}
+ {/* The notes below name people by their bare peer id; this is the key. */}
+ <span className="text-[10px] font-normal text-fg-subtle">peer {item.person_id}</span>
+ </div>
+ <div className="text-xs text-fg-muted tabular-nums shrink-0">
+ {item.error ? "couldn't read" : `${notes}${learned}`}
+ </div>
+ </div>
+ {item.card.length > 0 && (
+ <div className="mt-1 text-xs text-fg-muted">{item.card.join(" · ")}</div>
+ )}
+ {item.recent.length > 0 && (
+ <ul className="mt-2 space-y-1">
+ {item.recent.map((c, i) => (
+ <li key={`${c.created_at}-${i}`} className="text-sm text-fg-muted flex gap-2">
+ <span className="text-[10px] text-fg-subtle tabular-nums shrink-0 pt-0.5">
+ {formatDate(c.created_at)}
+ </span>
+ <span>{c.content}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ {nothingYet && <div className="mt-1 text-xs text-fg-subtle">Nothing learned yet.</div>}
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/memories/PulseHeader.tsx b/packages/ui/src/components/memories/PulseHeader.tsx
index 0627d359..a85ece9f 100644
--- a/packages/ui/src/components/memories/PulseHeader.tsx
+++ b/packages/ui/src/components/memories/PulseHeader.tsx
@@ -6,6 +6,7 @@ import {
listAdvice,
listDecisions,
listInitiatives,
+ listPeopleMemory,
listScheduledActions,
type DailyActivityCount,
type ScheduledAction,
@@ -24,7 +25,10 @@ import {
// Executive's self-initiated activity over the last 90 days. Every metric is
// derived from data the page already needs (pending scheduled actions + the
// three memory lists); only the per-day heatmap requires its own endpoint,
-// since /today/activity returns the last-N items, not a daily timeline.
+// since /today/activity returns the last-N items, not a daily timeline. Peer
+// memory is optional and remote, so it is fetched apart from the gating
+// batch: the strip renders from local data and the tile folds the peer notes
+// in when (and only if) they arrive.
const HEATMAP_DAYS = 90;
@@ -37,6 +41,23 @@ interface HeaderData {
export default function PulseHeader() {
const [data, setData] = useState<HeaderData | null>(null);
const [loading, setLoading] = useState(true);
+ // null until peer memory answers (or fails / is disabled): the tile then
+ // shows the local counts alone, which is not the same as "zero peer notes".
+ const [peerNotes, setPeerNotes] = useState<number | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ listPeopleMemory()
+ .then((people) => {
+ if (!cancelled && people.status === "ok") setPeerNotes(people.conclusion_total);
+ })
+ .catch(() => {
+ /* the tile simply shows the local counts */
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
useEffect(() => {
const controller = new AbortController();
@@ -71,7 +92,7 @@ export default function PulseHeader() {
};
}, []);
- const stats = useMemo(() => (data ? deriveStats(data) : null), [data]);
+ const stats = useMemo(() => (data ? deriveStats(data, peerNotes) : null), [data, peerNotes]);
return (
<header className="space-y-6">
@@ -133,7 +154,10 @@ interface Stat {
tone?: "default" | "accent" | "emerald" | "amber";
}
-function deriveStats({ pending, memoriesTotal, heatmap }: HeaderData): Stat[] {
+function deriveStats(
+ { pending, memoriesTotal, heatmap }: HeaderData,
+ peerNotes: number | null,
+): Stat[] {
const groups = groupByRhythm(pending);
const followups = pending.filter((a) => a.kind === "ad_hoc").length;
@@ -155,7 +179,19 @@ function deriveStats({ pending, memoriesTotal, heatmap }: HeaderData): Stat[] {
{ label: "Daily rhythms", value: groups.daily.length },
{ label: "Dept check-ins", value: groups.departments.length },
{ label: "Follow-ups", value: followups },
- { label: "Memories", value: memoriesTotal },
+ // Three episodic lists plus what peer memory has learned about people;
+ // the hint says how much of the number is peer notes so it reconciles
+ // with the tabs (the People tab badge counts people, not notes).
+ {
+ label: "Memories",
+ value: memoriesTotal + (peerNotes ?? 0),
+ hint:
+ peerNotes === null
+ ? undefined
+ : peerNotes > 0
+ ? `incl. ${peerNotes} peer notes`
+ : "no peer notes yet",
+ },
];
}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index b5cd21c5..65f9c7af 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -798,6 +798,31 @@ export interface Advice {
advice_summary: string;
}
+// Peer memory — what the Executive has learned about each person, derived
+// server-side and read-only here (no edit/delete: it is not the Executive's
+// own record the way decisions and advice are).
+export interface PersonConclusion {
+ content: string;
+ created_at: string;
+}
+
+export interface PersonMemory {
+ person_id: number;
+ full_name: string;
+ is_principal: boolean;
+ card: string[];
+ conclusion_count: number;
+ last_observed_at: string | null;
+ recent: PersonConclusion[];
+ error: string | null;
+}
+
+export interface PeopleMemory {
+ status: "ok" | "disabled" | "error";
+ people: PersonMemory[];
+ conclusion_total: number;
+}
+
export async function listDecisions(): Promise<Decision[]> {
const res = await fetch(`${API_BASE}/memories/decisions`);
if (!res.ok) throw new Error("Failed to list decisions");
@@ -861,6 +886,47 @@ export async function deleteAdvice(id: number): Promise<void> {
if (!res.ok) throw new Error("Failed to delete advice");
}
+// The Pulse header and the People tab both mount on page load and both need
+// this; behind it are one Honcho listing plus two reads per person, so the
+// two mounts share one in-flight request instead of doubling that fan-out.
+const PEOPLE_MEMORY_SHARE_MS = 5_000;
+// `settledAt` is null while the request is still running: a pending request is
+// always shared, however long it has run (the backend bounds it, not us), and a
+// resolved one for five seconds after it settled.
+let peopleMemoryShared: {
+ recent: number;
+ promise: Promise<PeopleMemory>;
+ settledAt: number | null;
+} | null = null;
+
+export function listPeopleMemory(recent = 5): Promise<PeopleMemory> {
+ const shared = peopleMemoryShared;
+ if (
+ shared &&
+ shared.recent === recent &&
+ (shared.settledAt === null || Date.now() - shared.settledAt < PEOPLE_MEMORY_SHARE_MS)
+ ) {
+ return shared.promise;
+ }
+ const promise = (async () => {
+ const res = await fetch(`${API_BASE}/memories/people?recent=${recent}`);
+ if (!res.ok) throw new Error("Failed to list people memory");
+ return (await res.json()) as PeopleMemory;
+ })();
+ const entry = { recent, promise, settledAt: null as number | null };
+ peopleMemoryShared = entry;
+ promise.then(
+ () => {
+ entry.settledAt = Date.now();
+ },
+ () => {
+ // A failure must not be served to the next caller.
+ if (peopleMemoryShared === entry) peopleMemoryShared = null;
+ },
+ );
+ return promise;
+}
+
export interface ScheduledAction {
id: number;
created_at: string;