Skip to content

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

feat(ui): show every peer-memory note in a scrollable People tab (#201)

Rufusdaabb99c5ea9
diff --git a/packages/core/openexecutive/api/routes/episodic.py b/packages/core/openexecutive/api/routes/episodic.py
index e0ecf492..c994cedd 100644
--- a/packages/core/openexecutive/api/routes/episodic.py
+++ b/packages/core/openexecutive/api/routes/episodic.py
@@ -20,7 +20,13 @@ from openexecutive.memory.episodic import (
update_decision,
update_initiative,
)
-from openexecutive.memory.honcho_client import PeopleMemory, people_overview
+from openexecutive.memory.honcho_client import (
+ PERSON_CONCLUSIONS_MAX_PAGE,
+ PeopleMemory,
+ PersonConclusionsPage,
+ people_overview,
+ person_conclusions,
+)
router = APIRouter()
@@ -129,3 +135,18 @@ async def list_people_memory(recent: int = Query(5, ge=1, le=50)) -> PeopleMemor
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)
+
+
[email protected]("/memories/people/{person_id}/conclusions", response_model=PersonConclusionsPage)
+async def list_person_conclusions(
+ person_id: int,
+ page: int = Query(1, ge=1),
+ size: int = Query(50, ge=1, le=PERSON_CONCLUSIONS_MAX_PAGE),
+) -> PersonConclusionsPage:
+ """One page of every conclusion peer memory holds about one person,
+ newest first. Read-only and LLM-free; 404 when the person is not on the
+ roster or peer memory has no peer for them yet."""
+ result = await person_conclusions(person_id, page=page, size=size)
+ if result is None:
+ raise HTTPException(status_code=404, detail="Person not found in peer memory")
+ return result
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index f5bdff71..19a1aa4b 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -1430,6 +1430,21 @@ peer_memory:
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.
+ person_conclusions: |
+ ``GET /memories/people/{person_id}/conclusions?page=&size=``
+ (``honcho_client.person_conclusions``) — every self-conclusion about
+ one person, newest first, one page at a time (``size`` 1–100, default
+ 50). The People tab renders each person as a card whose notes pane is
+ seeded from the overview's ``recent`` and, on "Show all", reads this
+ page by page as the pane scrolls. The peer is found through the same
+ ``peers()`` listing as the overview (shared ``_matched_peers``), never
+ ``peer(id)``: an unknown, archived or never-talked person is a 404,
+ not a new peer. Items are ordered by instant and scrubbed by the same
+ ``_to_conclusion`` as the overview. Response ``{status, person_id,
+ items, page, size, total, has_more}``; ``has_more`` falls back to "the
+ page was full" when the server sends no total. Listing under the 15 s
+ clock, the page read under the unscaled prefetch budget; one
+ ``peer_memory`` row per page, ``op=conclusions``.
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 a44450dc..7e732c43 100644
--- a/packages/core/openexecutive/architecture/prebuilt/api.json
+++ b/packages/core/openexecutive/architecture/prebuilt/api.json
@@ -1,7 +1,7 @@
{
"section_id": "api",
"title": "API Reference",
- "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\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. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | 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| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\n| `company-profile` | `GET\\|PATCH /company-profile` | Structured company profile. |\n| `auth` | `GET /auth/allowed-emails` | Non-archived people with an email, offered to the UI's sign-in gate. The gate takes the **union** of this roster and its own `ALLOWED_EMAILS` env list, so env entries always work (and are checked first, short-circuiting the fetch) and roster entries are additive — a roster change can never revoke a configured operator. |\n| `fixtures` | `/fixtures`, `/fixtures/{name}/load` | Demo-company fixture load/reset/snapshot. |\n| `clients` | `/clients`, `/clients/generate`, `/clients/cockpit`, `/clients/save`, `/clients/{slug}/activate` | Client-company slots — multi-client mode for fractional use; create from current/blank/AI-generated intake draft (pasted notes and/or file attachments, multipart on `/clients/generate`), save-back switching, engagement metadata (PATCH), cross-client cockpit, delete. See the Client Companies section. |\n| webhooks | `POST /webhook/telegram`, `POST /webhook/google-chat` | Inbound integration callbacks (self-verified). |\n| MCP server | `POST\\|GET /mcp` | Open Executive exposed as an MCP server (Streamable-HTTP). Not a router — a mounted FastMCP sub-app. Same shared-secret gate (`x-api-key`); exposes company context as resources and the specialist council as tools. See the MCP Server section. |",
+ "markdown": "The FastAPI surface lives in `openexecutive.api.main`, which mounts one router per topic. A shared-secret middleware gates every request via an `x-api-key` header, except `/health` and the `/webhook/*` callbacks (which carry their own verification). CORS is restricted to configured UI origins. The gate is off when `BACKEND_SHARED_SECRET` is unset — intended for local development only — so any internet-reachable deployment sets `OE_PUBLIC_DEPLOYMENT`, and `create_app()` then refuses to boot without the secret rather than serving an unauthenticated API.\n\nEndpoints grouped by router:\n\n| Router | Key endpoints | Purpose |\n|---|---|---|\n| `chat` | `POST /chat`, `POST /chat/stop` | SSE stream of a live Executive turn. The request body optionally carries `page_context` (route, page title, guide section id, and a form descriptor with current values) — sent only by the Ask OE side panel so the Executive can explain the current page or propose form values. When the Executive calls its `propose_form_values` tool, the stream emits a `form_patch` event (`{type, form_id, fields, rationale, iteration}`) that the panel applies into the on-screen form as highlighted suggestions; the user reviews and saves through the form's normal submit path. Each round of tool calls also emits an `activity` event (`{type, label, tool, iteration}`) naming what is running — progress only, forwarded verbatim and never persisted with the message, unlike an `action_taken` chip. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List and read saved chat sessions (assistant messages carry their row `id` and any `feedback`). The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it (403 otherwise). The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same owner-or-principal 403 as feedback; successful suggestions are cached in-process per (session, reply id). |\n| `today` | `GET /today`, `GET /today/activity`, `GET /today/activity/daily` | Morning-brief aggregation, recent-action rail, and Pulse heartbeat heatmap (per-day activity counts). |\n| `people` | `GET\\|POST\\|PATCH /people`, `POST /people/{id}/archive`, `GET /people/{id}/open-loops`, `POST /open-loops/{loop_id}/close`, `GET /people/{id}/outreach`, `GET\\|PUT\\|DELETE /people/{id}/attunement` | Roster CRUD and scope lookups. Archiving a person closes their open loops. The open-loop routes list what a person owes (soonest due first) and close one (`reason`: done / not_needed / cancelled) — both the principal's or the owner's only (403 otherwise, via `people.store.is_principal_or_self`). `/outreach` returns, per kind of proactive outreach over 30 days, `sent` / `replied` / `acted` / `ignored` / `pending` (voided DMs are excluded) — same access rule, checked before the person lookup so it can't probe which ids exist. `/attunement` reads, replaces (`rules`: up to 4 strings, or omitted to only set `locked`) or resets the person's working-style rules — same access rule, 404 for an archived person; `PUT` rejects a rule that is not purely about style with 422. Archiving a person also drops their working style. |\n| `departments` | `GET\\|POST\\|PATCH\\|DELETE /departments`, `.../goals` | Department state and per-department goals. `PATCH /departments/{slug}` also takes `watched_entities` (≤50 names, `[]` clears) — the entities the research watch policy may add watches for and route to this department. A `cadences` spec that does not parse is rejected with a 422 (empty means no cadence). |\n| `agents` | `GET /agents`, `GET /agents/models`, `GET /agents/models/options`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. `/agents/models` is the flat model allowlist the PATCH validator uses; `/agents/models/options` returns the same ids in the same order, each tagged with `provider`, `provider_label`, `route` (`direct` / `openrouter` / `local`) and a display `label`, for the Council's Provider → Model picker. |\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. Each catalog entry (`WorkflowMeta`) carries `is_custom` and `background` (true for the system-run built-ins the UI files under “System”). The run endpoint streams SSE; its `awaiting_human` event carries `delivery` (`self` \\| `sent` \\| `suppressed` \\| `alerted` \\| `failed`) alongside `person_id` / `question` / `awaiting_until`, because the outbound guard or an unreachable approver means the question may never have been asked — a client must not render “waiting on them” for those. A paused run ends the stream with neither `done` nor `error`, so that `awaiting_human` frame carries `terminal: true` to say so explicitly, plus `resumable` — whether the run continues by itself once answered or stops at the gate. `GET /workflows/runs/{run_id}` returns the run row with the resume payload replaced by a small `resume_progress` summary (`gate_step_id`, `completed_step_ids`, or `null`): the payload holds every completed step's full text, and the run-detail page polls this endpoint while a run is unfinished. |\n| `knowledge` | `/knowledge/builtin`, `/external`, `/search` | MBA knowledge base and external sources. `/search` is the introspection parallel of `retriever.retrieve` and mirrors its filters — including the `general` catch-all on the company collection — so the panel cannot report a specialist seeing nothing that it does retrieve in chat. It accepts `general` in `domain_filter` for the same reason. `/search` applies the same review gate as `retrieve()` — withheld (pending or rejected) built-in, external and failure rows are dropped, so the panel never advertises knowledge the Executive cannot use; it degrades to unfiltered rather than failing if review state is unreadable. `POST /knowledge/builtin` refuses a name already held by shipped content, and `POST|DELETE /knowledge/failures` now register and deregister for review — without that a user-authored failure case study had no review row, so no SME decision could block it. |\n| `skills` | `/skills`, `/skills/search` | 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`, `GET /memories/people/{person_id}/conclusions` | 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) and one person's full conclusion list, paged newest first (`{status, person_id, items, page, size, total, has_more}`; `?page=` ≥1, `?size=` 1–100, default 50; 404 when the person has no peer). |\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| `workflow_designer` | `POST /workflows/designer/start`, `POST /workflows/designer/message`, `POST /workflows/designer/draft`, `GET /workflows/designer/{session_id}` | The conversational New workflow wizard. The `workflow_designer` agent asks clarifying questions (`phase: \"question\"`, with `hint` and up to four suggested `options`), then returns `phase: \"draft\"` with `draft.definition` (exactly the body `POST /workflows/custom` takes), `summary`, and `assumptions`; every response carries the `transcript`. **Nothing is persisted here** — sessions are in memory, and the UI saves through `POST /workflows/custom`. Errors are fixed strings (422 over the 8,000-char message cap or the transcript cap, 404 for an expired session, 409 while another turn on the same session is still running, 502/504 for model failure or timeout). Mounted ahead of the `workflows` router. |\n| `onboarding` (fallback) | `/onboard/start`, `/onboard/answer`, `/onboard/status/{id}` | The original 12-step form wizard, kept as a fallback (UI at `/onboard?mode=form`) and used by the `openexecutive onboard` CLI. |\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-23T22:46:22.244621+00:00"
+ "generated_at": "2026-09-24T12:21:45.972791+00:00"
}
diff --git a/packages/core/openexecutive/architecture/prebuilt/peer_memory.json b/packages/core/openexecutive/architecture/prebuilt/peer_memory.json
index 4798d566..2b341133 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. Honcho derives facts about a person from everything posted under their peer, so a turn whose prompt carries text the person did not write passes `memory_text` to `Executive.chat` / `stream_chat` / `stream_chat_with_committee`, and that — not the prompt — is what both syncs post: an inbound email records the sender's new text, the attachment filenames and its subject unless that is a reply's or forward's (`Re:`, `Fwd:`, `AW:`, `SV:`, `Re[2]:`, `[EXT] Re:` … — the earlier message's subject, often the Executive's own) (never the \"You have an inbound email\" framing, the headers with the Executive's own address in `To:`, the `[POLICY]` notice or the quoted chain, which held the Executive's own earlier email and taught Honcho that the sender *was* the Executive); a web upload records the typed text and filenames, not the extracted document text; a briefing handoff records a short line of what the user asked, phrased as the user speaking and ended before the headline, which follows on its own line (\"Let's discuss this flagged artifact.\" / \"I approve this proposal.\" — an \"Asked to …\" line came back as \"<user> was asked to …\", and a \"?\" in a headline inside the sentence voided the extraction quote); approve-with-edits records the same short line without the edited text, which starts as the Executive's card body and is often sent unchanged, not the Executive's card body it seeds. Filenames are noted as \"(Attached files: …)\", never the \"[Attached: …]\" label that marks inlined document text. The same speaker text, not the prompt, is what episodic extraction and the open-loop pass quote commitments from (see Memory and Attunement). Without `memory_text` the prompt is used, as before. The `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is also stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\n### Prefetch budget\n\nIn representation mode the prefetch is a single read with no LLM behind it: it runs on `HONCHO_PREFETCH_TIMEOUT_S` unscaled and `reasoning_level` is ignored. The rest of this section is the dialectic mode.\n\n`HONCHO_PREFETCH_TIMEOUT_S` is the knob for the **fast per-turn path** and is used unscaled there. The two per-turn callers pick different levels on purpose: `stream_chat` awaits the prefetch inline before the first streamed byte and defaults to `minimal`, the cheapest level, after `low` was measured hitting the ~5 s tail for peers with large representations; the chat route runs the prefetch inside the same gather as knowledge and episodic retrieval, so its `low` adds no dead air of its own and buys a fuller answer. Only the deliberate levels scale off it — `medium` 4x, `high` 5x, `max` 6x — capped by an absolute ceiling and never taken below the configured base. At the default 3s base that is 12s for `medium` with `high`/`max` at the 15s ceiling; at a 10s base every deliberate level *is* the ceiling. The multipliers only differentiate below it — the ceiling is the binding constraint at realistic bases, by design.\n\nHoncho's dialectic latency scales steeply with the level (roughly 2s at `low` against 8s at `medium`), so a single flat budget made the deeper levels unreachable: every `medium` call — the committee path — timed out and the turn silently ran with no peer memory at all, which is strictly worse than having asked for `low`. `medium` gets more headroom than its measurement alone implies because the budget spans `peer()` plus `chat()`, and a budget set at the mean still times out on half the calls.\n\nThe fast levels stay unscaled for two reasons: `prefetch` is awaited inline before the first streamed byte, so multiplying the base there would add dead air to every ordinary turn; and a multiplier above 1.0 flattens every level onto the ceiling once the base approaches it, which would make the operator's knob stop distinguishing the two paths. Each prefetch audit row records the `timeout_s` it ran under.\n\nThe SDK client's HTTP timeout is an **outer** bound, kept strictly greater than every *per-call* budget; the aggregate ceilings on whole passes are deliberately not folded in, since it applies per request and would otherwise hand every unbudgeted call a bound several times too long. Because it is no longer a tight bound, all three fire-and-forget bodies (person sync, department sync, department note) — whose individual calls are not separately budgeted — carry their own aggregate ceiling, as does the session listing in the workspace purge.\n\n### Peer identity\n\nPeers are keyed by `Person.id`, so the only identity signal Honcho gets from the key alone is a bare integer — and its dreaming agent concludes that the number *is* the person's name (observed in production as a card reading `IDENTITY: Name: 1`). Because cards are injected into the dialectic system prompt on every `chat()`, that error propagates into every later answer about that person. So both sync paths seed each person peer's card from the roster, for the sender, the department-turn originator, and co-present peers alike.\n\nThe card carries the **name only** — email and role would export roster PII to a third-party memory service, including for people who were merely cc'd, and neither is needed to fix the defect. `set_card` replaces the whole card, so only `IDENTITY:` lines are swapped and the deriver's own `ATTRIBUTE:` / `RELATIONSHIP:` lines survive; the existing card is split on physical lines first, since one list element may itself span lines and hide an identity claim on its second.\n\nRoster values are attacker-reachable — `upsert_person` is a chat tool an inbound email sender can reach — so a value is NFKC-normalised, stripped of control and format characters, whitespace-flattened, length-capped, and then held to an **allow-list** of letters, combining marks, digits and a small punctuation set, with the colon lookalikes the category allow-list would otherwise admit **stripped out** — taken from Unicode's confusables data (everything it maps to `:`), not from character names, since U+A4FD `ꓽ` is a Lisu *tone letter* whose name never says colon. They are stripped rather than grounds for refusing the value, because the visarga is the nominative ending in formal Devanagari and Gujarati names: refusing would leave those people never seeded, while stripping keeps the name as its stem form and still lets no colon shape reach the card. Modifier letters as a class stay allowed (々 in 佐々木, ー in ジョーンズ, ʻ in Hawaiʻi). A deny-list of structure tokens is not enough here: the consumer is an LLM system prompt rather than a parser, so `ATTRIBUTE :`, a fullwidth colon and a homoglyph all read the same to the model while defeating a literal match. The allow-list refuses every colon variant, which is what card structure depends on — checked by an exhaustive test over every Unicode codepoint whose name contains COLON plus an explicit test of the confusables the names miss. It does **not** stop a value that is merely persuasive prose — OE already embeds `full_name` in its own system prompt, so that exposure is pre-existing rather than introduced here.\n\nSeeding runs *after* the message write and *outside* the sync ceiling, and is audited as its own `seed_identity` row (`ok` only when no peer's attempt failed; `error` when any did, with the `failed` count on the row; `timeout` when the pass or the roster read hit its ceiling; `empty` when there was nobody to seed) — so the sync row is a pure record of the persist, emitted the instant the write lands, and a slow card round trip can neither delay nor replace it. It is bounded per peer *and* per pass, and is best-effort. It is memoized per `(workspace, person)` on the facts sent with a recheck interval — a rename re-seeds immediately, and because the deriver keeps re-deriving identity from the peer id, a one-shot memo would let `IDENTITY: Name: 1` come back unnoticed. A failed attempt is memoized separately and briefly — including every peer a pass-ceiling cut-off left in flight or unreached — so a degraded card endpoint is probed once per interval rather than once per peer per turn.\n\n### Cross-pollination & isolation\n\nWhen a person turn touches a department, the dept peer joins the person's session as a co-present peer — the hybrid peer graph that lets later queries synthesize across both timelines, with synthesis depth degrading at greater peer-graph distance. Demo fixtures run in a sacrificial `openexec-fixture-<name>` workspace so demo turns never pollute real peer cards. Every wrapper call emits a `peer_memory` audit row (`op` + `outcome`) into the per-turn flow at `/audit/session/{id}`.",
+ "markdown": "An external, peer-keyed memory layer gives the Executive durable cross-channel recall, sitting on top of Honcho via `openexecutive.memory.honcho_client`. The `HONCHO_ENABLED` env var gates it; when false every entry point short-circuits with `outcome=disabled` and behavior matches the pre-Honcho posture.\n\n### Two scopes\n\n- **Per-person**, keyed by `Person.id` — a user chatting from Discord, Telegram, email, or web is one peer card, so facts shared in any channel surface in the others. Each entry point resolves the caller to a `Person.id` (channel-ID lookups for adapters; `x-caller-email` for web).\n- **Per-department**, keyed by `department_<slug>` — each department accumulates an institutional voice from dept-scoped decisions, advice, committee outcomes, and dept-bound specialist turns.\n\n### Flow\n\n`prefetch` runs once per turn and injects a `<peer_memory>` block into the user turn (empty on timeout or error). `HONCHO_PREFETCH_MODE` picks how the block is produced. `representation` (the default) reads the person's peer card and the derived conclusions most relevant to the inbound message straight from Honcho (`peer.context(search_query=…)`, `HONCHO_PREFETCH_MAX_CONCLUSIONS` of them, default 20): a GET with no LLM behind it, about 100 ms self-hosted. The block keeps whole lines only, up to a size cap (a line that does not fit is dropped, never cut), strips control characters and defangs a literal closing tag, since conclusions derive from text anyone who can email the Executive wrote. A person Honcho knows nothing about yet yields no block and an `empty` audit outcome. `dialectic` asks Honcho's chat endpoint with the message as the question and injects the synthesized prose (an LLM call, seconds), where `reasoning_level` trades latency for depth. The mode applies to every per-person prefetch, committee turns included. Only `prefetch_department` (one dialectic question per consulted specialist that maps to a department, yielding `<department_memory>`) and the `ask_about_person` tool always use the chat endpoint: they are deliberate questions off the inline path, the split Honcho's own guidance draws between `context()` for per-turn grounding and `chat()` for reasoned answers. After the response, `sync_turn` and `sync_department_turn` persist the exchange as fire-and-forget background tasks that never block the user. The Executive's reply is written under an `executive` peer resolved with `observe_me=false`: the person's representation sees both sides of the exchange, but Honcho no longer derives a representation of the Executive itself, which nothing read and which is where a person's words were occasionally misattributed to the Executive. Both record the person's words only. Honcho derives facts about a person from everything posted under their peer, so a turn whose prompt carries text the person did not write passes `memory_text` to `Executive.chat` / `stream_chat` / `stream_chat_with_committee`, and that — not the prompt — is what both syncs post: an inbound email records the sender's new text, the attachment filenames and its subject unless that is a reply's or forward's (`Re:`, `Fwd:`, `AW:`, `SV:`, `Re[2]:`, `[EXT] Re:` … — the earlier message's subject, often the Executive's own) (never the \"You have an inbound email\" framing, the headers with the Executive's own address in `To:`, the `[POLICY]` notice or the quoted chain, which held the Executive's own earlier email and taught Honcho that the sender *was* the Executive); a web upload records the typed text and filenames, not the extracted document text; a briefing handoff records a short line of what the user asked, phrased as the user speaking and ended before the headline, which follows on its own line (\"Let's discuss this flagged artifact.\" / \"I approve this proposal.\" — an \"Asked to …\" line came back as \"<user> was asked to …\", and a \"?\" in a headline inside the sentence voided the extraction quote); approve-with-edits records the same short line without the edited text, which starts as the Executive's card body and is often sent unchanged, not the Executive's card body it seeds. Filenames are noted as \"(Attached files: …)\", never the \"[Attached: …]\" label that marks inlined document text. The same speaker text, not the prompt, is what episodic extraction and the open-loop pass quote commitments from (see Memory and Attunement). Without `memory_text` the prompt is used, as before. The `<outbound_reply_context>` block that inbound hydration prepends for the LLM turn is also stripped before the message is posted, and from the prefetch query, so the Executive's own DM is never learned as something the person said.\n\n### What it knows, on Pulse\n\nThe Pulse page's Memory section has a **People** tab beside Decisions, Initiatives and Advice, backed by `GET /memories/people` (`people_overview`). It is read-only and costs no LLM call: one listing of the workspace's peers, then, for each peer that matches a rostered person by id, one page of that person's self-conclusions (newest first, `?recent=` of them, plus the total) and one card read with the identity lines the roster already supplies stripped out. Peers are matched, never created — `peer(id)` is a get-or-create POST, and a page you merely open must not mint peers for people who have never talked — and the `executive` and `department_*` peers and archived people are skipped. The listing runs under one clock (the SDK walks every page, bounded only per request otherwise) and each person is then read under the unscaled prefetch budget, at most eight at a time because these reads share the client with the live chat prefetch; one person's failure or timeout marks only that entry (`error`) and the others still render. The header and the tab share one in-flight request per page load. The header's Memories tile adds the conclusion total to the three episodic counts (its hint says how many are peer notes) without waiting on the read, and the tab hides itself when peer memory is disabled. Peers are matched only by an id spelled exactly as OE writes it, once per person, so a stray or repeated peer skips rather than fails or double-counts; within the newest page the conclusions are ordered by instant here (not by the rendered timestamp, which is not chronological across offsets) rather than trusting the server's order. Card elements and conclusions are split on physical lines before the scrub, so an identity claim on the second line of one element is caught too. Every line passes the same control-character and closing-tag scrub as the `<peer_memory>` block, since the text was derived from what people wrote. One `peer_memory` audit row per call, `op=overview`.\n\nEach person renders as a card: the peer card as a list of lines (long ones fold behind a toggle), then their notes in a scrollable pane seeded with the overview's newest few. **Show all** reads `GET /memories/people/{person_id}/conclusions?page=&size=` (`person_conclusions`; `size` 1–100, default 50) page by page as the pane scrolls: the same newest-first self-conclusions, ordered by instant and scrubbed exactly as the overview's, with `{status, person_id, items, page, size, total, has_more}`. The peer is found through the same workspace listing, never `peer(id)`, so an unknown, archived or never-talked person is a 404 rather than a new peer. Same clocks as the overview, one `peer_memory` audit row per page, `op=conclusions`.\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-23T19:18:37Z"
+ "generated_at": "2026-09-24T12:21:45.971984+00:00"
}
diff --git a/packages/core/openexecutive/memory/honcho_client.py b/packages/core/openexecutive/memory/honcho_client.py
index 392fa580..8794a2c1 100644
--- a/packages/core/openexecutive/memory/honcho_client.py
+++ b/packages/core/openexecutive/memory/honcho_client.py
@@ -2290,6 +2290,14 @@ def _safe_lines(text: Any) -> list[str]:
return [line for line in lines if line]
+def _to_conclusion(c: Any) -> PersonConclusion:
+ """One Honcho conclusion as the page shows it, every line scrubbed."""
+ return PersonConclusion(
+ content=" ".join(_safe_lines(c.content)),
+ created_at=_block_safe_line(_iso(c.created_at)),
+ )
+
+
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
@@ -2314,13 +2322,7 @@ async def _person_memory(person: Any, peer: Any, *, recent: int) -> PersonMemory
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
- ]
+ conclusions = [_to_conclusion(c) 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.
@@ -2354,6 +2356,27 @@ def _person_memory_failed(person: Any, exc: BaseException) -> PersonMemory:
)
+async def _matched_peers(client: Any, roster: dict[int, Any]) -> list[tuple[Any, Any]]:
+ """(person, peer) for every rostered person the workspace listing holds.
+
+ 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)
+ if len(found) == len(roster):
+ break
+ return list(found.values())
+
+
async def people_overview(*, recent: int) -> PeopleMemory:
"""What peer memory knows about each rostered person.
@@ -2381,24 +2404,10 @@ async def people_overview(*, recent: int) -> PeopleMemory:
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)
+ matched = await asyncio.wait_for(
+ _matched_peers(client, roster), 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)
@@ -2432,3 +2441,102 @@ async def people_overview(*, recent: int) -> PeopleMemory:
details={"people": len(people), "conclusions": total, "errors": errors},
)
return PeopleMemory(status="ok", people=people, conclusion_total=total)
+
+
+# Honcho's list routes cap a page at 100 items.
+PERSON_CONCLUSIONS_MAX_PAGE = 100
+
+
+class PersonConclusionsPage(BaseModel):
+ status: Literal["ok", "disabled", "error"]
+ person_id: int
+ items: list[PersonConclusion]
+ """Newest first, continuing where the previous page stopped."""
+ page: int
+ size: int
+ total: int | None
+ """The server's total when it reports one."""
+ has_more: bool
+
+
+async def person_conclusions(person_id: int, *, page: int, size: int) -> PersonConclusionsPage | None:
+ """One page of everything peer memory has concluded about one person,
+ newest first — the People tab's "show all" reads it page by page.
+
+ ``None`` when the person is not an active rostered person or has no peer
+ yet (the route answers 404). The peer is found through the workspace
+ listing, as in ``people_overview``, never ``client.aio.peer(id)``: that
+ is a get-or-create and a read must not mint peers. Same clocks as the
+ overview, same scrub, one ``peer_memory`` audit row, ``op=conclusions``.
+ """
+ from openexecutive.people import registry
+
+ def _empty(status: Literal["disabled", "error"]) -> PersonConclusionsPage:
+ return PersonConclusionsPage(
+ status=status, person_id=person_id, items=[], page=page, size=size,
+ total=None, has_more=False,
+ )
+
+ settings = get_settings()
+ if not settings.honcho_enabled:
+ _emit_peer_memory(op="conclusions", person_id=person_id, outcome="disabled")
+ return _empty("disabled")
+
+ started = time.monotonic()
+
+ def _failed(error_type: str) -> PersonConclusionsPage:
+ _emit_peer_memory(
+ op="conclusions",
+ person_id=person_id,
+ outcome="error",
+ duration_ms=int((time.monotonic() - started) * 1000),
+ details={"error_type": error_type},
+ )
+ return _empty("error")
+
+ client = await _get_client()
+ if client is None:
+ return _failed("ClientConstructionFailed")
+
+ person = registry.get_person(person_id)
+ if person is None:
+ return None
+ try:
+ matched = await asyncio.wait_for(
+ _matched_peers(client, {person_id: person}), timeout=_OVERVIEW_LISTING_TIMEOUT_S
+ )
+ if not matched:
+ return None
+ _, peer = matched[0]
+ # reverse=False is the server's newest-first default; see
+ # `_person_memory` for why reverse=True would be the wrong page.
+ result = await asyncio.wait_for(
+ peer.conclusions.aio.list(page=page, size=size, reverse=False),
+ timeout=base_prefetch_timeout_s(settings.honcho_prefetch_timeout_s),
+ )
+ # Inside the try: a malformed page is an error status, not a bare 500.
+ items = sorted(result.items, key=lambda c: _as_instant(c.created_at), reverse=True)
+ conclusions = [_to_conclusion(c) for c in items]
+ raw_total = getattr(result, "total", None)
+ total = None if raw_total is None else int(raw_total)
+ except Exception as exc:
+ logger.warning("Honcho conclusions read failed: %s", type(exc).__name__)
+ return _failed(type(exc).__name__)
+
+ has_more = page * size < total if total is not None else len(items) == size
+ _emit_peer_memory(
+ op="conclusions",
+ person_id=person_id,
+ outcome="ok",
+ duration_ms=int((time.monotonic() - started) * 1000),
+ details={"page": page, "size": size, "items": len(items)},
+ )
+ return PersonConclusionsPage(
+ status="ok",
+ person_id=person_id,
+ items=conclusions,
+ page=page,
+ size=size,
+ total=total,
+ has_more=has_more,
+ )
diff --git a/packages/core/tests/unit/test_memories_people_route.py b/packages/core/tests/unit/test_memories_people_route.py
index e46a7873..17716065 100644
--- a/packages/core/tests/unit/test_memories_people_route.py
+++ b/packages/core/tests/unit/test_memories_people_route.py
@@ -109,7 +109,7 @@ class _ConclusionsAio:
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})
+ self._calls.append({"page": page, "size": size, "reverse": reverse})
# Mirrors the real server: the default (reverse=False) is newest-first
# ("ordered by recency unless reverse is true"), so the list passed to
# `_Peer(conclusions=...)` IS taken as that default order, whatever
@@ -119,7 +119,8 @@ class _ConclusionsAio:
# what would have caught the production bug where the code asked for
# `reverse=True` and silently got the oldest page every time.
ordered = list(reversed(self._conclusions)) if reverse else self._conclusions
- return _Page(ordered[:size], self._total, no_total=self._no_total)
+ start = (page - 1) * size
+ return _Page(ordered[start:start + size], self._total, no_total=self._no_total)
class _Conclusions:
@@ -255,7 +256,7 @@ def test_ok_maps_rostered_peers_principal_first(
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": False}], "newest first, capped by ?recent="
+ assert principal.calls == [{"page": 1, "size": 2, "reverse": False}], "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"]
@@ -525,3 +526,111 @@ def test_an_edge_of_range_timestamp_does_not_blank_the_person(roster: dict[str,
person = _client().get("/memories/people").json()["people"][0]
assert person["error"] is None
assert [c["content"] for c in person["recent"]] == ["real", "edge"]
+
+
+# --------------------------------------------------------------------------- #
+# GET /memories/people/{id}/conclusions — every note, one page at a time
+# --------------------------------------------------------------------------- #
+
+
+def _stamps(n: int) -> list[_Conclusion]:
+ """n conclusions, newest first (the server's default order)."""
+ return [_Conclusion(f"note {i}", datetime(2026, 9, 1, tzinfo=UTC).replace(hour=23 - i)) for i in range(n)]
+
+
+def test_conclusions_pages_through_everything_newest_first(
+ roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ member = _Peer(str(roster["member"]), conclusions=_stamps(5), total=5)
+ client = _Client([member])
+ with _with_client(client):
+ first = _client().get(f"/memories/people/{roster['member']}/conclusions?size=2").json()
+ last = _client().get(f"/memories/people/{roster['member']}/conclusions?page=3&size=2").json()
+
+ assert first["status"] == "ok" and first["person_id"] == roster["member"]
+ assert [c["content"] for c in first["items"]] == ["note 0", "note 1"]
+ assert first["total"] == 5 and first["has_more"] is True
+ assert [c["content"] for c in last["items"]] == ["note 4"]
+ assert last["has_more"] is False
+ assert member.calls == [
+ {"page": 1, "size": 2, "reverse": False},
+ {"page": 3, "size": 2, "reverse": False},
+ ], "newest first, the page the caller asked for"
+ assert client.aio.peer_calls == [], "a read-only page must never get-or-create a peer"
+ audit = [r["details"] for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert [(a["op"], a["outcome"], a["person_id"]) for a in audit] == [
+ ("conclusions", "ok", roster["member"])
+ ] * 2
+
+
+def test_conclusions_without_a_total_guess_more_from_a_full_page(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(str(roster["member"]), conclusions=_stamps(3), no_total=True)])
+ with _with_client(client):
+ full = _client().get(f"/memories/people/{roster['member']}/conclusions?size=2").json()
+ short = _client().get(f"/memories/people/{roster['member']}/conclusions?page=2&size=2").json()
+ assert full["total"] is None and full["has_more"] is True
+ assert short["has_more"] is False
+
+
+def test_conclusions_are_block_safe(roster: dict[str, int]) -> None:
+ client = _Client([_Peer(
+ str(roster["member"]), conclusions=[_Conclusion("likes\x00 tea\nand\u202e cake", _T1)],
+ )])
+ with _with_client(client):
+ body = _client().get(f"/memories/people/{roster['member']}/conclusions").json()
+ overview_item = honcho_client._to_conclusion(_Conclusion("likes\x00 tea\nand\u202e cake", _T1))
+ assert body["items"] == [overview_item.model_dump()], "the same scrub as the overview"
+ assert "\x00" not in body["items"][0]["content"] and "\u202e" not in body["items"][0]["content"]
+
+
[email protected]("who", ["archived", "unknown", "no_peer"])
+def test_conclusions_404_for_anyone_without_a_peer(who: str, roster: dict[str, int]) -> None:
+ person_id = {"archived": roster["archived"], "unknown": 999, "no_peer": roster["principal"]}[who]
+ client = _Client([
+ _Peer(str(roster["archived"]), conclusions=[_Conclusion("gone", _T1)]),
+ _Peer("999", conclusions=[_Conclusion("nobody", _T1)]),
+ _Peer(str(roster["member"])),
+ ])
+ with _with_client(client):
+ resp = _client().get(f"/memories/people/{person_id}/conclusions")
+ assert resp.status_code == 404
+ assert client.aio.peer_calls == [], "a miss must not mint the peer either"
+
+
+def test_conclusions_disabled(monkeypatch: pytest.MonkeyPatch, roster: dict[str, int]) -> None:
+ monkeypatch.setenv("HONCHO_ENABLED", "false")
+ body = _client().get(f"/memories/people/{roster['member']}/conclusions").json()
+ assert body["status"] == "disabled" and body["items"] == [] and body["has_more"] is False
+
+
+def test_conclusions_read_failure_is_an_error_status(
+ roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ client = _Client([], fail=RuntimeError("down"))
+ with _with_client(client):
+ body = _client().get(f"/memories/people/{roster['member']}/conclusions").json()
+ assert body["status"] == "error" and body["items"] == []
+ audit = [r["details"] for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert audit[0]["op"] == "conclusions" and audit[0]["error_type"] == "RuntimeError"
+
+
[email protected]("query", ["page=0", "size=0", "size=101"])
+def test_conclusions_paging_is_bounded(query: str, roster: dict[str, int]) -> None:
+ resp = _client().get(f"/memories/people/{roster['member']}/conclusions?{query}")
+ assert resp.status_code == 422
+
+
+def test_a_malformed_conclusions_page_is_an_error_status(
+ roster: dict[str, int], audit_rows: list[dict[str, Any]]
+) -> None:
+ client = _Client([_Peer(str(roster["member"]), conclusions=[_Conclusion("a", _T1)])])
+
+ async def _bad_list(*_: Any, **__: Any) -> Any:
+ return _Page([_Conclusion("a", _T1)], "not-a-number") # type: ignore[arg-type]
+
+ client.aio._peers[0].conclusions.aio.list = _bad_list # type: ignore[method-assign]
+ with _with_client(client):
+ resp = _client().get(f"/memories/people/{roster['member']}/conclusions")
+ assert resp.status_code == 200 and resp.json()["status"] == "error"
+ audit = [r["details"] for r in audit_rows if r["event_type"] == "peer_memory"]
+ assert audit[-1]["outcome"] == "error" and audit[-1]["error_type"] == "ValueError"
diff --git a/packages/ui/src/components/memories/MemorySection.tsx b/packages/ui/src/components/memories/MemorySection.tsx
index ea524422..c92253bd 100644
--- a/packages/ui/src/components/memories/MemorySection.tsx
+++ b/packages/ui/src/components/memories/MemorySection.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import {
deleteAdvice,
deleteDecision,
@@ -9,6 +9,7 @@ import {
listDecisions,
listInitiatives,
listPeopleMemory,
+ listPersonConclusions,
updateAdvice,
updateDecision,
updateInitiative,
@@ -16,6 +17,7 @@ import {
type Decision,
type Initiative,
type PeopleMemory,
+ type PersonConclusion,
type PersonMemory,
} from "@/lib/api";
import { DOMAINS, STATUSES, EmptyState, formatDate } from "./shared";
@@ -632,7 +634,7 @@ function PeopleTab({
if (data.people.length === 0) return <EmptyState message={PEOPLE_EMPTY} />;
return (
- <div className="divide-y divide-line">
+ <div className="space-y-3">
{data.people.map((p) => (
<PersonMemoryRow key={p.person_id} item={p} />
))}
@@ -640,43 +642,149 @@ function PeopleTab({
);
}
+// Card lines past this many fold behind a toggle so one talkative card
+// doesn't push everyone else off the screen.
+const CARD_PREVIEW_LINES = 4;
+// Load the next page once the notes pane is scrolled within this many pixels
+// of its bottom.
+const NOTES_SCROLL_SLACK_PX = 48;
+
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}
+ <div className="rounded-lg border border-line bg-surface-overlay/30 p-4">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
+ <div className="flex items-center gap-2 min-w-0">
+ <span className="text-sm font-semibold text-fg truncate">{item.full_name}</span>
{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>
+ <span className="text-[10px] text-fg-subtle shrink-0">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.card.length > 0 && <PersonCard lines={item.card} />}
+ {item.recent.length > 0 && <PersonNotes item={item} />}
+ {nothingYet && <div className="mt-2 text-xs text-fg-subtle">Nothing learned yet.</div>}
+ </div>
+ );
+}
+
+function PersonCard({ lines }: { lines: string[] }) {
+ const [open, setOpen] = useState(false);
+ const hidden = lines.length - CARD_PREVIEW_LINES;
+ const shown = open || hidden <= 0 ? lines : lines.slice(0, CARD_PREVIEW_LINES);
+ return (
+ <div className="mt-3">
+ <div className="text-[10px] uppercase tracking-wide text-fg-subtle mb-1">Profile</div>
+ <ul className="space-y-0.5 text-xs text-fg-muted list-disc pl-4 marker:text-fg-subtle">
+ {shown.map((line, i) => (
+ <li key={i} className="break-words">{line}</li>
+ ))}
+ </ul>
+ {hidden > 0 && (
+ <button onClick={() => setOpen((o) => !o)} className="mt-1 text-xs text-fg-muted hover:text-fg">
+ {open ? "Show less" : `Show ${hidden} more`}
+ </button>
)}
- {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>
+ </div>
+ );
+}
+
+/** Newest first. Seeds from the overview's few; "Show all" then reads the
+ * full list page by page as the pane scrolls. */
+function PersonNotes({ item }: { item: PersonMemory }) {
+ const [notes, setNotes] = useState<PersonConclusion[]>(item.recent);
+ const [nextPage, setNextPage] = useState<number | null>(null); // null until "Show all"
+ const [hasMore, setHasMore] = useState(item.conclusion_count > item.recent.length);
+ const [loading, setLoading] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const loadingRef = useRef(false);
+ const paneRef = useRef<HTMLDivElement>(null);
+
+ const load = useCallback(
+ async (page: number) => {
+ if (loadingRef.current) return;
+ loadingRef.current = true;
+ setLoading(true);
+ setFailed(false);
+ try {
+ const res = await listPersonConclusions(item.person_id, page);
+ if (res.status !== "ok") throw new Error(res.status);
+ setNotes((prev) => {
+ // Page 1 already holds the seeded few; later pages append. New notes
+ // landing between reads shift the pages, so drop repeats.
+ const base = page === 1 ? [] : prev;
+ const seen = new Set(base.map((c) => `${c.created_at}|${c.content}`));
+ return [...base, ...res.items.filter((c) => !seen.has(`${c.created_at}|${c.content}`))];
+ });
+ setHasMore(res.has_more);
+ setNextPage(page + 1);
+ } catch {
+ setFailed(true);
+ } finally {
+ loadingRef.current = false;
+ setLoading(false);
+ }
+ },
+ [item.person_id],
+ );
+
+ const onScroll = () => {
+ const el = paneRef.current;
+ if (!el || nextPage === null || !hasMore || failed) return;
+ if (el.scrollHeight - el.scrollTop - el.clientHeight < NOTES_SCROLL_SLACK_PX) void load(nextPage);
+ };
+
+ // A page too short to scroll can never fire onScroll: keep filling until it can.
+ useEffect(() => {
+ const el = paneRef.current;
+ if (!el || nextPage === null || !hasMore || loading || failed) return;
+ if (el.scrollHeight <= el.clientHeight) void load(nextPage);
+ }, [notes, nextPage, hasMore, loading, failed, load]);
+
+ const remaining = Math.max(item.conclusion_count - notes.length, 0);
+ return (
+ <div className="mt-3">
+ <div className="text-[10px] uppercase tracking-wide text-fg-subtle mb-1">
+ Notes{nextPage !== null && ` · ${notes.length} of ${Math.max(item.conclusion_count, notes.length)}`}
+ </div>
+ <div
+ ref={paneRef}
+ onScroll={onScroll}
+ className="max-h-80 overflow-y-auto rounded-md border border-line/60 bg-surface-elevated/40"
+ >
+ <ul className="divide-y divide-line/60">
+ {notes.map((c, i) => (
+ <li key={`${c.created_at}-${i}`} className="grid grid-cols-[5.5rem_1fr] gap-3 px-3 py-2">
+ <span className="text-[11px] text-fg-subtle tabular-nums pt-0.5">{formatDate(c.created_at)}</span>
+ <span className="text-sm text-fg leading-relaxed break-words">{c.content}</span>
</li>
))}
</ul>
- )}
- {nothingYet && <div className="mt-1 text-xs text-fg-subtle">Nothing learned yet.</div>}
+ {(loading || failed || (hasMore && nextPage === null)) && (
+ <div className="px-3 py-2 text-xs text-fg-muted border-t border-line/60">
+ {loading ? (
+ "Loading…"
+ ) : failed ? (
+ <button onClick={() => void load(nextPage ?? 1)} className="hover:text-fg">
+ Couldn&apos;t load more — retry
+ </button>
+ ) : (
+ <button onClick={() => void load(1)} className="hover:text-fg">
+ Show all {item.conclusion_count} notes ({remaining} more)
+ </button>
+ )}
+ </div>
+ )}
+ </div>
</div>
);
}
diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.ts
index 01ee3170..366b906a 100644
--- a/packages/ui/src/lib/api.ts
+++ b/packages/ui/src/lib/api.ts
@@ -1003,6 +1003,30 @@ export function listPeopleMemory(recent = 5): Promise<PeopleMemory> {
return promise;
}
+export interface PersonConclusionsPage {
+ status: "ok" | "disabled" | "error";
+ person_id: number;
+ items: PersonConclusion[];
+ page: number;
+ size: number;
+ total: number | null;
+ has_more: boolean;
+}
+
+// Every conclusion about one person, newest first, one page at a time — the
+// People tab's "show all" pane. The overview above carries only the newest few.
+export async function listPersonConclusions(
+ personId: number,
+ page: number,
+ size = 50,
+): Promise<PersonConclusionsPage> {
+ const res = await fetch(
+ `${API_BASE}/memories/people/${personId}/conclusions?page=${page}&size=${size}`,
+ );
+ if (!res.ok) throw new Error("Failed to list person conclusions");
+ return res.json();
+}
+
export interface ScheduledAction {
id: number;
created_at: string;