Skip to content

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

fix(clients): stop derived caches leaking across companies

Eric Oliveira2cafb1ff3ebf
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index eb737e13..d74d6973 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2842,6 +2842,37 @@ clients:
blank slot (no state.db yet) factory-wipes the per-client tables and
re-seeds defaults (departments, onboarding templates, principal briefs,
cadences) so the new client's Today works without a process restart.
+ Wipe lists must cover the DERIVED CACHES, not just authored state.
+ briefing_narrative and person_insights were wiped by NO path, and because
+ /today serves the cached narrative unconditionally (regenerating only in a
+ BackgroundTask), whichever path swapped the company rendered the OUTGOING
+ one's narrative under the incoming one. Do not assume person_insights'
+ input_hash self-guards: that hash covers role/status/counters/UTC-day but
+ NOT person or company identity, and the key is a reused autoincrement
+ person_id — so an outgoing principal and a freshly seeded incoming
+ principal hash identically. Ordinary steady state, not a collision.
+ THREE paths swap live company state and each kept its own hand-written
+ table list, which is why fixing one left the leak live in the other two.
+ They now all consume `cli.fixture_loader.PER_CLIENT_CACHE_TABLES`:
+ `clients.slots._BLANK_WIPE_TABLES` (switch into a blank/seed slot),
+ `reset_all_state` (factory reset), and `_seed_episodic_memory` (fixture
+ load — the worst surface, since a demo is what gets screen-shared).
+ Client→client switching into a slot that HAS state.db was already safe:
+ the sqlite backup API truncates the destination to an exact copy.
+ Add any new per-company cache table to that constant, once.
+ Graded as NOT wiped: generated_fixtures (operator-level, see
+ _GLOBAL_TABLES) and architecture_sections (repo-derived, keyed by a hash of
+ the facts file). Still UNGRADED, deliberately deferred: dynamic_workflows
+ and eval_scenarios. These ARE client-scoped — the non-blank path already
+ swaps them with the whole DB — and on the blank path the outgoing client's
+ workflow definitions stay registered AND active (`list_definitions(
+ active_only=True)`), runnable against the incoming client's data, with full
+ bodies exposed via /workflows. They are not in the wipe list because they
+ are authored, not derived, and `snapshot_user_state` (the first-activation
+ branch, when no client is active) captures only profile/docs/memory.json/
+ people/departments — so wiping them there would irrecoverably delete the
+ operator's own work. The fix is to capture them in that snapshot FIRST,
+ then wipe. Both tables are empty on current installs.
invariants:
- At most one slot is active; the .active_client sentinel records it
(allowlist-validated on read, same defence as the fixture sentinel).
diff --git a/packages/core/openexecutive/cli/fixture_loader.py b/packages/core/openexecutive/cli/fixture_loader.py
index 3fc7d971..8f75d94c 100644
--- a/packages/core/openexecutive/cli/fixture_loader.py
+++ b/packages/core/openexecutive/cli/fixture_loader.py
@@ -65,6 +65,28 @@ _FIXTURE_OP_LOCK = asyncio.Lock()
# sentinel file so a tampered/garbage value cannot reach the UI.
_SAFE_NAME_RE = re.compile(r"^[a-z0-9_-]+$")
+# Per-company DERIVED caches in the episodic DB. Regenerable, so always safe to
+# drop — and they MUST be dropped by every path that swaps the live company,
+# because /today serves them from cache and only regenerates in a
+# BackgroundTask. Leave a row behind and the next request renders the OUTGOING
+# company's text under the incoming one: observed live, one client's briefing
+# narrative appearing verbatim under another.
+#
+# Three separate paths swap live company state, and each maintained its own
+# hand-written table list — so this was fixed in one and still live in the other
+# two. They now all consume this constant: `clients.slots._BLANK_WIPE_TABLES`
+# (client switch into a blank/seed slot), `reset_all_state` (factory reset), and
+# `_seed_episodic_memory` (fixture load). Any new per-company cache table goes
+# here, once.
+#
+# Not included, deliberately: `generated_fixtures` (operator-level, see
+# `slots._GLOBAL_TABLES`) and `architecture_sections` (repo-derived, keyed by a
+# hash of the facts file — not company data).
+PER_CLIENT_CACHE_TABLES: tuple[str, ...] = (
+ "briefing_narrative",
+ "person_insights",
+)
+
# Walk up from this file to find the repo root (contains evals/, fixtures/, etc.)
# Match on ``fixtures/companies`` specifically — NOT a bare ``fixtures`` dir —
# so the in-package ``openexecutive/fixtures/`` module (generated-fixture store
@@ -671,6 +693,14 @@ async def reset_all_state(
# circuit (and there's nothing to wipe in a DB that isn't there).
if EPISODIC_DB_PATH.exists():
monitoring_store.initialize_db(EPISODIC_DB_PATH)
+ # Same reasoning for the derived caches in PER_CLIENT_CACHE_TABLES:
+ # both create their table lazily on first put/get, so a DB that has
+ # never served a briefing lacks them and the DELETE pass would raise.
+ from openexecutive.briefing import narrative_cache
+ from openexecutive.people import insights_cache
+
+ narrative_cache.initialize_db(EPISODIC_DB_PATH)
+ insights_cache.initialize_db(EPISODIC_DB_PATH)
episodic_cleared = _delete_all_rows(
EPISODIC_DB_PATH,
(
@@ -689,6 +719,7 @@ async def reset_all_state(
"eval_runs",
"external_signals",
"watchlist",
+ *PER_CLIENT_CACHE_TABLES,
),
)
@@ -1136,6 +1167,18 @@ def _seed_episodic_memory(memory_path: Path, settings: Any) -> dict[str, int]:
if alerts_table_exists:
conn.execute("DELETE FROM alerts")
+ # Derived per-company caches. Without this, loading a fixture over a
+ # live company leaves that company's cached briefing narrative in
+ # place and the demo's /today renders it verbatim — the surface most
+ # likely to be screen-shared. Same existence guard as alerts above:
+ # a minimal/legacy DB may not have these tables yet.
+ for cache_table in PER_CLIENT_CACHE_TABLES:
+ if conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
+ (cache_table,),
+ ).fetchone():
+ conn.execute(f"DELETE FROM {cache_table}") # noqa: S608 — fixed tuple
+
decisions = data.get("decisions", [])
for row in decisions:
conn.execute(
diff --git a/packages/core/openexecutive/clients/slots.py b/packages/core/openexecutive/clients/slots.py
index 32d6738f..10773f9b 100644
--- a/packages/core/openexecutive/clients/slots.py
+++ b/packages/core/openexecutive/clients/slots.py
@@ -45,6 +45,9 @@ from openexecutive.cli.fixture_loader import (
get_fixture_status,
snapshot_user_state,
)
+from openexecutive.cli.fixture_loader import (
+ PER_CLIENT_CACHE_TABLES as _PER_CLIENT_CACHE_TABLES,
+)
logger = logging.getLogger(__name__)
@@ -82,6 +85,18 @@ ENGAGEMENT_STATUSES = ("active", "paused", "winding_down", "completed")
# Ordered children-before-parents for PRAGMA foreign_keys=ON. Existence-guarded
# at delete time, so stores that haven't initialized on this box are skipped.
_BLANK_WIPE_TABLES = (
+ # Derived caches first — see PER_CLIENT_CACHE_TABLES for why they must be
+ # wiped by every company-swapping path, not just this one. Neither declares
+ # a foreign key, so head position is free.
+ #
+ # Do not assume person_insights' input_hash makes it self-guarding: the hash
+ # (people.insights.build_insight_input_hash) covers role, is_principal,
+ # status, counters, availability and the UTC day — NOT the person's name or
+ # id. The cache key is person_id, a reused autoincrement PK. So an outgoing
+ # principal and a freshly seeded incoming principal, both with no awaiting
+ # work on the same day, hash identically and the stale note is served. That
+ # is an ordinary steady state for a seeded slot, not a collision.
+ *_PER_CLIENT_CACHE_TABLES,
"chat_messages",
"sessions",
"decisions",
diff --git a/packages/core/tests/unit/test_client_slots.py b/packages/core/tests/unit/test_client_slots.py
index eb79cba2..1db5c43b 100644
--- a/packages/core/tests/unit/test_client_slots.py
+++ b/packages/core/tests/unit/test_client_slots.py
@@ -458,6 +458,96 @@ async def test_generated_slot_pins_encoding_on_every_text_write(
assert (slot / "docs" / "plano.md").read_bytes().decode("utf-8") == _NON_ASCII_DOC
+async def test_seed_slot_activation_clears_derived_caches(env: SimpleNamespace) -> None:
+ """The outgoing client's cached narrative/insights must not survive a switch.
+
+ /today serves the cached briefing narrative unconditionally and only
+ regenerates in a background task (api/routes/today.py::_attach_narrative),
+ so a surviving row renders the PREVIOUS client's narrative under the
+ incoming one — observed live, one client's briefing appearing verbatim
+ under another. Both tables are regenerable caches, so wiping is free.
+ """
+ from openexecutive.briefing import narrative_cache
+ from openexecutive.people import insights_cache
+
+ _seed_live_company(env, "Outgoing Co")
+ narrative_cache.put(
+ narrative_cache.BriefingNarrative(
+ scope="principal",
+ input_hash="stale-hash",
+ narrative_text="**Outgoing Co is straining** — do not show this elsewhere.",
+ generated_at="2026-09-01T00:00:00+00:00",
+ )
+ )
+ insights_cache.put(
+ insights_cache.PersonInsight(
+ person_id=1,
+ input_hash="stale-hash",
+ insight_text="Outgoing Co founder is unreachable.",
+ generated_at="2026-09-01T00:00:00+00:00",
+ )
+ )
+ # Both caches are warm for the outgoing client.
+ assert narrative_cache.get("principal") is not None
+ assert insights_cache.get(1) is not None
+
+ await create_client_slot(
+ env.settings,
+ display_name="Incoming Co",
+ source="generated",
+ bundle=_intake_bundle(),
+ )
+ await activate_client_slot(env.settings, "incoming_co")
+
+ assert narrative_cache.get("principal") is None
+ assert insights_cache.get(1) is None
+
+
+async def test_switch_preserves_outgoing_caches_in_its_slot(env: SimpleNamespace) -> None:
+ """Wiping the caches on switch must not DESTROY them — only unpublish them.
+
+ The wipe has to happen after the outgoing client's VACUUM INTO save-back, so
+ its cached narrative lands in state.db and returns on reactivation. Ordering
+ the wipe before the save-back would lose it permanently, and the sibling
+ test above cannot catch that: there, no client is active, so the save-back
+ branch of activate_client_slot never runs.
+ """
+ from openexecutive.briefing import narrative_cache
+ from openexecutive.people import insights_cache
+
+ _seed_live_company(env, "Client A")
+ await create_client_slot(env.settings, display_name="Client A", source="current")
+ narrative_cache.put(
+ narrative_cache.BriefingNarrative(
+ scope="principal",
+ input_hash="a-hash",
+ narrative_text="**Client A narrative**",
+ generated_at="2026-09-01T00:00:00+00:00",
+ )
+ )
+ insights_cache.put(
+ insights_cache.PersonInsight(
+ person_id=1,
+ input_hash="a-hash",
+ insight_text="Client A insight",
+ generated_at="2026-09-01T00:00:00+00:00",
+ )
+ )
+ await save_active_client(env.settings)
+
+ await create_client_slot(env.settings, display_name="Client B", source="blank")
+ await activate_client_slot(env.settings, "client_b")
+ assert narrative_cache.get("principal") is None
+
+ await activate_client_slot(env.settings, "client_a")
+ restored = narrative_cache.get("principal")
+ assert restored is not None
+ assert restored.narrative_text == "**Client A narrative**"
+ restored_insight = insights_cache.get(1)
+ assert restored_insight is not None
+ assert restored_insight.insight_text == "Client A insight"
+
+
async def test_generated_seed_slot_activation_seeds_org_and_memory(
env: SimpleNamespace,
) -> None:
diff --git a/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py b/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
index 33229913..e2186cd9 100644
--- a/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
+++ b/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
@@ -23,6 +23,7 @@ import inspect
import sqlite3
from datetime import UTC, datetime
from pathlib import Path
+from types import SimpleNamespace
import pytest
@@ -141,3 +142,92 @@ def test_apply_state_from_source_resets_research_skip_gate() -> None:
"a fixture reload within 24h will skip its seeded research scan and "
"surface zero findings."
)
+
+
+# ── Derived per-company caches (same leak class as the watchlist above) ──────
+#
+# briefing_narrative and person_insights were wiped by NO path. Because /today
+# serves them from cache and only regenerates in a BackgroundTask, loading a
+# demo fixture over a live company rendered that company's real briefing
+# narrative verbatim under the demo — on the surface most likely to be
+# screen-shared. All three swapping paths now consume PER_CLIENT_CACHE_TABLES.
+
+
+def test_seed_episodic_memory_clears_derived_caches(
+ _episodic_db: Path, tmp_path: Path
+) -> None:
+ """The fixture-load seeder must drop the outgoing company's cached text.
+
+ Behavioural, not a source grep: ``_seed_episodic_memory`` is cheap, and it
+ resolves the DB via ``episodic.DB_PATH`` imported at call time, which the
+ ``_episodic_db`` fixture monkeypatches — so the wipe is proven against the
+ live schema rather than asserted from source.
+ """
+ import json
+
+ from openexecutive.briefing import narrative_cache
+ from openexecutive.cli.fixture_loader import _seed_episodic_memory
+ from openexecutive.people import insights_cache
+
+ # First arg is the fixture's memory.json, NOT a db path; an absent or
+ # unparseable file short-circuits before the wipe, so it must be real.
+ memory_path = tmp_path / "memory.json"
+ memory_path.write_text(json.dumps({"decisions": []}), encoding="utf-8")
+
+ narrative_cache.put(
+ narrative_cache.BriefingNarrative(
+ scope="principal",
+ input_hash="outgoing",
+ narrative_text="**Real client narrative** — must not reach a demo.",
+ generated_at=datetime.now(UTC).isoformat(),
+ ),
+ db_path=_episodic_db,
+ )
+ insights_cache.put(
+ insights_cache.PersonInsight(
+ person_id=1,
+ input_hash="outgoing",
+ insight_text="Real client founder note.",
+ generated_at=datetime.now(UTC).isoformat(),
+ ),
+ db_path=_episodic_db,
+ )
+ assert narrative_cache.get("principal", db_path=_episodic_db) is not None
+ assert insights_cache.get(1, db_path=_episodic_db) is not None
+
+ # settings has no episodic_db_path, so the seeder falls back to the
+ # monkeypatched episodic.DB_PATH — i.e. _episodic_db.
+ _seed_episodic_memory(memory_path, SimpleNamespace())
+
+ assert narrative_cache.get("principal", db_path=_episodic_db) is None
+ assert insights_cache.get(1, db_path=_episodic_db) is None
+
+
+def test_wipe_lists_consume_the_shared_cache_constant() -> None:
+ """All three swapping paths must reference the one constant, not copies.
+
+ The original bug was three hand-maintained table lists over one DB: the fix
+ landed in one and the leak stayed live in the other two. Source-grep for the
+ heavy async ``reset_all_state`` (same cheap guard the monitoring tables use)
+ and for the shared constant in the slot wipe list.
+ """
+ from openexecutive.cli.fixture_loader import (
+ PER_CLIENT_CACHE_TABLES,
+ _seed_episodic_memory,
+ )
+ from openexecutive.clients.slots import _BLANK_WIPE_TABLES
+
+ assert PER_CLIENT_CACHE_TABLES == ("briefing_narrative", "person_insights")
+
+ for fn in (reset_all_state, _seed_episodic_memory):
+ assert "PER_CLIENT_CACHE_TABLES" in inspect.getsource(fn), (
+ f"{fn.__name__} no longer consumes PER_CLIENT_CACHE_TABLES — the "
+ "outgoing company's cached briefing narrative will survive and be "
+ "rendered under the incoming one."
+ )
+
+ for table in PER_CLIENT_CACHE_TABLES:
+ assert table in _BLANK_WIPE_TABLES, (
+ f"{table!r} dropped out of the client-slot wipe list — switching "
+ "into a blank/seed slot will leak the previous client's cache."
+ )