Skip to content

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

fix(clients): harden the derived-cache wipe guards after adversarial review

Rufusa8e29e285f3e
diff --git a/packages/core/openexecutive/architecture/prebuilt/clients.json b/packages/core/openexecutive/architecture/prebuilt/clients.json
index 46e018dc..b7a3a4fb 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. 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.",
+ "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. `/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 the wipe \u2014 on **every** swapping path, fixture load/unload and slot activation alike, since those writers neither take the destructive-op lock nor check company identity. For `person_insights` it does not self-heal: the late write stores the outgoing `input_hash`, which the incoming person's signals often match, so the stale note survives until the UTC-day bucket rolls. Closing this needs company identity in the cache hash or those writers taking the lock. Second, and blank-slot only, `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-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 028bc00b..82885d5c 100644
--- a/packages/core/openexecutive/cli/fixture_loader.py
+++ b/packages/core/openexecutive/cli/fixture_loader.py
@@ -504,26 +504,10 @@ async def _apply_state_from_source(source_dir: Path, settings: Any) -> dict[str,
)
# ── 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)
+ # Same leak class as the watchlist above; see PER_CLIENT_CACHE_TABLES for
+ # why this belongs here rather than in _seed_episodic_memory. Nothing in
+ # this step may become conditional on the fixture's contents.
+ caches_cleared = _wipe_derived_caches(EPISODIC_DB_PATH)
logger.info("fixture: cleared derived per-company caches: %s", caches_cleared)
# ── 6. Reset the periodic research skip-if-unchanged gate ───────────────
@@ -722,14 +706,10 @@ 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)
+ # Same reasoning for the derived caches in PER_CLIENT_CACHE_TABLES,
+ # which this DELETE pass also covers; the helper is guarded on the
+ # DB existing, exactly like the monitoring init above.
+ _initialize_derived_cache_schemas(EPISODIC_DB_PATH)
episodic_cleared = _delete_all_rows(
EPISODIC_DB_PATH,
(
@@ -913,6 +893,37 @@ def _delete_all_rows(
return counts
+def _initialize_derived_cache_schemas(db_path: Path) -> None:
+ """Create the PER_CLIENT_CACHE_TABLES schemas if the DB already exists.
+
+ Both caches CREATE TABLE lazily on first put, so a DB that has never
+ served a briefing lacks them — and ``_delete_all_rows`` guards only the DB
+ *file*, not each table, so a wipe would raise mid-pass. Idempotent
+ (CREATE TABLE IF NOT EXISTS). Guarded on the DB already existing so we
+ never materialise one the caller never created, which would defeat
+ ``_delete_all_rows``' own exists() short circuit.
+ """
+ if not db_path.exists():
+ return
+ from openexecutive.briefing import narrative_cache
+ from openexecutive.people import insights_cache
+
+ narrative_cache.initialize_db(db_path)
+ insights_cache.initialize_db(db_path)
+
+
+def _wipe_derived_caches(db_path: Path) -> dict[str, int]:
+ """Drop every row of the derived per-company caches; return per-table counts.
+
+ The one place the initialize-then-delete pairing is expressed for callers
+ that wipe only these tables. ``reset_all_state`` folds them into its own
+ single DELETE pass instead (it reports per-table counts for the whole
+ episodic DB), but shares ``_initialize_derived_cache_schemas`` above.
+ """
+ _initialize_derived_cache_schemas(db_path)
+ return _delete_all_rows(db_path, PER_CLIENT_CACHE_TABLES)
+
+
def get_fixture_status(settings: Any) -> dict[str, Any]:
"""Lightweight status for the UI: which fixture is active and is there a snapshot?"""
backup_dir = _user_backup_dir(settings)
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 bb0ce633..a8b1bb21 100644
--- a/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
+++ b/packages/core/tests/unit/test_fixture_loader_clears_watchlist.py
@@ -159,27 +159,35 @@ def test_delete_clears_derived_caches_on_a_never_briefed_db(
) -> None:
"""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.
+ Behavioural, and it calls the production helper ``_wipe_derived_caches``
+ itself rather than re-implementing the initialize-then-delete sequence —
+ otherwise deleting the schema init at the call site would leave this test
+ green, and the cold-DB path would have no coverage at all. Exercising
+ ``_apply_state_from_source`` end to end is what this module's docstring
+ rules out (it would drag ChromaDB, Honcho and an ``app.state`` shim into a
+ unit test); the sibling test below pins that the helper is actually called
+ there, unconditionally.
+
+ The cold-DB half is the regression the original fix hit: both caches
+ CREATE TABLE lazily on first put, so a DB that has never served a briefing
+ lacks them, and ``_delete_all_rows`` guards only the DB file, not each
+ table. Removing the init inside ``_wipe_derived_caches`` fails this test.
"""
from openexecutive.briefing import narrative_cache
- from openexecutive.cli.fixture_loader import PER_CLIENT_CACHE_TABLES
+ from openexecutive.cli.fixture_loader import (
+ PER_CLIENT_CACHE_TABLES,
+ _wipe_derived_caches,
+ )
from openexecutive.people import insights_cache
# Cold: neither table exists yet on this DB.
with sqlite3.connect(str(_episodic_db)) as conn:
+ placeholders = ", ".join("?" * len(PER_CLIENT_CACHE_TABLES))
present = {
r[0]
for r in conn.execute(
- "SELECT name FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
+ "SELECT name FROM sqlite_master WHERE type='table' " # noqa: S608
+ f"AND name IN ({placeholders})",
PER_CLIENT_CACHE_TABLES,
)
}
@@ -188,9 +196,7 @@ def test_delete_clears_derived_caches_on_a_never_briefed_db(
"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
+ _wipe_derived_caches(_episodic_db) # must not raise on a cold DB
# Warm: rows written by the outgoing company are actually removed.
narrative_cache.put(
@@ -214,14 +220,14 @@ def test_delete_clears_derived_caches_on_a_never_briefed_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
- _delete_all_rows(_episodic_db, PER_CLIENT_CACHE_TABLES)
+ _wipe_derived_caches(_episodic_db)
assert narrative_cache.get("principal", db_path=_episodic_db) is None
assert insights_cache.get(1, db_path=_episodic_db) is None
-def test_fixture_path_wipes_caches_unconditionally() -> None:
- """The fixture-path wipe must not sit behind ``memory.json``.
+def test_fixture_path_cache_wipe_is_unconditional() -> None:
+ """The fixture-path wipe must not sit behind ``memory.json`` — structurally.
``_seed_episodic_memory`` returns early when the fixture has no
``memory.json``, when that file will not parse, and when the DB is
@@ -230,10 +236,15 @@ def test_fixture_path_wipes_caches_unconditionally() -> None:
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.
+ A substring search for the constant would not catch a regression here: it
+ passes just as happily when the wipe is present but wrapped in an ``if``.
+ So walk the AST and require the wipe to be a *direct* child of the
+ function body — no enclosing conditional, loop, or try. The sibling test
+ above proves the deletion itself works; this one proves it always runs.
"""
+ import ast
+ import textwrap
+
from openexecutive.cli.fixture_loader import (
PER_CLIENT_CACHE_TABLES,
_seed_episodic_memory,
@@ -241,10 +252,35 @@ def test_fixture_path_wipes_caches_unconditionally() -> None:
assert PER_CLIENT_CACHE_TABLES == ("briefing_narrative", "person_insights")
- 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."
+ fn = ast.parse(
+ textwrap.dedent(inspect.getsource(_apply_state_from_source))
+ ).body[0]
+ assert isinstance(fn, ast.AsyncFunctionDef)
+
+ def _wipes(node: ast.AST) -> bool:
+ """True if ``node`` contains a call to the wipe helper."""
+ return any(
+ isinstance(call, ast.Call)
+ and isinstance(call.func, ast.Name)
+ and call.func.id == "_wipe_derived_caches"
+ for call in ast.walk(node)
+ )
+
+ # Only leaf statements count. ``ast.walk`` descends, so testing every
+ # member of ``fn.body`` would also accept a wipe nested inside a top-level
+ # ``if``/``for``/``try`` — precisely the regression this pins against. A
+ # wrapping compound statement is none of these three node types, so
+ # nesting the call makes this assertion fail.
+ assert any(
+ _wipes(stmt)
+ for stmt in fn.body
+ if isinstance(stmt, (ast.Expr, ast.Assign, ast.AnnAssign))
+ ), (
+ "_apply_state_from_source does not call _wipe_derived_caches as a "
+ "top-level statement — either the wipe is gone, or it is nested in a "
+ "conditional. A fixture load whose memory.json is absent or unparseable "
+ "still swaps the company, so a gated wipe leaves the outgoing company's "
+ "briefing narrative to be served 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 "