Skip to content

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

fix(clients): address review on the derived-cache leak fix

Rufusb91587695f91
diff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yaml
index d74d6973..13e18e04 100644
--- a/packages/core/openexecutive/architecture/architecture-facts.yaml
+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml
@@ -2847,16 +2847,24 @@ clients:
/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.
+ input_hash self-guards: that hash covers role, is_principal, status,
+ awaiting/reply counters, overdue, on_leave_until, reachable_now,
+ authority_scope, department_slugs, four hour-bucketed timestamps and the
+ UTC day — all per-person signals, and NOT person, name or company
+ identity. The key is a reused autoincrement person_id, so an outgoing
+ principal and a freshly seeded incoming principal hash identically
+ whenever those signals coincide. 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).
+ `reset_all_state` (factory reset), and `_apply_state_from_source` (fixture
+ load AND unload — the worst surface, since a demo is what gets
+ screen-shared). The fixture-path wipe sits in `_apply_state_from_source`
+ beside the unconditional watchlist wipe, NOT in `_seed_episodic_memory`:
+ that seeder returns early when a fixture has no readable `memory.json`,
+ and `load_fixture` only requires `profile.yaml`, so a wipe inside the
+ seeder is skipped on exactly those loads while the company still swaps.
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.
@@ -2872,7 +2880,8 @@ clients:
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.
+ then wipe. Both tables were observed empty on all known installs as of
+ 2026-09 — an observation at a point in time, not an invariant to rely on.
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/architecture/prebuilt/clients.json b/packages/core/openexecutive/architecture/prebuilt/clients.json
index 50e41586..46e018dc 100644
--- a/packages/core/openexecutive/architecture/prebuilt/clients.json
+++ b/packages/core/openexecutive/architecture/prebuilt/clients.json
@@ -1,7 +1,7 @@
{
"section_id": "clients",
"title": "Client Companies (Slots)",
- "markdown": "The **clients** module (`openexecutive.clients`) adds **multi-client mode** for fractional executives: one Open Executive instance serving several client companies, exactly **one active at a time**. It generalizes the fixture switcher's swap machinery into named, durable *slots* \u2014 save files of the full company context. Single-company installs are untouched: nothing changes until a slot is explicitly created, and the `/clients` page shows only an intro until then.\n\n## What a slot contains\n\nEach slot lives at `company/_client_slots/<slug>/` (gitignored \u2014 client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB \u2014 chat history, scheduled actions, onboarding plans, talent pipeline, departments, people, watchlist, audit/run history |\n| `profile.yaml` | The company profile |\n| `docs/`, `skills/` | Company documents (all file types) and company-authored skills |\n| `mcp_servers.json` | Per-client external MCP tools (e.g. one client's Crayon or Google Workspace credentials) |\n| `meta.json` | Display name + created/saved timestamps |\n\n## Switching\n\n`POST /clients/{slug}/activate` saves the current client back to its slot (`VACUUM INTO` for the DB copy), then restores the target: the DB through sqlite3's online **backup API** (the live file's inode never changes, so handles held elsewhere stay valid), the company artifacts by replacement, and the ChromaDB `company_docs` collection + company skills re-indexed from the restored directories. Idempotent schema initializers re-run after every restore, so a slot saved before a schema-adding deploy gains the new tables. Activating a **blank** slot (created with `source: \"blank\"`, no `state.db` yet) factory-wipes the per-client tables and re-seeds defaults \u2014 departments, onboarding templates, principal briefs, cadences \u2014 so the new client's Today page works without a restart.\n\nThe first activation from single-company mode auto-snapshots the original company to `_user_backup` (the same restore point the fixture switcher uses); `POST /fixtures/unload` brings it back and exits client mode.\n\n## Invariants\n\n- At most one slot is active \u2014 recorded in an allowlist-validated `.active_client` sentinel.\n- **Only the active client is live**: its scheduled actions fire, its docs are indexed; parked clients sleep. The single-instance scheduler constraint is unchanged.\n- Slot operations share the fixture switcher's destructive-op lock, so fixture loads, snapshots, resets, and slot switches serialize against each other. The Notion sync tick coordinates with the same lock without queueing on it: it skips its tick while the lock is held, fetches from Notion unlocked, and takes the lock only for its short local write phase \u2014 aborting without writing if the active client changed mid-fetch (in-process only; a CLI run is a separate process the lock cannot see). A fixture and a client are never active simultaneously (slot ops refuse with 409 while a fixture is loaded); loading a fixture saves an active client back to its slot first, so demos can never destroy client work. Factory reset clears the active-client sentinel but preserves slot directories.\n- `generated_fixtures` is operator-level (the demo library) and is preserved verbatim across switches.\n- Each client gets a stable Honcho workspace (`openexec-client-<slug>`) so peer memory survives parking; fixture teardown paths recognise the prefix and never delete these.\n\n## Caveats\n\n`mcp_servers.json` is read by the MCP gateway at process startup \u2014 a switch that changes it takes effect on the next API restart (the activate response carries `mcp_config_changed`). Scheduled actions whose `run_at` passed while a client was parked are claimed on the first tick after activation; authority gates still apply, but expect the returning client's overdue follow-ups to fire shortly after a switch.\n\n## Setting up a new engagement with AI\n\n`POST /clients/generate` turns **real intake material** into a reviewable draft of the client: profile, org, roster, starter docs, and known history. Intake material is pasted text (kickoff-call notes, a brief, website copy) and/or **file attachments** (PDF, Word, Excel, CSV, Markdown/text; the request is multipart). Each attachment's extracted text both feeds the draft and is appended to the bundle as a `source_<name>.md` company doc, so it lands in the seed slot and is indexed into the `company_docs` collection on activation alongside the AI-written docs (extracted text, not the original binary; legacy `.xls` is unsupported). It runs the Council-configurable `engagement_intake` agent \u2014 the grounded sibling of the demo fixture generator (same bundle schema, validation, and repair-retry; the Company Simulator's fictional path is unchanged). Grounding rules: extract, don't invent \u2014 unstated numbers stay null, only people named in the material appear, docs are engagement working documents (intake brief, current-state summary, stakeholder map, open questions), and **no contact handles are ever imported**, even if present in the notes.\n\nSaving the reviewed draft (`POST /clients` with `source: \"generated\"`) writes a **seed slot**: profile and docs as normal slot artifacts, plus `people.yaml` / `departments.yaml` / `memory.json` in the same shapes curated fixtures use. Nothing touches live state until activation, when the blank-restore path applies the seed files with the fixture loader's seeders and skips the default-department reseed (the draft supplied the org). After the first save-back writes `state.db`, the seed files remain as the engagement's birth record but are no longer consulted; `meta.json` records `origin: \"generated\"` and the intake notes.\n\n## The practice layer: engagement metadata + cockpit\n\nEach slot's `meta.json` carries optional **engagement metadata** \u2014 your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact \u2014 editable via `PATCH /clients/{slug}` for active *and* parked slots, because meta.json lives outside the swapped client state. Renewal awareness deliberately lives here and never as scheduled actions (those swap with the client and would vanish when parked).\n\nThe **practice cockpit** (`GET /clients/cockpit`) gives cross-client awareness without touching the one-active-client ceiling: the active client is counted from the live DB, and each parked client's `state.db` is opened **read-only, in place** \u2014 no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, onboarding tasks due within a week, and renewal countdowns. Parked data is as fresh as the slot's last save point and every card says so; one broken slot degrades to a single error-flagged card, never a failed board. Cockpit cards link to the **engagement value report** \u2014 a workflow that turns the client's own record (decisions, deliverables, follow-through) into a renewal-ready artifact, reading parked clients without activating them. With two or more clients, `/today` gains an \"Across your clients\" section for the parked ones \u2014 single-company installs see none of this, anywhere.\n\n## Overnight rotation (cockpit v2)\n\nWith `CLIENT_ROTATION_ENABLED=true` (off by default), a nightly scheduled job (`CLIENT_ROTATION_TIME`, default 03:30 UTC) activates each parked client in turn, generates its morning brief as an artifact in that client's own record, runs its monitor scan, saves it back, and **always restores the original active client** \u2014 then delivers one cross-client digest via the original client's principal channel. Two safety rails matter: the scheduler **pauses claiming** while the rotation's `.rotation_in_progress` marker exists (so a just-activated client's overdue outbound backlog can never fire at 3am \u2014 rotation does brief + monitors only, never outbound), and the rotation row is re-seeded after every slot activation because scheduled rows swap with the client. Completed engagements and never-activated slots sleep through rotation; per-client failures are skipped and reported in the digest.\n\n## API + UI\n\n`GET /clients` (list + active + fixture status), `POST /clients` (`source: \"current\"` captures the live company and activates; `\"blank\"` creates an empty client to onboard fresh; `\"generated\"` saves a reviewed intake draft as a seed slot), `POST /clients/generate` (grounded AI draft from intake notes and/or file attachments; multipart), `PATCH /clients/{slug}` (engagement metadata), `GET /clients/cockpit` (practice board), `POST /clients/save` (checkpoint without switching), `POST /clients/{slug}/activate`, `DELETE /clients/{slug}` (refuses the active slot). The `/clients` page lives under Settings \u2192 advanced tools.",
+ "markdown": "The **clients** module (`openexecutive.clients`) adds **multi-client mode** for fractional executives: one Open Executive instance serving several client companies, exactly **one active at a time**. It generalizes the fixture switcher's swap machinery into named, durable *slots* \u2014 save files of the full company context. Single-company installs are untouched: nothing changes until a slot is explicitly created, and the `/clients` page shows only an intro until then.\n\n## What a slot contains\n\nEach slot lives at `company/_client_slots/<slug>/` (gitignored \u2014 client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB \u2014 chat history, scheduled actions, onboarding plans, talent pipeline, departments, people, watchlist, audit/run history |\n| `profile.yaml` | The company profile |\n| `docs/`, `skills/` | Company documents (all file types) and company-authored skills |\n| `mcp_servers.json` | Per-client external MCP tools (e.g. one client's Crayon or Google Workspace credentials) |\n| `meta.json` | Display name + created/saved timestamps |\n\n## Switching\n\n`POST /clients/{slug}/activate` saves the current client back to its slot (`VACUUM INTO` for the DB copy), then restores the target: the DB through sqlite3's online **backup API** (the live file's inode never changes, so handles held elsewhere stay valid), the company artifacts by replacement, and the ChromaDB `company_docs` collection + company skills re-indexed from the restored directories. Idempotent schema initializers re-run after every restore, so a slot saved before a schema-adding deploy gains the new tables. Activating a **blank** slot (created with `source: \"blank\"`, no `state.db` yet) factory-wipes the per-client tables and re-seeds defaults \u2014 departments, onboarding templates, principal briefs, cadences \u2014 so the new client's Today page works without a restart. That wipe covers the **derived caches** \u2014 `briefing_narrative` and `person_insights` \u2014 as well as authored state. They are regenerable, but `/today` serves them from cache and only regenerates in a background task, so a surviving row renders the *outgoing* client's briefing text under the incoming one, and `person_insights` reaches Discord, the MCP server, and the morning/end-of-day digests as well as the UI. Switching into a slot that already has `state.db` was never exposed: the sqlite backup API truncates the destination to an exact copy of the source.\n\nThe first activation from single-company mode auto-snapshots the original company to `_user_backup` (the same restore point the fixture switcher uses); `POST /fixtures/unload` brings it back and exits client mode.\n\n## Invariants\n\n- At most one slot is active \u2014 recorded in an allowlist-validated `.active_client` sentinel.\n- **Only the active client is live**: its scheduled actions fire, its docs are indexed; parked clients sleep. The single-instance scheduler constraint is unchanged.\n- Slot operations share the fixture switcher's destructive-op lock, so fixture loads, snapshots, resets, and slot switches serialize against each other. The Notion sync tick coordinates with the same lock without queueing on it: it skips its tick while the lock is held, fetches from Notion unlocked, and takes the lock only for its short local write phase \u2014 aborting without writing if the active client changed mid-fetch (in-process only; a CLI run is a separate process the lock cannot see). A fixture and a client are never active simultaneously (slot ops refuse with 409 while a fixture is loaded); loading a fixture saves an active client back to its slot first, so demos can never destroy client work. Factory reset clears the active-client sentinel but preserves slot directories.\n- `generated_fixtures` is operator-level (the demo library) and is preserved verbatim across switches.\n- **Every path that swaps the live company wipes the derived caches**, from one shared list (`cli.fixture_loader.PER_CLIENT_CACHE_TABLES`): blank/seed slot activation, factory reset, and fixture load *and* unload. Three hand-maintained copies of that list is what let the leak survive in two paths after being fixed in one \u2014 a new per-company cache table goes in the constant, once. On the fixture path the wipe runs in `_apply_state_from_source`, unconditionally: a fixture needs only `profile.yaml`, so gating it on `memory.json` would skip exactly the loads that still swap the company.\n- Do **not** treat `person_insights`' `input_hash` as a guard against this. It covers per-person signals (role, principal flag, status, counters, availability, authority and department scope, bucketed timestamps, the UTC day) but carries no person, name or company identity, and the cache key is `person_id` \u2014 a reused autoincrement PK. An outgoing principal and a freshly seeded incoming one hash identically whenever those signals coincide, which is ordinary steady state for a seeded slot.\n- Each client gets a stable Honcho workspace (`openexec-client-<slug>`) so peer memory survives parking; fixture teardown paths recognise the prefix and never delete these.\n\n## Caveats\n\n`mcp_servers.json` is read by the MCP gateway at process startup \u2014 a switch that changes it takes effect on the next API restart (the activate response carries `mcp_config_changed`). Scheduled actions whose `run_at` passed while a client was parked are claimed on the first tick after activation; authority gates still apply, but expect the returning client's overdue follow-ups to fire shortly after a switch.\n\nTwo residuals on the blank-slot path. `/today`'s background regeneration tasks capture the outgoing company's data and can write it back into the live DB for up to roughly 25 seconds after a switch, past the wipe; closing that needs company identity in the cache hash or those writers taking the destructive-op lock. And `dynamic_workflows` / `eval_scenarios` are client-scoped but **not** wiped: they are authored rather than derived, and the first-activation snapshot captures only profile, docs, `memory.json`, people and departments \u2014 so wiping them before extending that snapshot would destroy the operator's own work. Until then the outgoing client's workflow definitions stay registered and active on the blank path, runnable against the incoming client's data and readable via `/workflows`.\n\n## Setting up a new engagement with AI\n\n`POST /clients/generate` turns **real intake material** into a reviewable draft of the client: profile, org, roster, starter docs, and known history. Intake material is pasted text (kickoff-call notes, a brief, website copy) and/or **file attachments** (PDF, Word, Excel, CSV, Markdown/text; the request is multipart). Each attachment's extracted text both feeds the draft and is appended to the bundle as a `source_<name>.md` company doc, so it lands in the seed slot and is indexed into the `company_docs` collection on activation alongside the AI-written docs (extracted text, not the original binary; legacy `.xls` is unsupported). It runs the Council-configurable `engagement_intake` agent \u2014 the grounded sibling of the demo fixture generator (same bundle schema, validation, and repair-retry; the Company Simulator's fictional path is unchanged). Grounding rules: extract, don't invent \u2014 unstated numbers stay null, only people named in the material appear, docs are engagement working documents (intake brief, current-state summary, stakeholder map, open questions), and **no contact handles are ever imported**, even if present in the notes.\n\nSaving the reviewed draft (`POST /clients` with `source: \"generated\"`) writes a **seed slot**: profile and docs as normal slot artifacts, plus `people.yaml` / `departments.yaml` / `memory.json` in the same shapes curated fixtures use. Nothing touches live state until activation, when the blank-restore path applies the seed files with the fixture loader's seeders and skips the default-department reseed (the draft supplied the org). After the first save-back writes `state.db`, the seed files remain as the engagement's birth record but are no longer consulted; `meta.json` records `origin: \"generated\"` and the intake notes.\n\n## The practice layer: engagement metadata + cockpit\n\nEach slot's `meta.json` carries optional **engagement metadata** \u2014 your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact \u2014 editable via `PATCH /clients/{slug}` for active *and* parked slots, because meta.json lives outside the swapped client state. Renewal awareness deliberately lives here and never as scheduled actions (those swap with the client and would vanish when parked).\n\nThe **practice cockpit** (`GET /clients/cockpit`) gives cross-client awareness without touching the one-active-client ceiling: the active client is counted from the live DB, and each parked client's `state.db` is opened **read-only, in place** \u2014 no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, onboarding tasks due within a week, and renewal countdowns. Parked data is as fresh as the slot's last save point and every card says so; one broken slot degrades to a single error-flagged card, never a failed board. Cockpit cards link to the **engagement value report** \u2014 a workflow that turns the client's own record (decisions, deliverables, follow-through) into a renewal-ready artifact, reading parked clients without activating them. With two or more clients, `/today` gains an \"Across your clients\" section for the parked ones \u2014 single-company installs see none of this, anywhere.\n\n## Overnight rotation (cockpit v2)\n\nWith `CLIENT_ROTATION_ENABLED=true` (off by default), a nightly scheduled job (`CLIENT_ROTATION_TIME`, default 03:30 UTC) activates each parked client in turn, generates its morning brief as an artifact in that client's own record, runs its monitor scan, saves it back, and **always restores the original active client** \u2014 then delivers one cross-client digest via the original client's principal channel. Two safety rails matter: the scheduler **pauses claiming** while the rotation's `.rotation_in_progress` marker exists (so a just-activated client's overdue outbound backlog can never fire at 3am \u2014 rotation does brief + monitors only, never outbound), and the rotation row is re-seeded after every slot activation because scheduled rows swap with the client. Completed engagements and never-activated slots sleep through rotation; per-client failures are skipped and reported in the digest.\n\n## API + UI\n\n`GET /clients` (list + active + fixture status), `POST /clients` (`source: \"current\"` captures the live company and activates; `\"blank\"` creates an empty client to onboard fresh; `\"generated\"` saves a reviewed intake draft as a seed slot), `POST /clients/generate` (grounded AI draft from intake notes and/or file attachments; multipart), `PATCH /clients/{slug}` (engagement metadata), `GET /clients/cockpit` (practice board), `POST /clients/save` (checkpoint without switching), `POST /clients/{slug}/activate`, `DELETE /clients/{slug}` (refuses the active slot). The `/clients` page lives under Settings \u2192 advanced tools.",
"mermaid": "flowchart TD\n UI[\"/clients page (Settings)\"] -->|\"activate slug\"| Lock[\"destructive-op lock (shared with fixtures)\"]\n Lock --> SaveBack[\"save-back: VACUUM INTO state.db + copy profile / docs / skills / mcp\"]\n SaveBack --> SlotA[(\"slot A dir\")]\n SlotB[(\"slot B dir\")] --> Restore[\"restore: sqlite backup API + artifact replacement\"]\n Lock --> Restore\n Restore --> Live[(\"live company context\")]\n Restore --> Chroma[\"reindex company_docs + skills\"]\n Restore -.stable workspace.-> Honcho[\"Honcho peer memory\"]\n Live --> Scheduler[\"scheduler: only the ACTIVE client's actions fire\"]",
- "generated_at": "2026-06-10T00:00:00Z"
+ "generated_at": "2026-09-07T00:00:00Z"
}
\ No newline at end of file
diff --git a/packages/core/openexecutive/cli/fixture_loader.py b/packages/core/openexecutive/cli/fixture_loader.py
index 8f75d94c..028bc00b 100644
--- a/packages/core/openexecutive/cli/fixture_loader.py
+++ b/packages/core/openexecutive/cli/fixture_loader.py
@@ -76,8 +76,14 @@ _SAFE_NAME_RE = re.compile(r"^[a-z0-9_-]+$")
# 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.
+# `_apply_state_from_source` (fixture load AND unload). Any new per-company
+# cache table goes here, once.
+#
+# The fixture-path wipe belongs in `_apply_state_from_source`, NOT in
+# `_seed_episodic_memory`: that seeder returns early when the fixture has no
+# readable `memory.json`, and `load_fixture` only requires `profile.yaml` — so
+# such a fixture swaps the company while skipping a wipe placed inside the
+# seeder.
#
# Not included, deliberately: `generated_fixtures` (operator-level, see
# `slots._GLOBAL_TABLES`) and `architecture_sections` (repo-derived, keyed by a
@@ -497,6 +503,29 @@ async def _apply_state_from_source(source_dir: Path, settings: Any) -> dict[str,
EPISODIC_DB_PATH, ("external_signals", "watchlist")
)
+ # ── 5b. Wipe the derived per-company caches ────────────────────────────
+ # Same leak class as the watchlist above, and it lives here — beside the
+ # other unconditional wipes — rather than in ``_seed_episodic_memory``,
+ # because that seeder returns early on a fixture whose ``memory.json`` is
+ # absent or unparseable. ``load_fixture`` only requires ``profile.yaml``,
+ # so such a fixture still swaps the company; wiping inside the seeder
+ # would skip exactly those loads and serve the outgoing company's
+ # narrative under the incoming one. Nothing here is conditional on the
+ # fixture's contents.
+ #
+ # Both caches CREATE TABLE lazily on first put, so a DB that has never
+ # served a briefing lacks them and _delete_all_rows — which is not
+ # per-table existence-guarded — would raise mid-wipe. Initialize first,
+ # exactly as the monitoring schema is handled above. Idempotent.
+ from openexecutive.briefing import narrative_cache
+ from openexecutive.people import insights_cache
+
+ if EPISODIC_DB_PATH.exists():
+ narrative_cache.initialize_db(EPISODIC_DB_PATH)
+ insights_cache.initialize_db(EPISODIC_DB_PATH)
+ caches_cleared = _delete_all_rows(EPISODIC_DB_PATH, PER_CLIENT_CACHE_TABLES)
+ logger.info("fixture: cleared derived per-company caches: %s", caches_cleared)
+
# ── 6. Reset the periodic research skip-if-unchanged gate ───────────────
# The skip gate reads the last run's state_hash from audit_log; load/unload
# wipes the profile/initiatives/watchlist that feed that fingerprint but
@@ -1167,18 +1196,6 @@ 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 10773f9b..b8a92418 100644
--- a/packages/core/openexecutive/clients/slots.py
+++ b/packages/core/openexecutive/clients/slots.py
@@ -89,13 +89,18 @@ _BLANK_WIPE_TABLES = (
# 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
+ # 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.
+ # status, awaiting_count, awaiting_reply_count, overdue, on_leave_until,
+ # reachable_now, authority_scope, department_slugs, the hour-bucketed
+ # soonest_sla_at / oldest_awaiting_reply_at / next_window_at /
+ # last_contact_at, and the UTC day — every one of them a per-person signal,
+ # and NOT the person's name, the person's id, or the company. The cache key
+ # is person_id, a reused autoincrement PK. So an outgoing principal and a
+ # freshly seeded incoming principal hash identically whenever those signals
+ # coincide: both principals, same role string, no awaiting work, no leave,
+ # same default departments, same UTC day. That is an ordinary steady state
+ # for a seeded slot, not a collision.
*_PER_CLIENT_CACHE_TABLES,
"chat_messages",
"sessions",
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 e2186cd9..bb0ce633 100644
--- a/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
+++ b/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
@@ -23,7 +23,6 @@ import inspect
import sqlite3
from datetime import UTC, datetime
from pathlib import Path
-from types import SimpleNamespace
import pytest
@@ -150,30 +149,50 @@ def test_apply_state_from_source_resets_research_skip_gate() -> None:
# 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.
+# screen-shared. All three swapping paths now consume PER_CLIENT_CACHE_TABLES,
+# and on the fixture path the wipe sits in _apply_state_from_source rather
+# than in _seed_episodic_memory, which returns early without a memory.json.
-def test_seed_episodic_memory_clears_derived_caches(
- _episodic_db: Path, tmp_path: Path
+def test_delete_clears_derived_caches_on_a_never_briefed_db(
+ _episodic_db: 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.
+ """The cache wipe must work against the live schema, including a cold DB.
+
+ Behavioural, and deliberately routed through ``_delete_all_rows`` — the
+ same helper the call site delegates to — for the reason this module's
+ docstring gives: exercising ``_apply_state_from_source`` end to end would
+ drag ChromaDB, Honcho and an ``app.state`` shim into a unit test.
+
+ The cold-DB half is the regression the author hit: both caches CREATE
+ TABLE lazily on first put, so a DB that has never served a briefing lacks
+ them, and ``_delete_all_rows`` is not per-table existence-guarded. The
+ call site initializes both schemas first; this proves that is sufficient
+ and that the DELETE then really empties warm rows.
"""
- import json
-
from openexecutive.briefing import narrative_cache
- from openexecutive.cli.fixture_loader import _seed_episodic_memory
+ from openexecutive.cli.fixture_loader import PER_CLIENT_CACHE_TABLES
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")
+ # Cold: neither table exists yet on this DB.
+ with sqlite3.connect(str(_episodic_db)) as conn:
+ present = {
+ r[0]
+ for r in conn.execute(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
+ PER_CLIENT_CACHE_TABLES,
+ )
+ }
+ assert present == set(), (
+ "these caches are expected to be created lazily; if they now ship in "
+ "the base episodic schema the initialize_db calls at the wipe site "
+ "are redundant, but the wipe itself still must not regress."
+ )
+ narrative_cache.initialize_db(_episodic_db)
+ insights_cache.initialize_db(_episodic_db)
+ _delete_all_rows(_episodic_db, PER_CLIENT_CACHE_TABLES) # must not raise
+ # Warm: rows written by the outgoing company are actually removed.
narrative_cache.put(
narrative_cache.BriefingNarrative(
scope="principal",
@@ -195,36 +214,61 @@ def test_seed_episodic_memory_clears_derived_caches(
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())
+ _delete_all_rows(_episodic_db, PER_CLIENT_CACHE_TABLES)
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.
+def test_fixture_path_wipes_caches_unconditionally() -> None:
+ """The fixture-path wipe must not sit behind ``memory.json``.
- 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.
+ ``_seed_episodic_memory`` returns early when the fixture has no
+ ``memory.json``, when that file will not parse, and when the DB is
+ missing. ``load_fixture`` only requires ``profile.yaml``, so a fixture
+ with no usable ``memory.json`` still swaps the company — and a wipe
+ placed inside the seeder is skipped on exactly those loads, leaving the
+ outgoing company's narrative to be served under the incoming one.
+
+ So the wipe belongs in ``_apply_state_from_source``, beside the
+ unconditional watchlist wipe, and must stay out of the seeder. This pins
+ both halves; the sibling test above proves the deletion itself works.
"""
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."
- )
+ assert "PER_CLIENT_CACHE_TABLES" in inspect.getsource(_apply_state_from_source), (
+ "_apply_state_from_source no longer wipes the derived caches — fixture "
+ "load/unload will serve the outgoing company's briefing narrative "
+ "under the incoming one."
+ )
+ assert "PER_CLIENT_CACHE_TABLES" not in inspect.getsource(_seed_episodic_memory), (
+ "the derived-cache wipe moved back into _seed_episodic_memory, which "
+ "returns early on a fixture with no readable memory.json — those loads "
+ "would swap the company and skip the wipe."
+ )
+
+
+def test_reset_and_slot_switch_consume_the_shared_cache_constant() -> None:
+ """The other two company-swapping paths must reference the one constant.
+
+ 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`` (the same cheap guard the
+ monitoring tables use above) and for the shared constant in the slot
+ wipe list.
+ """
+ from openexecutive.cli.fixture_loader import PER_CLIENT_CACHE_TABLES
+ from openexecutive.clients.slots import _BLANK_WIPE_TABLES
+
+ assert "PER_CLIENT_CACHE_TABLES" in inspect.getsource(reset_all_state), (
+ "reset_all_state no longer consumes PER_CLIENT_CACHE_TABLES — a factory "
+ "reset will leave the previous company's cached briefing narrative."
+ )
for table in PER_CLIENT_CACHE_TABLES:
assert table in _BLANK_WIPE_TABLES, (