AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(api): check session ownership on every per-session route (#197)
Rufuscf61609ff8a3
diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.pyindex 3e938794..a4144d39 100644--- a/packages/core/openexecutive/api/routes/chat.py+++ b/packages/core/openexecutive/api/routes/chat.py@@ -8,7 +8,7 @@ import reimport sqlite3import timeimport uuid-from typing import Any, NamedTuple+from typing import Any, Literal, NamedTuplefrom fastapi import APIRouter, File, Form, HTTPException, Request, UploadFilefrom fastapi.responses import StreamingResponse@@ -373,6 +373,96 @@ def _request_stop(client_turn_id: str, owner: str) -> str | None:return entry.turn_id+# Who started each chat this process has served. Lets a caller the roster+# can't resolve (a fresh install with no principal yet, or an allowlisted user+# who isn't on the roster) keep talking in a chat they started, without opening+# every ownerless session to every unresolved caller. In-memory like+# `_sessions`, so it does not survive a restart.+_session_starters: dict[str, frozenset[str]] = {}++SessionAccess = Literal["missing", "allowed", "forbidden", "orphaned"]+++def _caller_keys(request: Request, caller_person_id: int | None) -> frozenset[str]:+ """Every identity the caller holds: their Person id and their verified+ email (the UI proxy re-stamps `x-caller-email` from the signed-in session).++ Both are kept so a starter still matches after they become resolvable: a+ user who started a chat before being added to the roster (or while the+ lookup failed) carries the same email once they resolve to a Person. With+ neither — CLI or direct curl, no principal yet — it is local trust."""+ keys: set[str] = set()+ if caller_person_id is not None:+ keys.add(f"person:{caller_person_id}")+ email = (request.headers.get("x-caller-email") or "").strip().lower()+ if email:+ keys.add(f"email:{email}")+ return frozenset(keys or {"local"})+++def _is_session_starter(+ request: Request, session_id: str, caller_person_id: int | None+) -> bool:+ starter = _session_starters.get(session_id)+ return starter is not None and bool(starter & _caller_keys(request, caller_person_id))+++def _is_channel_namespaced(session_id: str) -> bool:+ """Ids with a `prefix:` namespace (`slack:dm:…`, `telegram:…`) belong to+ the channel adapters, which create their rows server-side. Web chats get a+ bare uuid."""+ return ":" in session_id+++def _session_access(+ request: Request, session_id: str, caller_person_id: int | None+) -> SessionAccess:+ """May this caller read, continue or delete ``session_id``?++ The session's owner or the principal may (`is_principal_or_self`, the same+ rule as feedback and followup; an ownerless legacy row is the principal's+ alone). The one other way in is having started it in this process: that is+ how an unresolved caller continues their own chat, whose row has no owner.++ - "missing": neither a stored row nor a live chat has that id.+ - "orphaned": a stored row with no owner that nobody in this process+ started — typically an unresolved caller's chat after a restart. Refused+ like "forbidden", but /chat starts a fresh chat instead of failing.+ """+ from openexecutive.memory.session_store import get_session_owner+ from openexecutive.people.store import is_principal_or_self++ exists, owner = get_session_owner(session_id)+ started_here = session_id in _session_starters+ if not exists and not started_here:+ return "missing"+ if exists and is_principal_or_self(caller_person_id, owner):+ return "allowed"+ if (not exists or owner is None) and _is_session_starter(+ request, session_id, caller_person_id+ ):+ return "allowed"+ if exists and owner is None and not started_here:+ return "orphaned"+ return "forbidden"+++def _is_current_session(session: Any) -> bool:+ """Whether ``session`` is still the live one for its id — False once it was+ deleted (or its id reclaimed after a reset) while a turn held it."""+ return _sessions.get(session.session_id) is session+++def forget_session(session_id: str) -> bool:+ """Drop a deleted session's in-process state; True if there was any.++ Without this, a later turn naming the deleted id would pick the cached+ `Session` (history and all) back up out of `_sessions`."""+ had_starter = _session_starters.pop(session_id, None) is not None+ had_session = _sessions.pop(session_id, None) is not None+ return had_starter or had_session++def _get_or_create_session(session_id: str | None, request: Request) -> Any:from openexecutive.memory.session_store import load_messagesfrom openexecutive.onboarding.profile_builder import load_or_create_profile@@ -574,6 +664,48 @@ async def _run_chat_turn(# by signed-in user); see its docstring for the precedence rule that# protects against cross-identity leakage.caller_person_id = _resolve_caller_person_id(request)+ # A client-supplied id must be the caller's own chat; any other id the+ # turn can't use is swapped for a fresh chat before the stop switch arms.+ requested_id = _clean_session_id(session_id)+ access: SessionAccess = "missing"+ if requested_id is not None:+ access = _session_access(request, requested_id, caller_person_id)+ if access in ("forbidden", "orphaned"):+ # Someone else's chat, or an ownerless one nobody here can vouch+ # for (its starter was lost to a restart). Continue in a fresh+ # chat: that neither fails every send nor answers differently for+ # "exists but not yours" than for an unknown namespaced id, so the+ # guessable ones (`slack:dm:<user id>`) can't be probed for which+ # chats exist. (A bare web id is a uuid4, so not guessable.)+ logger.warning("chat.session_refused access=%s session_id=%s", access, requested_id)+ requested_id, access = None, "missing"+ elif access == "missing":+ # No stored row and no live starter, so any cached Session under+ # this id is stale — its row was removed by a fixture reset or a+ # client-slot switch, neither of which clears `_sessions`. Never+ # hand that transcript to whoever names the id next.+ _sessions.pop(requested_id, None)+ if access == "missing" and requested_id and _is_channel_namespaced(requested_id):+ # A web caller minting an adapter's id would squat it: the+ # adapter's INSERT OR IGNORE keeps the first owner, so whoever+ # claimed `slack:dm:<someone>` first would own that person's DM+ # history. Start a fresh chat instead.+ logger.warning("chat.session_id_reserved session_id=%s", requested_id)+ requested_id = None+ if access == "missing" and requested_id:+ # Claiming an unused id. Any messages already stored under it are+ # orphans (a delete that raced a streaming turn, a reset mid-turn,+ # or rows left before this check existed): clear them so this+ # caller neither loads them as history nor becomes their owner.+ from openexecutive.memory.session_store import delete_session++ delete_session(requested_id)+ # Only the chat's starter binds an ownerless row to themselves. Anyone else+ # allowed in (the principal) must not take it over just by continuing it.+ bind_owner = requested_id is None or (+ requested_id not in _session_starters+ or _is_session_starter(request, requested_id, caller_person_id)+ )client_turn_id = _clean_client_turn_id(client_turn_id)stop_event: asyncio.Event | None = Noneif client_turn_id:@@ -596,10 +728,14 @@ async def _run_chat_turn(# now permanent-ish: the registry refuses new turns at its cap rather than# evicting live ones, so enough of them would disable Stop for everybody.try:- session = _get_or_create_session(session_id, request)+ session = _get_or_create_session(requested_id, request)except BaseException:_release_stop(client_turn_id, turn_id)raise+ if access == "missing":+ _session_starters.setdefault(+ session.session_id, _caller_keys(request, caller_person_id)+ )is_first_turn = len(session.conversation_history) == 0logger.info(@@ -641,7 +777,7 @@ async def _run_chat_turn(session.session_id,title,session.created_at.isoformat(),- caller_person_id=caller_person_id,+ caller_person_id=caller_person_id if bind_owner else None,)except Exception: # pragma: no cover - DB write should not block the turnlogger.exception("chat.session_persist_failed turn_id=%s", turn_id)@@ -882,6 +1018,14 @@ async def _run_chat_turn(# the response uniformly. Don't duplicate it here.if not full_response:return+ if not _is_current_session(session):+ # Deleted (or reset) while this turn streamed. Writing now+ # would leave messages under an id with no session row,+ # which the next caller to claim that id would inherit.+ logger.info(+ "chat.persist_skipped_deleted session_id=%s", session.session_id+ )+ returnif not is_first_turn:update_session_timestamp(session.session_id)save_message(diff --git a/packages/core/openexecutive/api/routes/sessions.py b/packages/core/openexecutive/api/routes/sessions.pyindex 8c28dfdc..f4946129 100644--- a/packages/core/openexecutive/api/routes/sessions.py+++ b/packages/core/openexecutive/api/routes/sessions.py@@ -8,16 +8,18 @@ from pydantic import BaseModel, Fieldfrom openexecutive.api.models import SessionSummaryfrom openexecutive.api.routes import chat as chat_route-from openexecutive.api.routes.chat import _resolve_caller_person_id+from openexecutive.api.routes.chat import (+ _resolve_caller_person_id,+ _session_access,+ forget_session,+)from openexecutive.memory.session_store import (delete_session,get_session_metadata,- get_session_owner,list_sessions,load_messages,set_message_feedback,)-from openexecutive.people.store import is_principal_or_selfrouter = APIRouter()@@ -34,8 +36,22 @@ def get_sessions(request: Request) -> list[SessionSummary]:return [SessionSummary(**s) for s in list_sessions(caller_person_id)]+def _require_session_access(request: Request, session_id: str) -> int | None:+ """404 unless the caller may use this session; returns the caller's id.++ Session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`), so+ every per-session route checks ownership rather than trusting the id. An+ unknown session and someone else's answer the same, so the routes can't be+ used to probe which chats exist (as `/chat/stop` does for turn ids)."""+ caller = _resolve_caller_person_id(request)+ if _session_access(request, session_id, caller) != "allowed":+ raise HTTPException(status_code=404, detail="Session not found")+ return caller++@router.get("/sessions/{session_id}", response_model=SessionSummary)-def get_session(session_id: str) -> SessionSummary:+def get_session(session_id: str, request: Request) -> SessionSummary:+ _require_session_access(request, session_id)meta = get_session_metadata(session_id)if meta is None:raise HTTPException(status_code=404, detail="Session not found")@@ -43,7 +59,8 @@ def get_session(session_id: str) -> SessionSummary:@router.get("/sessions/{session_id}/messages")-def get_session_messages(session_id: str) -> list[dict]:+def get_session_messages(session_id: str, request: Request) -> list[dict]:+ _require_session_access(request, session_id)meta = get_session_metadata(session_id)if meta is None:raise HTTPException(status_code=404, detail="Session not found")@@ -51,8 +68,12 @@ def get_session_messages(session_id: str) -> list[dict]:@router.delete("/sessions/{session_id}", status_code=status.HTTP_204_NO_CONTENT)-def delete_session_route(session_id: str) -> Response:- if not delete_session(session_id):+def delete_session_route(session_id: str, request: Request) -> Response:+ _require_session_access(request, session_id)+ deleted = delete_session(session_id)+ # A chat whose row never persisted still counts: dropping its live state+ # is the delete the caller asked for.+ if not forget_session(session_id) and not deleted:raise HTTPException(status_code=404, detail="Session not found")return Response(status_code=status.HTTP_204_NO_CONTENT)@@ -76,12 +97,7 @@ def post_message_feedback(Only the session's own caller, or the principal, may rate it: feedbackfeeds per-person learning, so a rating left on someone else's sessionwould be read as that person's reaction."""- exists, owner = get_session_owner(session_id)- if not exists:- raise HTTPException(status_code=404, detail="Session not found")- caller = _resolve_caller_person_id(request)- if not is_principal_or_self(caller, owner):- raise HTTPException(status_code=403, detail="Not your session")+ caller = _require_session_access(request, session_id)if not set_message_feedback(session_id, message_id, body.feedback, body.note, by_person_id=caller):@@ -133,11 +149,7 @@ async def get_followup_suggestion(session_id: str, request: Request) -> dict[strown caller, or the principal, may ask: the suggestion paraphrases theconversation."""- exists, owner = get_session_owner(session_id)- if not exists:- raise HTTPException(status_code=404, detail="Session not found")- if not is_principal_or_self(_resolve_caller_person_id(request), owner):- raise HTTPException(status_code=403, detail="Not your session")+ _require_session_access(request, session_id)messages = load_messages(session_id)last = messages[-1] if messages else Nonediff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex 3c527162..c604eba7 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -1529,6 +1529,37 @@ attunement:`Session.caller_person_id = person_id` every turn for tool handlers.Email / Google Chat don't persist chat_messages (known gap) but theopen-loop hook lives in the Executive, so they still open/close loops.+ session_access: |+ Every per-session HTTP route (GET /sessions/{id}, GET /sessions/{id}/messages,+ DELETE /sessions/{id}, POST /chat with a session_id, and feedback/followup)+ is limited to the session's owner or the principal (`is_principal_or_self`;+ a NULL-owner legacy row is the principal's alone). The sessions routes answer+ 404 for anyone else, identical to an unknown id, so they are no oracle for+ which chats exist; POST /chat instead runs the turn in a fresh chat. Session ids are guessable+ (`slack:dm:<user id>`, `telegram:<chat id>`), so the id alone is no proof.+ `chat._session_access` also admits whoever started the chat in this process+ (`_session_starters` holds the starter's `_caller_keys`: Person id and/or+ verified email, else "local"), which is how an unresolved caller (fresh+ install, allowlisted but unrostered) continues their own ownerless chat.+ Matching on email too means the starter keeps access once they resolve to a+ Person, and that turn late-binds the row to them. Only the starter binds an+ ownerless row: the principal continuing it does not take it over. The record+ is in-memory; after a restart an ownerless row nobody here started is+ "orphaned": reads get 404 and POST /chat continues in a fresh chat instead+ of failing. POST /chat also ignores an unknown namespaced id (contains ':')+ rather than letting a web caller squat an id a channel adapter will later+ create (INSERT OR IGNORE keeps the first owner). A "missing" id evicts any+ cached Session under it: fixture reset and client-slot switching remove+ rows without clearing `_sessions`, and the stale transcript must not be+ handed to the next claimant. A turn whose Session was deleted mid-stream+ (no longer the cached object) skips persisting, so no orphan messages are+ left under the deleted id. Claiming an unused bare id also deletes any+ messages already stored under it (orphans from a delete/reset race or from+ before this check), so they are never loaded as the claimant's history.+ DELETE also evicts the in-memory Session so the id cannot resume its history.+ Known gap, not covered: GET /audit/sessions/{id} is not owner-scoped.+ (GET /debug/last-turn, which leaked the last turn to any caller, was+ removed in #200.)feedback: |`chat_messages.feedback` up|down (+ `feedback_note`) viaPOST /sessions/{id}/messages/{message_id}/feedback — session's own callerdiff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex f0112219..78b5ca72 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`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` 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. |",+ "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. A `session_id` in the body must be a chat the caller may use (the same ownership rule as `sessions`). If it isn't, the turn runs in a fresh chat instead, so nothing is written into someone else's session and the reply looks the same as for an unknown id. An unknown namespaced id (`slack:…`, `telegram:…` and so on) is ignored and a fresh chat is started, because those ids belong to the channel adapters and claiming one first would make the caller its owner. The client mints a `client_turn_id` and sends it with the turn; `POST /chat/stop` takes that id and halts the turn mid-flight, so the button is live from the moment Send is pressed rather than only once the first SSE byte arrives. A stopped turn emits a `stopped` event and then the usual `done` over the same still-open stream — never an `error` — and whatever streamed so far is persisted and flagged. The endpoint returns 404 both for an unknown id and for another caller's turn, so it cannot be used to probe which turns are live. An optional `memory_text` (1–2000 chars) is what peer memory records as the caller's words instead of `message` — the briefing handoffs send it because their seed quotes the Executive's own card; `POST /chat/upload` derives it from the typed text and filenames. Since it never reaches the transcript, the `chat_turn` audit row keeps it beside `message`. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}`, `GET /sessions/{id}/messages`, `DELETE /sessions/{id}`, `POST /sessions/{id}/messages/{message_id}/feedback`, `GET /sessions/{id}/followup` | List, read and delete saved chat sessions (assistant messages carry their row `id` and any `feedback`). The list is scoped to the caller. Every per-session route checks ownership, because session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`): only the session's owner or the principal gets through, and a legacy row with no owner is the principal's alone. Anyone else gets the same 404 as for an unknown id, so the routes can't be used to find out which chats exist. The one other way in is having started the chat in this process (matched by Person id or verified email, so it survives the caller being added to the roster), which is how a caller the roster can't resolve keeps using their own chat. That record is in memory, so after a restart such an ownerless chat is refused for reads. The principal can continue someone else's ownerless chat without becoming its owner. Deleting a session also drops its in-memory copy, so a later turn naming that id starts fresh. The feedback route records 👍/👎 (`{\"feedback\": \"up\"|\"down\"|null}`) on one assistant reply; only the session's own caller or the principal may rate it. The rater is stored (`feedback_by_person_id`), and a 👎 on a reply to the rater's own message triggers a working-style pass for them (paced; see attunement). The chat stream's `done` event carries `message_id` for the persisted reply. The followup route returns `{\"suggestion\": string|null}` — one suggested next user message, written by the utility-fast model from the last few turns, that the chat composer shows as its greyed placeholder (Tab / → or the inline chip fills it in without sending). It is null unless the session ends on a persisted assistant reply, and null (uncached) when the model fails. Same ownership check as feedback; successful suggestions are cached in-process per (session, reply id). |\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`, `GET\\|DELETE /workflows/custom/{name}/targets`, `POST /workflows/runs/{run_id}/decision`, `GET /workflows/tools/search?q=`, `GET /workflows/tools/describe?names=` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. Custom definitions come back with a server-managed `owner_person_id` (the creator — the web caller on `POST`, set on insert only; a client-sent value is ignored), who is asked to approve a workflow's first write to a new target. `GET /workflows/custom/{name}/targets` lists the targets its tool steps may write to without asking and `DELETE …/targets?value=` forgets one. `POST /workflows/runs/{run_id}/decision` with `{decision: \"approve\"|\"reject\"}` answers a run awaiting a yes/no sign-off from the web app — 403 unless the caller is the person it waits on or the principal, 409 if it isn't awaiting or needs a written reply — through the same `apply_resolution` a chat reply uses. Custom create/update also rejects (422) any action-step tool that does not resolve, and so does `POST /workflows/custom/{name}/activate` when turning a workflow **on** — that click is the approval for a tool workflow chat saved switched off (turning off is never checked). Turning on a workflow with action steps requires the body `{is_active: true, definition}` carrying the definition the user reviewed; if the stored one differs (ignoring `is_active` and timestamps) it returns 409, and the switch itself is a compare-and-set on the validated revision (`dynamic_store.activate_if_unchanged`, keyed on `updated_at`), so a save that lands while the tool check awaits the gateway — even from another process — is a 409 too, so only what was shown gets switched on. `GET /workflows/custom` lists inactive definitions too; `GET /workflows/{name}` 404s for them. The two `tools` endpoints return `{tools: [{name, description, read_only, source}]}` for the advanced editor's tool picker and the review card; `read_only` is true only when the name says it reads (a label, not a control). The run stream adds a `progress` event (`step_id`, `summary`) while an action step uses tools. Each catalog entry (`WorkflowMeta`) carries `is_custom` 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-24T00:00:00Z"}diff --git a/packages/core/openexecutive/memory/session_store.py b/packages/core/openexecutive/memory/session_store.pyindex 917c66a2..8f51d658 100644--- a/packages/core/openexecutive/memory/session_store.py+++ b/packages/core/openexecutive/memory/session_store.py@@ -152,7 +152,8 @@ def list_sessions(Legacy rows with caller_person_id IS NULL (created before this columnexisted) are excluded — the comparison `NULL = ?` never matches in- SQLite. They remain reachable by direct session_id URL.+ SQLite. Only the principal can still open them by id (see+ `api.routes.chat._session_access`)."""if not db_path.exists():return []diff --git a/packages/core/tests/unit/test_open_loops.py b/packages/core/tests/unit/test_open_loops.pyindex e5faed65..be61253d 100644--- a/packages/core/tests/unit/test_open_loops.py+++ b/packages/core/tests/unit/test_open_loops.py@@ -456,7 +456,9 @@ def test_feedback_route_authorization(monkeypatch: pytest.MonkeyPatch) -> None:from openexecutive.api.routes import sessions as route- monkeypatch.setattr(route, "get_session_owner", lambda sid: (True, 5))+ monkeypatch.setattr(+ "openexecutive.memory.session_store.get_session_owner", lambda sid: (True, 5)+ )monkeypatch.setattr(route, "set_message_feedback", lambda *a, **k: True)principal = SimpleNamespace(is_principal=True, archived=False)teammate = SimpleNamespace(is_principal=False, archived=False)@@ -473,8 +475,9 @@ def test_feedback_route_authorization(monkeypatch: pytest.MonkeyPatch) -> None:assert call(5) == 204 # the session's own callerassert call(1) == 204 # the principal- assert call(7) == 403 # someone else- assert call(None) == 403 # unrostered+ # Refused like an unknown session, so the route can't probe which exist.+ assert call(7) == 404 # someone else+ assert call(None) == 404 # unrostereddef test_close_open_loop_chip_only_when_closed() -> None:diff --git a/packages/core/tests/unit/test_session_followup.py b/packages/core/tests/unit/test_session_followup.pyindex c7eaf739..dc8bc6d8 100644--- a/packages/core/tests/unit/test_session_followup.py+++ b/packages/core/tests/unit/test_session_followup.py@@ -4,7 +4,7 @@ Covers:- A conversation ending on a persisted reply returns the model's suggestion.- Model failure / bad output returns ``null`` with a 200, and is not cached.- A conversation that does not end on a reply skips the model entirely.-- Unknown session → 404; someone else's session → 403.+- Unknown session and someone else's session → 404 alike.- Repeat calls for the same reply hit the cache.- The fast-model helper parses fenced JSON and rejects runaway answers."""@@ -46,9 +46,9 @@ def _patch_session(exists: bool = True,allowed: bool = True,) -> None:- monkeypatch.setattr(sessions_route, "get_session_owner", lambda _sid: (exists, 1))+ access = "missing" if not exists else ("allowed" if allowed else "forbidden")monkeypatch.setattr(sessions_route, "_resolve_caller_person_id", lambda _req: 1)- monkeypatch.setattr(sessions_route, "is_principal_or_self", lambda _c, _o: allowed)+ monkeypatch.setattr(sessions_route, "_session_access", lambda _req, _sid, _c: access)monkeypatch.setattr(sessions_route, "load_messages", lambda _sid: list(messages))@@ -124,14 +124,15 @@ def test_unknown_session_is_404(monkeypatch: pytest.MonkeyPatch) -> None:assert calls["n"] == 0-def test_other_callers_session_is_403(monkeypatch: pytest.MonkeyPatch) -> None:+def test_other_callers_session_looks_unknown(monkeypatch: pytest.MonkeyPatch) -> None:+ """404, like an unknown id, so the route can't probe which chats exist."""_patch_session(monkeypatch, _CONVO, allowed=False)calls = _patch_llm(monkeypatch, "x")with TestClient(_make_app()) as client:res = client.get("/sessions/s1/followup")- assert res.status_code == 403+ assert res.status_code == 404assert calls["n"] == 0diff --git a/packages/core/tests/unit/test_session_ownership.py b/packages/core/tests/unit/test_session_ownership.pynew file mode 100644index 00000000..72dcbe30--- /dev/null+++ b/packages/core/tests/unit/test_session_ownership.py@@ -0,0 +1,380 @@+"""Per-session routes must check who owns the session.++Session ids are guessable (`slack:dm:<user id>`, `telegram:<chat id>`), so+reading, deleting or continuing a chat by id must be limited to its owner or+the principal — the same rule the feedback and followup routes already use.+"""+from __future__ import annotations++import sqlite3+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from openexecutive.api.routes import chat as chat_route+from openexecutive.api.routes import sessions as sessions_route+from openexecutive.memory import episodic, session_store+from openexecutive.memory.company_profile import CompanyProfile+from openexecutive.people import store as people_store++ALEX = {"x-caller-email": "[email protected]"} # principal+SABIN = {"x-caller-email": "[email protected]"}+RIYA = {"x-caller-email": "[email protected]"}+STRANGER = {"x-caller-email": "[email protected]"} # signed in, not rostered++[email protected](autouse=True)+def _reset_route_state() -> None:+ chat_route._sessions.clear()+ chat_route._session_starters.clear()+++def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ monkeypatch.chdir(tmp_path)+ db_path = Path("./episodic_memory.db").resolve()+ monkeypatch.setattr(episodic, "DB_PATH", db_path)+ monkeypatch.setattr(session_store, "DB_PATH", db_path)+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")+ episodic.initialize_db(db_path)+ people_store.initialize_db()+ return db_path+++def people(db: Path) -> dict[str, int]:+ return {+ "alex": people_store.upsert_person(+ full_name="Alex", is_principal=True, email="[email protected]"+ ),+ "sabin": people_store.upsert_person(full_name="Sabin", email="[email protected]"),+ "riya": people_store.upsert_person(full_name="Riya", email="[email protected]"),+ }+++def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:+ """Both routers, with the Executive and its context fetches stubbed out."""+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")+ from openexecutive.knowledge import retriever+ from openexecutive.onboarding import profile_builder+ from openexecutive.orchestrator import executive as exec_mod+ from openexecutive.utils import session_title++ monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: CompanyProfile())+ monkeypatch.setattr(retriever, "retrieve", lambda *_a, **_k: "")++ async def _no_title(*_a: Any, **_k: Any) -> None:+ return None++ monkeypatch.setattr(session_title, "generate_session_title", _no_title)++ class _StubExecutive:+ _THINKING = exec_mod.Executive._THINKING++ def __init__(self, **_kwargs: Any) -> None:+ pass++ async def stream_chat(self, **_kwargs: Any) -> AsyncIterator[str]:+ yield "ok"++ async def stream_chat_with_committee(self, **_kwargs: Any) -> AsyncIterator[str]:+ yield "ok"++ monkeypatch.setattr(exec_mod, "Executive", _StubExecutive)+ app = FastAPI()+ app.include_router(chat_route.router)+ app.include_router(sessions_route.router)+ return TestClient(app)+++def _chat(client: TestClient, headers: dict[str, str], session_id: str | None = None) -> int:+ body: dict[str, Any] = {"message": "hi"}+ if session_id is not None:+ body["session_id"] = session_id+ resp = client.post("/chat", json=body, headers=headers)+ _ = resp.text # drain the SSE body so the turn finishes+ return resp.status_code+++def _session_ids(db_path: Path) -> list[str]:+ with sqlite3.connect(db_path) as conn:+ return [r[0] for r in conn.execute("SELECT session_id FROM sessions ORDER BY rowid")]+++def _owner(db_path: Path, session_id: str) -> int | None:+ with sqlite3.connect(db_path) as conn:+ row = conn.execute(+ "SELECT caller_person_id FROM sessions WHERE session_id = ?", (session_id,)+ ).fetchone()+ return row[0]+++def _message_count(db_path: Path, session_id: str) -> int:+ with sqlite3.connect(db_path) as conn:+ row = conn.execute(+ "SELECT COUNT(*) FROM chat_messages WHERE session_id = ?", (session_id,)+ ).fetchone()+ return int(row[0])+++def _seed(session_id: str, owner: int | None) -> None:+ session_store.create_session(session_id, "t", "2026-01-01T00:00:00", caller_person_id=owner)+++# --- read / delete ---------------------------------------------------------++[email protected]("path", ["/sessions/{id}", "/sessions/{id}/messages"])+def test_reads_are_limited_to_owner_and_principal(+ client: TestClient, people: dict[str, int], path: str+) -> None:+ _seed("slack:dm:USABIN", people["sabin"])+ url = path.format(id="slack:dm:USABIN")++ assert client.get(url, headers=SABIN).status_code == 200+ assert client.get(url, headers=ALEX).status_code == 200+ assert client.get(url, headers=RIYA).status_code == 404+ assert client.get(url, headers=STRANGER).status_code == 404+++def test_someone_elses_session_looks_exactly_like_an_unknown_one(+ client: TestClient, people: dict[str, int]+) -> None:+ """Ids are guessable, so "exists but not yours" must not be told apart+ from "no such session" — or the routes would reveal who has chatted."""+ _seed("slack:dm:USABIN", people["sabin"])++ for sid in ("slack:dm:USABIN", "slack:dm:UNOBODY"):+ for resp in (+ client.get(f"/sessions/{sid}", headers=RIYA),+ client.get(f"/sessions/{sid}/messages", headers=RIYA),+ client.get(f"/sessions/{sid}/followup", headers=RIYA),+ client.delete(f"/sessions/{sid}", headers=RIYA),+ ):+ assert (resp.status_code, resp.json()) == (404, {"detail": "Session not found"})+++def test_legacy_ownerless_session_is_the_principals_alone(+ client: TestClient, people: dict[str, int]+) -> None:+ _seed("legacy", None)++ assert client.get("/sessions/legacy/messages", headers=ALEX).status_code == 200+ assert client.get("/sessions/legacy/messages", headers=SABIN).status_code == 404+ assert client.get("/sessions/legacy/messages", headers=STRANGER).status_code == 404+++def test_delete_refuses_someone_elses_session_and_keeps_it(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ _seed("sabin-chat", people["sabin"])++ assert client.delete("/sessions/sabin-chat", headers=RIYA).status_code == 404+ assert _session_ids(db) == ["sabin-chat"]++ assert client.delete("/sessions/sabin-chat", headers=SABIN).status_code == 204+ assert _session_ids(db) == []+++def test_delete_evicts_the_in_memory_session(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ assert _chat(client, SABIN) == 200+ (sid,) = _session_ids(db)+ assert sid in chat_route._sessions++ assert client.delete(f"/sessions/{sid}", headers=SABIN).status_code == 204+ assert sid not in chat_route._sessions+ assert sid not in chat_route._session_starters+++# --- continuing a chat -----------------------------------------------------+++def test_chat_never_writes_into_someone_elses_session(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """Naming another person's session starts a fresh chat instead: nothing+ lands in theirs, and the response is the same as for an unknown id."""+ _seed("sabin-chat", people["sabin"])++ assert _chat(client, RIYA, "sabin-chat") == 200+ assert _chat(client, STRANGER, "sabin-chat") == 200+ assert _message_count(db, "sabin-chat") == 0+ assert len(_session_ids(db)) == 3 # sabin-chat + one fresh chat each++ assert _chat(client, SABIN, "sabin-chat") == 200+ assert _chat(client, ALEX, "sabin-chat") == 200+ assert _message_count(db, "sabin-chat") == 4+++def test_unresolved_caller_can_continue_only_their_own_new_chat(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """An allowlisted user who isn't on the roster has no Person id, so their+ chat's row has no owner. They started it in this process, so they may keep+ talking in it; another unresolved user may not."""+ assert _chat(client, STRANGER) == 200+ (sid,) = _session_ids(db)++ assert _chat(client, STRANGER, sid) == 200+ assert client.get(f"/sessions/{sid}/messages", headers=STRANGER).status_code == 200+ assert _chat(client, {"x-caller-email": "[email protected]"}, sid) == 200+ assert _chat(client, SABIN, sid) == 200+ assert _message_count(db, sid) == 4 # only the starter's two turns+ assert client.get(f"/sessions/{sid}/messages", headers=SABIN).status_code == 404+++def test_stale_cached_session_is_not_handed_to_the_next_claimant(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """A fixture reset or client-slot switch wipes the rows but not the+ in-memory cache. Whoever names the id next must get an empty chat, not the+ cached transcript."""+ assert _chat(client, SABIN) == 200+ (sid,) = _session_ids(db)+ stale = chat_route._sessions[sid]+ stale.conversation_history = [{"role": "user", "content": "SABIN'S SECRET"}]+ chat_route._session_starters.clear() # e.g. a resumed chat: no starter here+ session_store.delete_session(sid) # what reset_all_state does to the row++ assert _chat(client, RIYA, sid) == 200+ assert chat_route._sessions[sid] is not stale+ assert "SABIN'S SECRET" not in repr(chat_route._sessions[sid].conversation_history)+ assert _message_count(db, sid) == 2 # Riya's turn only+++def test_turn_finishing_after_its_session_was_deleted_is_not_saved(+ client: TestClient, db: Path, people: dict[str, int], monkeypatch: pytest.MonkeyPatch+) -> None:+ """Deleting a chat while a reply streams must not leave that reply's+ messages behind under the deleted id."""+ from openexecutive.orchestrator import executive as exec_mod++ class _DeletesMidStream:+ _THINKING = exec_mod.Executive._THINKING++ def __init__(self, **_kwargs: Any) -> None:+ pass++ async def stream_chat(self, **_kwargs: Any) -> AsyncIterator[str]:+ (sid,) = _session_ids(db)+ session_store.delete_session(sid)+ chat_route.forget_session(sid)+ yield "ok"++ monkeypatch.setattr(exec_mod, "Executive", _DeletesMidStream)++ assert _chat(client, SABIN) == 200+ assert _session_ids(db) == []+ with sqlite3.connect(db) as conn:+ assert conn.execute("SELECT COUNT(*) FROM chat_messages").fetchone()[0] == 0+++def test_fresh_install_without_a_principal_keeps_working(+ client: TestClient, db: Path+) -> None:+ """No roster at all: every caller is unresolved, and a multi-turn chat+ must still work for the person who started it."""+ headers = {"x-caller-email": "[email protected]"}+ assert _chat(client, headers) == 200+ (sid,) = _session_ids(db)+ assert _chat(client, headers, sid) == 200+++def test_channel_namespaced_id_cannot_be_squatted_from_the_web(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """Claiming `slack:dm:<someone>` before their first DM would make the+ caller the owner of that DM's history. The id is ignored instead."""+ assert _chat(client, RIYA, "slack:dm:UVICTIM") == 200++ ids = _session_ids(db)+ assert "slack:dm:UVICTIM" not in ids+ assert len(ids) == 1+++def test_web_client_may_still_name_a_new_plain_id(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ assert _chat(client, SABIN, "my-own-id") == 200+ assert _session_ids(db) == ["my-own-id"]+++def test_starter_keeps_their_chat_after_joining_the_roster(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """Started while unrostered, then added to the roster: the same verified+ email still matches, and the row is bound to their new Person."""+ newhire = {"x-caller-email": "[email protected]"}+ assert _chat(client, newhire) == 200+ (sid,) = _session_ids(db)+ assert _owner(db, sid) is None++ newhire_id = people_store.upsert_person(full_name="New", email="[email protected]")++ assert _chat(client, newhire, sid) == 200+ assert _owner(db, sid) == newhire_id+++def test_principal_continuing_a_chat_does_not_take_it_over(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ assert _chat(client, STRANGER) == 200+ (sid,) = _session_ids(db)++ assert _chat(client, ALEX, sid) == 200+ assert _owner(db, sid) is None+ assert _chat(client, STRANGER, sid) == 200+++def test_orphaned_chat_after_restart_continues_in_a_fresh_one(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """The starter record is in-memory. After a restart an unresolved caller's+ ownerless chat can't be vouched for: reads are refused, and /chat starts a+ new chat instead of failing every send."""+ assert _chat(client, STRANGER) == 200+ (sid,) = _session_ids(db)+ chat_route._sessions.clear()+ chat_route._session_starters.clear() # simulate a restart++ assert client.get(f"/sessions/{sid}/messages", headers=STRANGER).status_code == 404+ assert _chat(client, STRANGER, sid) == 200+ ids = _session_ids(db)+ assert len(ids) == 2 and ids[0] == sid+++def test_delete_of_a_never_persisted_chat_reports_success(+ client: TestClient, people: dict[str, int]+) -> None:+ """A chat whose row failed to persist lives only in memory; deleting it+ drops that state and is a success, not a 404."""+ chat_route._session_starters["live-only"] = frozenset(+ {f"person:{people['sabin']}", "email:[email protected]"}+ )+ chat_route._sessions["live-only"] = object()++ assert client.delete("/sessions/live-only", headers=SABIN).status_code == 204+ assert "live-only" not in chat_route._sessions+++def test_orphaned_messages_are_not_inherited_by_whoever_claims_the_id(+ client: TestClient, db: Path, people: dict[str, int]+) -> None:+ """Messages left under an id with no session row (a delete racing a+ stream, a reset mid-turn) must not become the next claimant's history."""+ session_store.save_message("gone-chat", "user", "SABIN'S SECRET")++ assert _chat(client, RIYA, "gone-chat") == 200++ assert "SABIN'S SECRET" not in repr(chat_route._sessions["gone-chat"].conversation_history)+ resp = client.get("/sessions/gone-chat/messages", headers=RIYA)+ assert resp.status_code == 200+ assert "SABIN'S SECRET" not in resp.text+diff --git a/packages/core/tests/unit/test_sessions_route_delete.py b/packages/core/tests/unit/test_sessions_route_delete.pyindex a685aab5..e2829d77 100644--- a/packages/core/tests/unit/test_sessions_route_delete.py+++ b/packages/core/tests/unit/test_sessions_route_delete.py@@ -9,6 +9,7 @@ from fastapi.testclient import TestClientfrom openexecutive.api.routes import sessions as sessions_routefrom openexecutive.memory import episodic, session_store+from openexecutive.people import store as people_store@pytest.fixture()@@ -17,7 +18,9 @@ def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:db_path = Path("./episodic_memory.db").resolve()monkeypatch.setattr(episodic, "DB_PATH", db_path)monkeypatch.setattr(session_store, "DB_PATH", db_path)+ monkeypatch.setattr(people_store, "DB_PATH", tmp_path / "people.db")episodic.initialize_db(db_path)+ people_store.initialize_db()app = FastAPI()app.include_router(sessions_route.router)@@ -25,7 +28,11 @@ def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:def test_delete_session_success(client: TestClient) -> None:- session_store.create_session("s1", "title", "2024-01-01T00:00:00")+ # No caller header resolves to the principal, who owns the session.+ principal_id = people_store.upsert_person(full_name="Alex", is_principal=True)+ session_store.create_session(+ "s1", "title", "2024-01-01T00:00:00", caller_person_id=principal_id+ )session_store.save_message("s1", "user", "hi")resp = client.delete("/sessions/s1")diff --git a/packages/core/tests/unit/test_style.py b/packages/core/tests/unit/test_style.pyindex 92a068ae..85ca18db 100644--- a/packages/core/tests/unit/test_style.py+++ b/packages/core/tests/unit/test_style.py@@ -472,7 +472,7 @@ def test_thumbs_down_records_the_rater_and_triggers_a_pass(from openexecutive.api.routes import sessions as route_, aid = _turn(team.sara, "what's the runway")- monkeypatch.setattr(route, "get_session_owner", lambda sid: (True, team.sara))+ monkeypatch.setattr(route, "_session_access", lambda req, sid, caller: "allowed")monkeypatch.setattr(route, "_resolve_caller_person_id", lambda req: team.sara)real_set = session_store.set_message_feedbackmonkeypatch.setattr(route, "set_message_feedback",