AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
Remove the talent and staff-onboarding verticals (#116)
Rufusae29b64f0288
diff --git a/.claude/skills/anvil/SKILL.md b/.claude/skills/anvil/SKILL.mdindex 497c7aeb..4d377867 100644--- a/.claude/skills/anvil/SKILL.md+++ b/.claude/skills/anvil/SKILL.md@@ -658,9 +658,9 @@ sections_for() {departments|people|personas|onboarding) echo org;;memory) echo "memory peer_memory";; api) echo "api today";;orchestrator|agents|providers) echo "agents lifecycle review";;- audit) echo audit;; talent) echo talent;;+ audit) echo audit;;monitoring) echo external_monitoring;; mcp_server) echo mcp_server;;- clients|fixtures) echo "clients peer_memory";; staff_onboarding) echo staff_onboarding;;+ clients|fixtures) echo "clients peer_memory";;knowledge) echo rag;; briefing|alerts) echo today;;guide) echo user_guide;; *) echo "";;esac@@ -695,9 +695,9 @@ echo "$SNIP"; [ "$RESULT" = 1 ]```The module→section map is the gate's contract: touching `integrations/` and-editing only `prebuilt/talent.json` FAILS, because the edited section must be-one the module is documented under. When you add a module or a section,-extend `sections_for` in the same PR.+editing only `prebuilt/scheduler.json` FAILS, because the edited section must+be one the module is documented under. When you add or remove a module or a+section, update `sections_for` in the same PR.**On FAIL, you have exactly two honest exits.** Either (a) update the affected`prebuilt/<section>.json` (and the YAML notes), re-stage, and re-run the gate;diff --git a/CHANGELOG.md b/CHANGELOG.mdindex afd6c69e..1fbba832 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Removed+- **Talent / executive search.** The whole vertical is gone: the `talent`+ specialist, `openexecutive/talent/` (engagements, candidates, offers, the+ ChromaDB matching graph), its 21 REST routes, 12 chat tools, 4 MCP tools and+ the `/talent` UI, plus the five recruiting workflows (`candidate_screen`,+ `candidate_outreach`, `interview_coordination`, `reference_check`,+ `offer_approval`). The `chro` specialist and its `comp_refresh` /+ `org_design` / `performance_review` / `exec_search_brief` workflows are+ unchanged — `exec_search_brief` is an advisory hiring brief, not pipeline.+- **Staff onboarding.** `openexecutive/staff_onboarding/` (templates, per-hire+ plans, tasks), its REST routes and 8 chat tools, the `new_hire_onboarding` and+ `role_onboarding` workflows, the `/staff-onboarding` UI, and the+ `onboarding_ramp` / `onboarding_kickoff` / `onboarding_checkin` scheduler+ kinds. **The company-setup wizard (`/onboard`) is untouched** — it is a+ different subsystem that happens to share the word.+- `GET /today` no longer returns the `talent` or `onboarding` fields, and the+ per-turn chat briefing no longer includes their digests.++ Existing SQLite tables (`engagements`, `candidates`, `offers`,+ `onboarding_templates`, `onboarding_plans`, `onboarding_tasks`) are **not+ dropped** — nothing reads them, and a blank client slot still wipes them so+ candidate data cannot cross slots. Pending talent reminders the removed+ workflows had scheduled on the principal's DM channel are cancelled by a+ one-time startup sweep (`cancel_orphaned_talent_reminders`, recorded in the+ new `app_migrations` table); the sweep can be deleted in the release after+ next.+### Added- **Conversational onboarding.** `/onboard` now opens with "tell me about yourcompany" instead of a 12-step form. The user writes a paragraph (and candiff --git a/fixtures/companies/meridian_petroleum/scenarios/meridian_talent_001.yaml b/fixtures/companies/meridian_petroleum/scenarios/meridian_talent_001.yamldeleted file mode 100644index e9abade7..00000000--- a/fixtures/companies/meridian_petroleum/scenarios/meridian_talent_001.yaml+++ /dev/null@@ -1,24 +0,0 @@-id: meridian_talent_001-domain: talent-description: "Executive search screen: principal asks the talent specialist to assess a VP Drilling candidate against a cycle-tested upstream mandate"-company_context:- stage: Private / PE-backed- industry: Oil & Gas — Independent Refining, Crude Trading & Fuels Marketing- headcount: 1400- arr: 3200000000- open_search: VP Drilling- search_must_haves: "10+ yrs upstream operations, led a team through a price-crash downturn, HSE track record, P&L ownership"-query: "We're running the VP Drilling search. Candidate is Dana Cole — 12 years upstream, ran drilling ops at a mid-cap independent through the 2020 crash, owned a $180M capital program, clean HSE record. Screen them against our must-haves: give me a fit score out of 100, the evidence, the single biggest risk, and an advance/pass call. Don't pad the score."-expected_topics:- - candidate_fit_score- - cycle_tested_judgment- - hse_track_record- - biggest_risk_and_probe- - advance_or_pass_recommendation-required_routing:- - talent-quality_criteria:- actionable: true- specific: true- evidence_anchored: true- honest_about_risk: truediff --git a/fixtures/companies/meridian_petroleum/scenarios/meridian_talent_002.yaml b/fixtures/companies/meridian_petroleum/scenarios/meridian_talent_002.yamldeleted file mode 100644index a98f4380..00000000--- a/fixtures/companies/meridian_petroleum/scenarios/meridian_talent_002.yaml+++ /dev/null@@ -1,23 +0,0 @@-id: meridian_talent_002-domain: talent-description: "Talent-market mapping: where to source a Head of Trading Risk for an independent refiner, and how to reach them"-company_context:- stage: Private / PE-backed- industry: Oil & Gas — Independent Refining, Crude Trading & Fuels Marketing- headcount: 1400- arr: 3200000000- open_search: Head of Trading Risk- trading_desk_var_usd: 9500000-query: "We need to open a search for a Head of Trading Risk to sit over the crude desk. Map the talent market for me: what kinds of companies and seats do credible candidates sit in today, what's the trigger that would make them move to a PE-backed independent our size, and is our comp likely to pull the level we need? Be specific about company types, not 'big oil'."-expected_topics:- - talent_market_mapping- - target_company_types- - candidate_move_trigger- - comp_band_realism- - sourcing_approach-required_routing:- - talent-quality_criteria:- actionable: true- specific: true- names_real_entities: truediff --git a/packages/core/openexecutive/agents/talent.py b/packages/core/openexecutive/agents/talent.pydeleted file mode 100644index 29ed2ca6..00000000--- a/packages/core/openexecutive/agents/talent.py+++ /dev/null@@ -1,26 +0,0 @@-from openexecutive.agents.base import BaseAgent-from openexecutive.config import get_settings---class TalentAgent(BaseAgent):- """Talent & Executive Search specialist.-- Screens candidates against a search engagement's must-haves, maps the- talent market for a mandate, and grounds advice in energy-sector hiring- realities. Uses deep reasoning — candidate assessment is a judgment call- that benefits from the extra thinking budget, same as the CFO/strategy- specialists.- """-- name = "talent"- domain = "talent"- use_deep_reasoning = True-- @property- def model(self) -> str: # type: ignore[override]- return get_settings().deep_reasoning_model-- def get_system_prompt(self) -> str:- from openexecutive.prompts.domain_prompts import TALENT_PROMPT-- return TALENT_PROMPTdiff --git a/packages/core/openexecutive/api/main.py b/packages/core/openexecutive/api/main.pyindex 78d6f7d9..91e34f8e 100644--- a/packages/core/openexecutive/api/main.py+++ b/packages/core/openexecutive/api/main.py@@ -40,8 +40,6 @@ from openexecutive.api.routes import (scheduled,sessions,skills,- staff_onboarding,- talent,today,watchlist,workflows,@@ -253,21 +251,21 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:from openexecutive.people.store import initialize_db as initialize_people_dbinitialize_people_db()- # Talent / executive-search core (clients, engagements, candidates).- # Self-contained tables in the same DB; no FK ordering constraint with- # the other subsystems.- from openexecutive.talent.store import initialize_db as initialize_talent_db- initialize_talent_db()-- # Staff-onboarding framework (templates, plans, tasks). Self-contained tables- # in the same DB; no FK ordering constraint with the other subsystems.- from openexecutive.staff_onboarding.store import (- initialize_db as initialize_staff_onboarding_db,- )- initialize_staff_onboarding_db()- # Seed default onboarding templates (idempotent — operator edits are kept).- from openexecutive.staff_onboarding.seed import seed_default_templates- seed_default_templates()+ # One-shot cleanup of reminders the removed talent / staff-onboarding+ # workflows left pending on the principal's DM channel (see the function's+ # docstring for the removal schedule). Runs after `initialize_db()` so the+ # `app_migrations` table exists.+ from openexecutive.memory.episodic import cancel_orphaned_talent_reminders+ try:+ _swept = cancel_orphaned_talent_reminders()+ except Exception:+ # Best-effort data cleanup — a locked DB must not block boot.+ logging.getLogger("openexecutive").exception("orphaned-reminder sweep failed")+ else:+ if _swept:+ logging.getLogger("openexecutive").info(+ "cancelled %d orphaned talent/onboarding reminder(s) on startup", _swept+ )# Departments: persistent state layer over the 8 specialist agents. Init# AFTER episodic_db so the additive ALTERs (department column on decisions,@@ -615,8 +613,6 @@ def create_app() -> FastAPI:app.include_router(audit.router, tags=["audit"])app.include_router(departments.router, tags=["departments"])app.include_router(people.router, tags=["people"])- app.include_router(talent.router, tags=["talent"])- app.include_router(staff_onboarding.router, tags=["staff-onboarding"])app.include_router(today.router, tags=["today"])app.include_router(scheduled.router, tags=["scheduled"])app.include_router(watchlist.router, tags=["watchlist"])diff --git a/packages/core/openexecutive/api/routes/chat.py b/packages/core/openexecutive/api/routes/chat.pyindex 8866c934..6dd3a9cb 100644--- a/packages/core/openexecutive/api/routes/chat.py+++ b/packages/core/openexecutive/api/routes/chat.py@@ -239,22 +239,17 @@ async def _run_chat_turn(return ""async def _do_briefing() -> str:- # Current open-alert digest + open-search digest so the Executive can- # discuss a briefing item the principal clicked or named (the items- # behind the /today "What's going on" narrative) AND the live executive- # searches. Sync SQLite reads off the event loop; both formatters- # swallow their own errors, so this is belt-and-suspenders.+ # Current open-alert digest so the Executive can discuss a briefing item+ # the principal clicked or named (the items behind the /today "What's+ # going on" narrative). Sync SQLite read off the event loop; the+ # formatter swallows its own errors, so this is belt-and-suspenders.from openexecutive.briefing.context import format_open_alerts_for_prompt- from openexecutive.briefing.onboarding_digest import format_onboarding_for_prompt- from openexecutive.briefing.talent_digest import format_talent_for_prompt- # return_exceptions=True so one digest raising never discards the others —+ # return_exceptions=True so a digest raising never discards the others —# each formatter already swallows its own errors, this just guards the# to_thread wrappers themselves.results = await asyncio.gather(asyncio.to_thread(format_open_alerts_for_prompt),- asyncio.to_thread(format_talent_for_prompt),- asyncio.to_thread(format_onboarding_for_prompt),return_exceptions=True,)digests: list[str] = []diff --git a/packages/core/openexecutive/api/routes/staff_onboarding.py b/packages/core/openexecutive/api/routes/staff_onboarding.pydeleted file mode 100644index 64220413..00000000--- a/packages/core/openexecutive/api/routes/staff_onboarding.py+++ /dev/null@@ -1,260 +0,0 @@-"""FastAPI routes for the staff-onboarding framework.--Surfaces CRUD for the three entities — templates (reusable blueprints), plans-(one per hire), and tasks (checklist items) — mirroring the shape of-``api.routes.talent``. All rows live in the shared ``episodic_memory.db`` via-``openexecutive.staff_onboarding.store``.-"""-from __future__ import annotations--import logging--from fastapi import APIRouter, HTTPException, Response, status-from pydantic import BaseModel, Field--from openexecutive.staff_onboarding import service, store-from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingPlan,- OnboardingStatus,- OnboardingTask,- OnboardingTemplate,- TaskSpec,- TaskStatus,-)--logger = logging.getLogger(__name__)--router = APIRouter()--_SHORT_MAX = 200-_LONG_MAX = 8000---# --------------------------------------------------------------------------- #-# Templates-# --------------------------------------------------------------------------- #--class TemplateUpsert(BaseModel):- name: str = Field(min_length=1, max_length=_SHORT_MAX, pattern=r"^[a-z0-9_]+$")- title: str = Field(min_length=1, max_length=_SHORT_MAX)- description: str = Field(default="", max_length=_LONG_MAX)- department: str = Field(default="", max_length=_SHORT_MAX)- ramp_days: int = Field(default=0, ge=0, le=90)- checkin_cadence: str = Field(default="", max_length=_SHORT_MAX)- task_specs: list[TaskSpec] = Field(default_factory=list)- brief_sections: list[str] = Field(default_factory=list)- is_active: bool = True-- def to_template(self) -> OnboardingTemplate:- """Build the domain model from the request body (fields are 1:1; the- store stamps created_at/updated_at)."""- return OnboardingTemplate(**self.model_dump())--[email protected]("/onboarding-templates", response_model=list[OnboardingTemplate])-def list_templates(active_only: bool = True) -> list[OnboardingTemplate]:- return store.list_templates(active_only=active_only)--[email protected]("/onboarding-templates/{name}", response_model=OnboardingTemplate)-def get_template(name: str) -> OnboardingTemplate:- template = store.get_template(name)- if template is None:- raise HTTPException(status_code=404, detail="Template not found")- return template--[email protected]("/onboarding-templates/{name}", response_model=OnboardingTemplate)-def upsert_template(name: str, body: TemplateUpsert) -> OnboardingTemplate:- if body.name != name:- raise HTTPException(status_code=400, detail="Body name must match path name")- store.upsert_template(body.to_template())- saved = store.get_template(name)- if saved is None:- raise HTTPException(status_code=500, detail="Template vanished after save")- return saved--[email protected]("/onboarding-templates/{name}", status_code=status.HTTP_204_NO_CONTENT)-def delete_template(name: str) -> Response:- if not store.delete_template(name):- raise HTTPException(status_code=404, detail="Template not found")- return Response(status_code=status.HTTP_204_NO_CONTENT)---# --------------------------------------------------------------------------- #-# Plans-# --------------------------------------------------------------------------- #--class PlanCreate(BaseModel):- full_name: str = Field(min_length=1, max_length=_SHORT_MAX)- start_date: str = Field(min_length=1, max_length=_SHORT_MAX)- role: str = Field(default="", max_length=_SHORT_MAX)- template_name: str = Field(default="", max_length=_SHORT_MAX)- person_id: int | None = None- manager_person_id: int | None = None- buddy_person_id: int | None = None- engagement_id: int | None = None- candidate_id: int | None = None---class PlanPatch(BaseModel):- person_id: int | None = None- manager_person_id: int | None = None- buddy_person_id: int | None = None- status: OnboardingStatus | None = None- current_phase: OnboardingPhase | None = None--[email protected]("/onboarding-plans", response_model=list[OnboardingPlan])-def list_plans(- status: OnboardingStatus | None = None, include_archived: bool = False-) -> list[OnboardingPlan]:- return store.list_plans(status=status, include_archived=include_archived)--[email protected]("/onboarding-plans/{plan_id}", response_model=OnboardingPlan)-def get_plan(plan_id: int) -> OnboardingPlan:- plan = store.get_plan(plan_id)- if plan is None:- raise HTTPException(status_code=404, detail="Plan not found")- return plan--- "/onboarding-plans", response_model=OnboardingPlan, status_code=status.HTTP_201_CREATED-)-def create_plan(body: PlanCreate) -> OnboardingPlan:- """Create a plan, instantiating tasks from the named template when given."""- template: OnboardingTemplate | None = None- if body.template_name:- template = store.get_template(body.template_name)- if template is None:- raise HTTPException(- status_code=404, detail=f"Template {body.template_name!r} not found"- )- plan_id = service.instantiate_plan(- full_name=body.full_name,- start_date=body.start_date,- role=body.role,- template=template,- person_id=body.person_id,- manager_person_id=body.manager_person_id,- buddy_person_id=body.buddy_person_id,- engagement_id=body.engagement_id,- candidate_id=body.candidate_id,- )- plan = store.get_plan(plan_id)- if plan is None:- raise HTTPException(status_code=500, detail="Plan vanished after insert")- return plan--[email protected]("/onboarding-plans/{plan_id}", response_model=OnboardingPlan)-def patch_plan(plan_id: int, body: PlanPatch) -> OnboardingPlan:- if store.get_plan(plan_id) is None:- raise HTTPException(status_code=404, detail="Plan not found")- store.update_plan(- plan_id,- person_id=body.person_id,- manager_person_id=body.manager_person_id,- buddy_person_id=body.buddy_person_id,- status=body.status,- current_phase=body.current_phase,- )- updated = store.get_plan(plan_id)- if updated is None:- raise HTTPException(status_code=500, detail="Plan vanished")- return updated--[email protected]("/onboarding-plans/{plan_id}/advance", response_model=OnboardingPlan)-def advance_plan(plan_id: int) -> OnboardingPlan:- if store.get_plan(plan_id) is None:- raise HTTPException(status_code=404, detail="Plan not found")- service.advance_phase(plan_id)- updated = store.get_plan(plan_id)- if updated is None:- raise HTTPException(status_code=500, detail="Plan vanished")- return updated--[email protected]("/onboarding-plans/{plan_id}/activate", response_model=OnboardingPlan)-def activate_plan(plan_id: int) -> OnboardingPlan:- """Activate a plan (status → active) and enqueue its ramp drip. The drip- only fires once the plan has a roster person_id + generated ramp segments."""- if store.get_plan(plan_id) is None:- raise HTTPException(status_code=404, detail="Plan not found")- service.activate_plan(plan_id)- updated = store.get_plan(plan_id)- if updated is None:- raise HTTPException(status_code=500, detail="Plan vanished")- return updated--[email protected]("/onboarding-plans/{plan_id}/archive", status_code=status.HTTP_204_NO_CONTENT)-def archive_plan(plan_id: int) -> Response:- if store.get_plan(plan_id) is None:- raise HTTPException(status_code=404, detail="Plan not found")- store.archive_plan(plan_id)- return Response(status_code=status.HTTP_204_NO_CONTENT)---# --------------------------------------------------------------------------- #-# Tasks-# --------------------------------------------------------------------------- #--class TaskCreate(BaseModel):- title: str = Field(min_length=1, max_length=_SHORT_MAX)- phase: OnboardingPhase = OnboardingPhase.WEEK_1- category: str = Field(default="general", max_length=_SHORT_MAX)- owner_person_id: int | None = None- due_date: str | None = Field(default=None, max_length=_SHORT_MAX)---class TaskStatusPatch(BaseModel):- status: TaskStatus- completed_by_person_id: int | None = None--- "/onboarding-plans/{plan_id}/tasks",- response_model=OnboardingTask,- status_code=status.HTTP_201_CREATED,-)-def add_task(plan_id: int, body: TaskCreate) -> OnboardingTask:- if store.get_plan(plan_id) is None:- raise HTTPException(status_code=404, detail="Plan not found")- task_id = store.add_task(- plan_id=plan_id,- title=body.title,- phase=body.phase,- category=body.category,- owner_person_id=body.owner_person_id,- due_date=body.due_date,- )- task = store.get_task(task_id)- if task is None:- raise HTTPException(status_code=500, detail="Task vanished after insert")- return task--[email protected]("/onboarding-tasks/{task_id}/status", response_model=OnboardingTask)-def set_task_status(task_id: int, body: TaskStatusPatch) -> OnboardingTask:- if store.get_task(task_id) is None:- raise HTTPException(status_code=404, detail="Task not found")- store.set_task_status(- task_id, body.status, completed_by_person_id=body.completed_by_person_id- )- updated = store.get_task(task_id)- if updated is None:- raise HTTPException(status_code=500, detail="Task vanished")- return updated--[email protected]("/onboarding-tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT)-def delete_task(task_id: int) -> Response:- if not store.delete_task(task_id):- raise HTTPException(status_code=404, detail="Task not found")- return Response(status_code=status.HTTP_204_NO_CONTENT)diff --git a/packages/core/openexecutive/api/routes/talent.py b/packages/core/openexecutive/api/routes/talent.pydeleted file mode 100644index 51488139..00000000--- a/packages/core/openexecutive/api/routes/talent.py+++ /dev/null@@ -1,495 +0,0 @@-"""FastAPI routes for the talent / executive-search core.--Surfaces CRUD for the two entities — engagements (searches we're hiring for in-this company) and candidates — mirroring the shape of ``api.routes.people``. All-rows live in the shared ``episodic_memory.db`` via ``openexecutive.talent.store``.-"""-from __future__ import annotations--import logging-from typing import Any--from fastapi import APIRouter, HTTPException, Request, Response, status-from pydantic import BaseModel, Field--from openexecutive.talent import graph as talent_graph-from openexecutive.talent import offers as talent_offers-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import (- Candidate,- CandidateStage,- Engagement,- EngagementStatus,- Offer,- OfferStatus,-)--logger = logging.getLogger(__name__)--router = APIRouter()---def _get_store(request: Request): # type: ignore[return]- """Resolve the warm ChromaDB store from app state, else build one.-- Mirrors ``api.routes.knowledge._get_store`` so the talent graph reuses the- single in-process vector store the rest of the app shares.- """- if hasattr(request.app.state, "store"):- return request.app.state.store- from openexecutive.config import get_settings- from openexecutive.knowledge.store import ChromaDBStore-- return ChromaDBStore(persist_directory=get_settings().vector_store_path)--# Field length bounds. Short = names/titles/locations/comp bands/department;-# long = role descriptions, must-haves, and candidate notes that may carry a-# pasted CV blurb.-_SHORT_MAX = 200-_LONG_MAX = 8000---# --------------------------------------------------------------------------- #-# Request bodies-# --------------------------------------------------------------------------- #--class EngagementCreate(BaseModel):- role_title: str = Field(min_length=1, max_length=_SHORT_MAX)- department: str = Field(default="", max_length=_SHORT_MAX)- status: EngagementStatus = EngagementStatus.OPEN- location: str = Field(default="", max_length=_SHORT_MAX)- comp_band: str = Field(default="", max_length=_SHORT_MAX)- must_haves: str = Field(default="", max_length=_LONG_MAX)- description: str = Field(default="", max_length=_LONG_MAX)---class EngagementPatch(BaseModel):- role_title: str | None = Field(default=None, min_length=1, max_length=_SHORT_MAX)- department: str | None = Field(default=None, max_length=_SHORT_MAX)- status: EngagementStatus | None = None- location: str | None = Field(default=None, max_length=_SHORT_MAX)- comp_band: str | None = Field(default=None, max_length=_SHORT_MAX)- must_haves: str | None = Field(default=None, max_length=_LONG_MAX)- description: str | None = Field(default=None, max_length=_LONG_MAX)---class CandidateCreate(BaseModel):- engagement_id: int- full_name: str = Field(min_length=1, max_length=_SHORT_MAX)- current_title: str = Field(default="", max_length=_SHORT_MAX)- current_company: str = Field(default="", max_length=_SHORT_MAX)- location: str = Field(default="", max_length=_SHORT_MAX)- email: str | None = None- linkedin_url: str | None = None- source: str = Field(default="", max_length=_SHORT_MAX)- stage: CandidateStage = CandidateStage.LEAD- notes: str = Field(default="", max_length=_LONG_MAX)---class CandidatePatch(BaseModel):- full_name: str | None = Field(default=None, min_length=1, max_length=_SHORT_MAX)- current_title: str | None = Field(default=None, max_length=_SHORT_MAX)- current_company: str | None = Field(default=None, max_length=_SHORT_MAX)- location: str | None = Field(default=None, max_length=_SHORT_MAX)- email: str | None = None- linkedin_url: str | None = None- source: str | None = Field(default=None, max_length=_SHORT_MAX)- notes: str | None = Field(default=None, max_length=_LONG_MAX)---class StagePatch(BaseModel):- stage: CandidateStage---class OfferCreate(BaseModel):- candidate_id: int- comp_summary: str = Field(min_length=1, max_length=_LONG_MAX)- note: str = Field(default="", max_length=_LONG_MAX)---class OfferPatch(BaseModel):- comp_summary: str | None = Field(default=None, min_length=1, max_length=_LONG_MAX)- note: str | None = Field(default=None, max_length=_LONG_MAX)---class OfferExtend(BaseModel):- expires_at: str | None = None- expires_in_days: int = Field(default=7, ge=1, le=60)- note: str | None = Field(default=None, max_length=_LONG_MAX)---class OfferDecision(BaseModel):- decision: OfferStatus- note: str | None = Field(default=None, max_length=_LONG_MAX)---# --------------------------------------------------------------------------- #-# Engagements-# --------------------------------------------------------------------------- #-[email protected]("/engagements", response_model=list[Engagement])-def list_engagements(include_archived: bool = False) -> list[Engagement]:- return talent_store.list_engagements(include_archived=include_archived)--[email protected]("/engagements/{engagement_id}", response_model=Engagement)-def get_engagement(engagement_id: int) -> Engagement:- engagement = talent_store.get_engagement(engagement_id)- if engagement is None:- raise HTTPException(status_code=404, detail="Engagement not found")- return engagement--- "/engagements", response_model=Engagement, status_code=status.HTTP_201_CREATED-)-def create_engagement(body: EngagementCreate) -> Engagement:- eid = talent_store.upsert_engagement(- role_title=body.role_title,- department=body.department,- status=body.status,- location=body.location,- comp_band=body.comp_band,- must_haves=body.must_haves,- description=body.description,- )- engagement = talent_store.get_engagement(eid)- if engagement is None:- raise HTTPException(status_code=500, detail="Engagement vanished after insert")- return engagement--[email protected]("/engagements/{engagement_id}", response_model=Engagement)-def patch_engagement(engagement_id: int, body: EngagementPatch) -> Engagement:- current = talent_store.get_engagement(engagement_id)- if current is None:- raise HTTPException(status_code=404, detail="Engagement not found")- # All engagement columns are NOT NULL; an omitted OR explicitly-null field- # keeps the current value.- talent_store.upsert_engagement(- role_title=body.role_title if body.role_title is not None else current.role_title,- department=body.department if body.department is not None else current.department,- status=body.status if body.status is not None else current.status,- location=body.location if body.location is not None else current.location,- comp_band=body.comp_band if body.comp_band is not None else current.comp_band,- must_haves=body.must_haves if body.must_haves is not None else current.must_haves,- description=(- body.description if body.description is not None else current.description- ),- engagement_id=engagement_id,- )- updated = talent_store.get_engagement(engagement_id)- if updated is None:- raise HTTPException(status_code=500, detail="Engagement vanished")- return updated--- "/engagements/{engagement_id}/archive", status_code=status.HTTP_204_NO_CONTENT-)-def archive_engagement(engagement_id: int) -> Response:- if talent_store.get_engagement(engagement_id) is None:- raise HTTPException(status_code=404, detail="Engagement not found")- talent_store.archive_engagement(engagement_id)- return Response(status_code=status.HTTP_204_NO_CONTENT)---# --------------------------------------------------------------------------- #-# Candidates-# --------------------------------------------------------------------------- #-[email protected]("/candidates", response_model=list[Candidate])-def list_candidates(- engagement_id: int | None = None,- stage: CandidateStage | None = None,- include_archived: bool = False,-) -> list[Candidate]:- return talent_store.list_candidates(- engagement_id=engagement_id, stage=stage, include_archived=include_archived- )--[email protected]("/candidates/{candidate_id}", response_model=Candidate)-def get_candidate(candidate_id: int) -> Candidate:- candidate = talent_store.get_candidate(candidate_id)- if candidate is None:- raise HTTPException(status_code=404, detail="Candidate not found")- return candidate--- "/candidates", response_model=Candidate, status_code=status.HTTP_201_CREATED-)-def create_candidate(body: CandidateCreate, request: Request) -> Candidate:- if talent_store.get_engagement(body.engagement_id) is None:- raise HTTPException(- status_code=404, detail=f"Engagement {body.engagement_id} not found"- )- cid = talent_store.upsert_candidate(- engagement_id=body.engagement_id,- full_name=body.full_name,- current_title=body.current_title,- current_company=body.current_company,- location=body.location,- email=body.email,- linkedin_url=body.linkedin_url,- source=body.source,- stage=body.stage,- notes=body.notes,- )- candidate = talent_store.get_candidate(cid)- if candidate is None:- raise HTTPException(status_code=500, detail="Candidate vanished after insert")- talent_graph.index_candidate(candidate, _get_store(request))- return candidate--[email protected]("/candidates/{candidate_id}", response_model=Candidate)-def patch_candidate(candidate_id: int, body: CandidatePatch, request: Request) -> Candidate:- current = talent_store.get_candidate(candidate_id)- if current is None:- raise HTTPException(status_code=404, detail="Candidate not found")- # NOT NULL columns keep their current value on omit/null. Only `email` and- # `linkedin_url` are nullable in the schema, so for those an explicit JSON- # null clears the field while an omitted field is preserved — distinguished- # via the exclude_unset key set. `stage` is intentionally not patchable- # here — use POST /candidates/{id}/stage.- provided = body.model_dump(exclude_unset=True)- talent_store.upsert_candidate(- engagement_id=current.engagement_id,- full_name=body.full_name if body.full_name is not None else current.full_name,- current_title=(- body.current_title if body.current_title is not None else current.current_title- ),- current_company=(- body.current_company- if body.current_company is not None- else current.current_company- ),- location=body.location if body.location is not None else current.location,- email=provided.get("email", current.email),- linkedin_url=provided.get("linkedin_url", current.linkedin_url),- source=body.source if body.source is not None else current.source,- stage=current.stage,- notes=body.notes if body.notes is not None else current.notes,- candidate_id=candidate_id,- )- updated = talent_store.get_candidate(candidate_id)- if updated is None:- raise HTTPException(status_code=500, detail="Candidate vanished")- talent_graph.index_candidate(updated, _get_store(request))- return updated--[email protected]("/candidates/{candidate_id}/stage", response_model=Candidate)-def set_candidate_stage(candidate_id: int, body: StagePatch, request: Request) -> Candidate:- if talent_store.get_candidate(candidate_id) is None:- raise HTTPException(status_code=404, detail="Candidate not found")- talent_store.set_candidate_stage(candidate_id, body.stage)- updated = talent_store.get_candidate(candidate_id)- if updated is None:- raise HTTPException(status_code=500, detail="Candidate vanished")- talent_graph.index_candidate(updated, _get_store(request))- return updated--[email protected]("/candidates/{candidate_id}/archive", status_code=status.HTTP_204_NO_CONTENT)-def archive_candidate(candidate_id: int, request: Request) -> Response:- if talent_store.get_candidate(candidate_id) is None:- raise HTTPException(status_code=404, detail="Candidate not found")- talent_store.archive_candidate(candidate_id)- talent_graph.remove_candidate(candidate_id, _get_store(request))- return Response(status_code=status.HTTP_204_NO_CONTENT)---# --------------------------------------------------------------------------- #-# Offers-# --------------------------------------------------------------------------- #--# Maps OfferActionError codes to HTTP statuses. Lifecycle conflicts are 409s;-# a malformed expiry is the caller's input problem (400).-_OFFER_ERROR_STATUS = {- "not_found": 404,- "bad_expiry": 400,- "bad_status": 409,- "bad_transition": 409,- "approval_rejected": 409,- "approval_pending": 409,-}---def _offer_http_error(exc: talent_offers.OfferActionError) -> HTTPException:- return HTTPException(- status_code=_OFFER_ERROR_STATUS.get(exc.code, 400), detail=exc.message- )---class OfferActionResponse(BaseModel):- """An offer action's outcome: the offer plus what else happened."""-- offer: Offer- approval_state: str = "none"- nudges_scheduled: int = 0- cancelled_nudges: int = 0- side_effects: list[str] = Field(default_factory=list)- warnings: list[str] = Field(default_factory=list)--[email protected]("/offers", response_model=list[Offer])-def list_offers(- candidate_id: int | None = None,- engagement_id: int | None = None,- status: OfferStatus | None = None,- include_archived: bool = False,-) -> list[Offer]:- return talent_store.list_offers(- candidate_id=candidate_id,- engagement_id=engagement_id,- status=status,- include_archived=include_archived,- )--[email protected]("/offers/{offer_id}", response_model=Offer)-def get_offer(offer_id: int) -> Offer:- offer = talent_store.get_offer(offer_id)- if offer is None:- raise HTTPException(status_code=404, detail="Offer not found")- return offer--[email protected]("/offers", response_model=Offer, status_code=status.HTTP_201_CREATED)-def create_offer(body: OfferCreate) -> Offer:- candidate = talent_store.get_candidate(body.candidate_id)- if candidate is None:- raise HTTPException(- status_code=404, detail=f"Candidate {body.candidate_id} not found"- )- try:- oid = talent_store.create_offer(- candidate_id=body.candidate_id,- engagement_id=candidate.engagement_id,- comp_summary=body.comp_summary,- note=body.note,- )- except ValueError as exc:- # One open offer per candidate.- raise HTTPException(status_code=409, detail=str(exc)) from exc- offer = talent_store.get_offer(oid)- if offer is None:- raise HTTPException(status_code=500, detail="Offer vanished after insert")- return offer--[email protected]("/offers/{offer_id}", response_model=Offer)-def patch_offer(offer_id: int, body: OfferPatch) -> Offer:- current = talent_store.get_offer(offer_id)- if current is None:- raise HTTPException(status_code=404, detail="Offer not found")- if current.status not in (OfferStatus.DRAFT, OfferStatus.PENDING_APPROVAL):- raise HTTPException(- status_code=409,- detail=(- f"Offer is {current.status.value}; terms are only editable while "- "draft/pending_approval"- ),- )- talent_store.update_offer_terms(- offer_id, comp_summary=body.comp_summary, note=body.note- )- updated = talent_store.get_offer(offer_id)- if updated is None:- raise HTTPException(status_code=500, detail="Offer vanished")- return updated--[email protected]("/offers/{offer_id}/extend", response_model=OfferActionResponse)-def extend_offer(offer_id: int, body: OfferExtend) -> OfferActionResponse:- """Mark the offer extended (the principal sent it) and schedule expiry nudges."""- try:- result = talent_offers.extend_offer(- offer_id,- expires_at=body.expires_at,- expires_in_days=body.expires_in_days,- note=body.note,- )- except talent_offers.OfferActionError as exc:- raise _offer_http_error(exc) from exc- return OfferActionResponse(- offer=result.offer,- approval_state=result.approval_state,- nudges_scheduled=len(result.nudge_action_ids),- warnings=result.warnings,- )--[email protected]("/offers/{offer_id}/decision", response_model=OfferActionResponse)-def record_offer_decision(offer_id: int, body: OfferDecision) -> OfferActionResponse:- """Record the offer's terminal outcome; 'accepted' places the candidate."""- try:- result = talent_offers.record_offer_decision(- offer_id, body.decision, note=body.note- )- except talent_offers.OfferActionError as exc:- raise _offer_http_error(exc) from exc- return OfferActionResponse(- offer=result.offer,- cancelled_nudges=result.cancelled_nudges,- side_effects=result.side_effects,- )--[email protected]("/offers/{offer_id}/archive", status_code=status.HTTP_204_NO_CONTENT)-def archive_offer(offer_id: int) -> Response:- if talent_store.get_offer(offer_id) is None:- raise HTTPException(status_code=404, detail="Offer not found")- talent_store.archive_offer(offer_id)- return Response(status_code=status.HTTP_204_NO_CONTENT)---# --------------------------------------------------------------------------- #-# Talent graph — semantic matching-# --------------------------------------------------------------------------- #--class CandidateMatch(BaseModel):- candidate_id: int- engagement_id: int- stage: str- score: float---class ReindexResult(BaseModel):- indexed: int--[email protected]("/engagements/{engagement_id}/matches", response_model=list[CandidateMatch])-def match_candidates(- engagement_id: int, request: Request, limit: int = 10-) -> list[dict[str, Any]]:- """Rank the candidate pool against this engagement's role + must-haves."""- engagement = talent_store.get_engagement(engagement_id)- if engagement is None:- raise HTTPException(status_code=404, detail="Engagement not found")- return talent_graph.match_candidates_for_engagement(- engagement, _get_store(request), limit=limit- )--[email protected]("/candidates/{candidate_id}/similar", response_model=list[CandidateMatch])-def similar_candidates(- candidate_id: int, request: Request, limit: int = 5-) -> list[dict[str, Any]]:- """Find candidates whose profile is closest to this one (self excluded)."""- candidate = talent_store.get_candidate(candidate_id)- if candidate is None:- raise HTTPException(status_code=404, detail="Candidate not found")- return talent_graph.find_similar_candidates(- candidate, _get_store(request), limit=limit- )--[email protected]("/talent/reindex", response_model=ReindexResult)-def reindex_talent(request: Request) -> ReindexResult:- """Rebuild the talent index from the store (upsert active, drop archived)."""- indexed = talent_graph.reindex_all(_get_store(request))- return ReindexResult(indexed=indexed)diff --git a/packages/core/openexecutive/api/routes/today.py b/packages/core/openexecutive/api/routes/today.pyindex d9eacc3a..d80bb0c3 100644--- a/packages/core/openexecutive/api/routes/today.py+++ b/packages/core/openexecutive/api/routes/today.py@@ -28,11 +28,6 @@ from typing import TYPE_CHECKING, Anyfrom fastapi import APIRouter, BackgroundTasks, HTTPException, Query, Request, Responsefrom pydantic import BaseModel, Field-from openexecutive.briefing.onboarding_digest import (- OnboardingBriefItem,- build_onboarding_brief_items,-)-from openexecutive.briefing.talent_digest import TalentBriefItem, build_talent_brief_itemsfrom openexecutive.clients.cockpit import ClientCockpitCard, format_practice_for_todayif TYPE_CHECKING:@@ -394,13 +389,6 @@ class TodayResponse(BaseModel):# and people we're awaiting a reply from. Both additive, default empty.in_flight: list[InFlightItem] = []awaiting: list[AwaitingItem] = []- # Active executive-search engagements rolled up by pipeline stage, so the- # briefing surfaces talent the same way it surfaces departments and- # proposals. Additive, default empty (no talent data ⇒ no section).- talent: list[TalentBriefItem] = []- # New hires currently onboarding, rolled up by progress. Additive, default- # empty (no onboarding plans ⇒ no section).- onboarding: list[OnboardingBriefItem] = []# Multi-client practice mode only (2+ client slots): rollup cards for the# PARKED clients — overdue follow-ups, awaiting replies, renewals — so the# operator sees the whole practice from the active client's brief.@@ -815,14 +803,6 @@ def _build_today(response.in_flight = in_flight_itemsresponse.awaiting = awaiting_items- # Active executive-search engagements, rolled up by pipeline stage. The- # helper swallows its own errors (returns []), so a talent-store hiccup or a- # fresh install with no talent tables never breaks the brief.- response.talent = build_talent_brief_items()-- # New hires currently onboarding. Same swallow-errors contract as talent.- response.onboarding = build_onboarding_brief_items()-# Parked clients in multi-client practice mode. The helper returns [] for# single-company installs (0–1 slots) and swallows its own errors.from openexecutive.config import get_settings as _get_settingsdiff --git a/packages/core/openexecutive/architecture/architecture-facts.yaml b/packages/core/openexecutive/architecture/architecture-facts.yamlindex cb012520..5933bc77 100644--- a/packages/core/openexecutive/architecture/architecture-facts.yaml+++ b/packages/core/openexecutive/architecture/architecture-facts.yaml@@ -814,6 +814,7 @@ memory:- initiatives- advice_given- scheduled_actions+ - "app_migrations — one-shot data migrations (name PK, applied_at). Schema DDL stays idempotent and is NOT recorded here; only sweeps that must run exactly once per DB insert a row. First user is `cancel_orphaned_talent_reminders` (2026-09), deletable in the release after next."formatter: openexecutive.memory.episodic.format_for_prompt — produces a compact prompt block of recent decisions/initiatives.session_scoping: |Decisions and advice rows carry a session_id so per-thread continuity@@ -1303,7 +1304,16 @@ scheduler:through whichever channel was specified when the row was enqueued —`telegram`, `slack_dm`, `discord_dm`, `email` (requires MCP gatewayfor Gmail), or `__internal__` (bypasses outbound dispatch; used for- workflow steps and the nudge_scan heartbeat). Department-scoped+ workflow steps and the nudge_scan heartbeat). Rows a REMOVED feature+ left pending drain two ways: `__internal__` kinds (the old+ `onboarding_ramp` / `onboarding_kickoff` / `onboarding_checkin`) fall+ through the generic short-circuit — marked done, logged once, no+ dispatch; but the removed talent workflows scheduled `ad_hoc`+ reminders on the principal's REAL DM channel, which the short-circuit+ never sees, so `memory.episodic.cancel_orphaned_talent_reminders`+ cancels them by intent-text prefix at API startup and on slot schema+ init, bounded by an `app_migrations` marker row (runs once per DB).+ Department-scopedactions pass through the authority gate first(`departments.authority.gate_action`), which can `propose` (route toan approver via alert, not dispatched), `escalate` (alert + dispatch),@@ -1346,7 +1356,7 @@ scheduler:today:module: openexecutive.api.routes.todayendpoints:- - "GET /today — JSON aggregation. Returns TodayResponse(departments, people, proposals, narrative, in_flight, awaiting, talent, caller_person_id). `departments` rolls up each department's goal counts (total, at_risk, off_track) and awaiting workflow count, PLUS `attention_goals` — the actual off_track/at_risk Goal rows themselves (worst first, capped at 3), each carrying `key_result`, `current`, `target`, and `status`, so the briefing's Department card is insightful at rest (shows which goal is off and how far) instead of a count you must click into; empty for healthy/inactive departments and additive (older clients ignore it). `people` is an attention-ranked roster: each person carries the original preferred channel, awaiting-action count and soonest SLA PLUS enrichment signals — `status` (on_leave | needs_reply | awaiting | clear), `awaiting_reply_count`/`oldest_awaiting_reply_at` (open scheduled_action commitments we're waiting on THEM to answer, mirroring the nudge engine's awaiting_response_since set), `on_leave_until`, `reachable_now`/`next_window_at` (from people.channel availability windows), `authority_scope`, `department_slugs`, `last_contact_at` (most recent done outbound assigned to them), `overdue` (any SLA or awaited reply past deadline), `priority` (server sort key — overdue replies/work float to top, on-leave sinks), and `insight` (a one-line utility-fast note, see people.insights — null until the background cache warms). Rows are returned sorted by (-priority, full_name). `proposals` is the org-wide set of ALL unread alerts (workflow approvals, triage-classified inbound, Executive-created operational signals, and research artifacts the Executive flagged for review via `draft_artifact` — source=`artifact`, tagged `artifact`, which the UI renders as a Markdown document card rather than a terse proposal — and which also persist into the dedicated Artifacts section (`/artifacts`) so they remain browsable after they leave this unread queue — anything in the alerts table with status='unread'); the UI splits it into 'mine' vs 'across the team' using `caller_person_id` plus a 'principal owns unrouted' rule (alerts with `routed_to_person_id == null` fall to the principal's queue by default). Each proposal also carries presentation signals from `openexecutive.briefing.ranking`: `score` (attention sort key — severity-weighted, with a bonus for routed alerts) and `category` ('action' = a human should look, vs 'monitoring' = passive watchlist/external signals that are unrouted and not high/urgent), plus `surfaced_reason` (a short human note, null for most items) — set only when an external/watchlist signal was pulled into the 'action' lane *by its severity* (the high/urgent escape hatch in `categorize`, e.g. a ≥5% stock move), so the UI can render a per-item explanation of why a normally-Monitoring signal is in 'Needs you'. A proposal also carries `decision_instance_id` (parsed from a `decision_instance:{id}` topic tag), non-null only for gated calendar bookings surfaced from the decision ledger (source=`decision_scheduling`); the UI routes those cards' Approve/Reject to the /decisions endpoints (which book or cancel server-side and clear this alert) instead of the ack-and-hand-off-to-chat flow, so meeting bookings are reviewed in the briefing itself (the standalone proposals page was removed). `_build_today` sorts action items first (by score), monitoring last; the UI collapses the 'monitoring' tail into a separate section so it stops crowding the 'Needs you' queue. `narrative` is a PER-VIEWER Executive-voice 'what's going on' header (see `openexecutive.briefing.narrative` + `today._attach_narrative`). It is a SYNTHESIS, not a re-list: the actionable items render as cards below it, so the narrative gives the connective tissue a list can't (how items relate, what's most urgent and why, the single recommended focus) and deliberately does NOT enumerate a 'Needs you' section that would duplicate the cards. The principal and any unrostered/unresolved caller get the whole-company synthesis (cache scope `principal`) over ALL action-category proposals (mine + across the team; monitoring/watchlist noise is excluded) plus company-wide at-risk depts + activity; each non-principal teammate gets a role-scoped synthesis (cache scope `person:<id>`) over ONLY the action items routed to them + their departments' goal health + their department activity, written in their perspective. Synthesized by `synthesize_briefing_narrative`, which also produces the standalone morning_brief DM but via a DIFFERENT prompt (`standalone=True` → an enumerated brief with a 'Needs you' section, since the DM has no cards beside it to carry the list; the EoD digest still has its own prompt); the /today header path uses the synthesis prompt and never re-lists. Served from the per-scope `briefing_narrative` cache (`openexecutive.briefing.narrative_cache`, keyed by a hash of the viewer's scoped state + scope + UTC date + `NARRATIVE_PROMPT_VERSION`, the last so a prompt rewrite invalidates every cached narrative on the next view). Served from cache on the hot path and regenerated per-viewer in a FastAPI BackgroundTask when that viewer's hash moves; null on a cold cache. `in_flight` is the Executive's upcoming user-facing commitments — pending scheduled_actions (follow-ups, nudges) from `episodic.list_pending_scheduled_actions` (excludes the `__internal__` channel and `nudge_scan` heartbeat, the same set the activity feed hides), each with the resolved recipient `target` (person name via the shared channel→name lookup, or department/raw ref), `kind`, `run_at`, and `overdue` (run_at already passed). `awaiting` is the people we're waiting on a reply from, derived from the same open-commitment set behind each person's `awaiting_reply_count` (name, role, count, oldest_at, overdue), sorted most-overdue/oldest first. Together they power the briefing's 'In flight' section so cross-team work in progress is visible without opening the Scheduled Actions page. Both are additive and default to empty. `talent` is the active executive-search pipeline rolled up by `openexecutive.briefing.talent_digest.build_talent_brief_items` — one `TalentBriefItem` per non-terminal engagement (FILLED/CANCELLED dropped), carrying role_title, department, status, candidate_count, `stage_counts` (per-CandidateStage counts), and four attention signals (`offers_expiring_soon` = EXTENDED offers whose expires_at is within 72h or already past with no decision recorded — computed straight from the offers table so a missed nudge can't make it stale, `needs_screening` = leads, `offers_out` = offers, `stalled_count` = active-stage candidates not updated in ≥7 days), sorted expiring→offers→stalled→leads→size. It renders as the briefing's 'Executive search' card (one per search, click-to-discuss → chat) and feeds the narrative (a search going cold or an offer landing re-writes the header — the narrative hash now folds a talent fingerprint of [engagement_id, needs_screening, offers_out, stalled_count]). The same digest's `format_talent_for_prompt` is appended to the chat `<briefing>` user-turn block (alongside the open-alert digest) so the Executive can discuss live searches by client/role. Additive, default empty (no talent tables ⇒ empty, never an error). `caller_person_id` is the signed-in caller resolved from `x-caller-email` via chat._resolve_caller_person_id; null when no caller could be resolved (unrostered signed-in user, or a CLI hit without the header). The route is async: it serves insight notes from the person_insights cache and, after resolving the caller, attaches the viewer-scoped narrative via `_attach_narrative`, scheduling regeneration of stale entries as FastAPI BackgroundTasks so the request never blocks on an LLM call. `_build_today()` stays synchronous and caller-agnostic — no insight regen and NO narrative (that is attached per-viewer by the endpoints) — for the morning_brief workflow and the deprecated /morning-brief alias that call it directly; the alias resolves the caller and serves the cached narrative but cannot schedule a regen."+ - "GET /today — JSON aggregation. Returns TodayResponse(departments, people, proposals, narrative, in_flight, awaiting, caller_person_id). `departments` rolls up each department's goal counts (total, at_risk, off_track) and awaiting workflow count, PLUS `attention_goals` — the actual off_track/at_risk Goal rows themselves (worst first, capped at 3), each carrying `key_result`, `current`, `target`, and `status`, so the briefing's Department card is insightful at rest (shows which goal is off and how far) instead of a count you must click into; empty for healthy/inactive departments and additive (older clients ignore it). `people` is an attention-ranked roster: each person carries the original preferred channel, awaiting-action count and soonest SLA PLUS enrichment signals — `status` (on_leave | needs_reply | awaiting | clear), `awaiting_reply_count`/`oldest_awaiting_reply_at` (open scheduled_action commitments we're waiting on THEM to answer, mirroring the nudge engine's awaiting_response_since set), `on_leave_until`, `reachable_now`/`next_window_at` (from people.channel availability windows), `authority_scope`, `department_slugs`, `last_contact_at` (most recent done outbound assigned to them), `overdue` (any SLA or awaited reply past deadline), `priority` (server sort key — overdue replies/work float to top, on-leave sinks), and `insight` (a one-line utility-fast note, see people.insights — null until the background cache warms). Rows are returned sorted by (-priority, full_name). `proposals` is the org-wide set of ALL unread alerts (workflow approvals, triage-classified inbound, Executive-created operational signals, and research artifacts the Executive flagged for review via `draft_artifact` — source=`artifact`, tagged `artifact`, which the UI renders as a Markdown document card rather than a terse proposal — and which also persist into the dedicated Artifacts section (`/artifacts`) so they remain browsable after they leave this unread queue — anything in the alerts table with status='unread'); the UI splits it into 'mine' vs 'across the team' using `caller_person_id` plus a 'principal owns unrouted' rule (alerts with `routed_to_person_id == null` fall to the principal's queue by default). Each proposal also carries presentation signals from `openexecutive.briefing.ranking`: `score` (attention sort key — severity-weighted, with a bonus for routed alerts) and `category` ('action' = a human should look, vs 'monitoring' = passive watchlist/external signals that are unrouted and not high/urgent), plus `surfaced_reason` (a short human note, null for most items) — set only when an external/watchlist signal was pulled into the 'action' lane *by its severity* (the high/urgent escape hatch in `categorize`, e.g. a ≥5% stock move), so the UI can render a per-item explanation of why a normally-Monitoring signal is in 'Needs you'. A proposal also carries `decision_instance_id` (parsed from a `decision_instance:{id}` topic tag), non-null only for gated calendar bookings surfaced from the decision ledger (source=`decision_scheduling`); the UI routes those cards' Approve/Reject to the /decisions endpoints (which book or cancel server-side and clear this alert) instead of the ack-and-hand-off-to-chat flow, so meeting bookings are reviewed in the briefing itself (the standalone proposals page was removed). `_build_today` sorts action items first (by score), monitoring last; the UI collapses the 'monitoring' tail into a separate section so it stops crowding the 'Needs you' queue. `narrative` is a PER-VIEWER Executive-voice 'what's going on' header (see `openexecutive.briefing.narrative` + `today._attach_narrative`). It is a SYNTHESIS, not a re-list: the actionable items render as cards below it, so the narrative gives the connective tissue a list can't (how items relate, what's most urgent and why, the single recommended focus) and deliberately does NOT enumerate a 'Needs you' section that would duplicate the cards. The principal and any unrostered/unresolved caller get the whole-company synthesis (cache scope `principal`) over ALL action-category proposals (mine + across the team; monitoring/watchlist noise is excluded) plus company-wide at-risk depts + activity; each non-principal teammate gets a role-scoped synthesis (cache scope `person:<id>`) over ONLY the action items routed to them + their departments' goal health + their department activity, written in their perspective. Synthesized by `synthesize_briefing_narrative`, which also produces the standalone morning_brief DM but via a DIFFERENT prompt (`standalone=True` → an enumerated brief with a 'Needs you' section, since the DM has no cards beside it to carry the list; the EoD digest still has its own prompt); the /today header path uses the synthesis prompt and never re-lists. Served from the per-scope `briefing_narrative` cache (`openexecutive.briefing.narrative_cache`, keyed by a hash of the viewer's scoped state + scope + UTC date + `NARRATIVE_PROMPT_VERSION`, the last so a prompt rewrite invalidates every cached narrative on the next view). Served from cache on the hot path and regenerated per-viewer in a FastAPI BackgroundTask when that viewer's hash moves; null on a cold cache. `in_flight` is the Executive's upcoming user-facing commitments — pending scheduled_actions (follow-ups, nudges) from `episodic.list_pending_scheduled_actions` (excludes the `__internal__` channel and `nudge_scan` heartbeat, the same set the activity feed hides), each with the resolved recipient `target` (person name via the shared channel→name lookup, or department/raw ref), `kind`, `run_at`, and `overdue` (run_at already passed). `awaiting` is the people we're waiting on a reply from, derived from the same open-commitment set behind each person's `awaiting_reply_count` (name, role, count, oldest_at, overdue), sorted most-overdue/oldest first. Together they power the briefing's 'In flight' section so cross-team work in progress is visible without opening the Scheduled Actions page. Both are additive and default to empty. `caller_person_id` is the signed-in caller resolved from `x-caller-email` via chat._resolve_caller_person_id; null when no caller could be resolved (unrostered signed-in user, or a CLI hit without the header). The route is async: it serves insight notes from the person_insights cache and, after resolving the caller, attaches the viewer-scoped narrative via `_attach_narrative`, scheduling regeneration of stale entries as FastAPI BackgroundTasks so the request never blocks on an LLM call. `_build_today()` stays synchronous and caller-agnostic — no insight regen and NO narrative (that is attached per-viewer by the endpoints) — for the morning_brief workflow and the deprecated /morning-brief alias that call it directly; the alias resolves the caller and serves the cached narrative but cannot schedule a regen."- "GET /today/activity?limit=N — Returns ActivityResponse(items). Each item is one recent self-initiated Executive action — a fired scheduled_action (DM dispatched, follow-up fired, cadence run, paused workflow resumed) or an extracted decision/advice row. Items carry `kind` (coarse classifier the UI maps to verb + icon — dm_sent, email_sent, nudge_sent, cadence_sent, workflow_resumed, proposal_routed, decision_logged, advice_given, workflow_done, initiative_started, decision_resolved, alert_raised, or action for unclassified), `summary`, `actor` (always Executive for now), `target` (channel ref / person, or null), `department`, and `at` (ISO timestamp). Sources merged — `scheduled_actions` with status=done (excluding `nudge_scan` heartbeat and `__internal__` channel), `decisions`, `advice_given`, completed `workflow_runs` (status=done — briefings/check-ins/research, bucketed at `updated_at`), `initiatives` (kicked-off projects, at `created_at`), resolved `decision_instances` (terminal gated-decision outcomes — approved/rejected/reversed, at `resolved_at`; pending ones stay in `proposals`, not the rail), and `alerts` raised (excluding source=`decision_scheduling`, which is the companion alert for a gated booking already represented by its `decision_resolved` row). This broadens the feed beyond the original messaging-heavy three sources so it reflects all self-initiated Executive activity, not just dispatched messages. Actions on `propose_only` departments are reclassified to `proposal_routed` because the runner marks them done without dispatching (the proposal is surfaced via /today's `proposals` field; the activity rail shows it as 'proposed to <approver>' rather than implying a DM was sent). Sorted by `at DESC`, then capped at `limit` (default 20, clamped to 1..100 via FastAPI Query validation — 422 on out-of-range). The Pulse page polls this endpoint (limit=100) every ~20s so new activity streams into the 'Recent activity' card without a reload; the card scrolls internally at a fixed max-height rather than growing the page."- "GET /today/activity/daily?days=N — Returns DailyActivityResponse(days), the per-day counts behind the Pulse page's 'heartbeat' heatmap (the GitHub-contributions-style grid at `/memories`). Same source set and exclusions as /today/activity — the union of `decisions`, `advice_given`, status=done `scheduled_actions` (excluding the `nudge_scan` heartbeat and `__internal__` channel), completed `workflow_runs`, `initiatives`, resolved `decision_instances`, and `alerts` — but bucketed by calendar day (UTC) in `episodic.count_activity_by_day` rather than returned as individual items — decisions/advice by their `timestamp`, fired actions by `run_at` (fire time, not `created_at` queue time, so a cadence queued the night before counts on the day it fires), workflow runs by `updated_at` (completion), initiatives by `created_at`, resolved decisions by `resolved_at`, alerts by `created_at`. The `workflow_runs` and `alerts` tables are owned by other stores (not `episodic.initialize_db`), so each UNION arm is included only when its table exists — `count_activity_by_day` checks `sqlite_master` and still counts the sources episodic owns on a DB initialised by episodic alone. The response is DENSE: every calendar day in the window is present (count 0 when nothing fired), oldest→newest, so the UI renders a gap-free grid without client-side fill. `days` defaults to 90, clamped to 1..365 via FastAPI Query validation (422 on out-of-range). Read-only, unauthenticated (matches /today/activity and /memories/*), uncached."- GET /morning-brief — deprecated alias for GET /today, kept for one release for older UI builds and bookmarks. Sends a Deprecation header with a Sunset date.@@ -2407,22 +2417,16 @@ workflows:(the common case) are fully served by the capture-and-surface pathabove; multi-step auto-continuation is the gap.- `offer_approval` (talent) is the first BUILT-IN workflow to yield the- gate (previously only user-created dynamic workflows did). It is- designed AROUND the resume gap: the run yields `result` + `artifact`- BEFORE the gate (the runner never reaches `complete_run` on a paused- run) and persists the package onto the Offer row, the gate exists to- RECORD the HIRING_SIGNOFF decision, and the actual- `pending_approval → extended` state transition is an explicit- follow-up action (the `extend_offer` tool / POST /offers/{id}/extend)- that consults the recorded resolution via- `talent.offers.offer_approval_state` — a recorded rejection blocks the- extension; a pending/absent sign-off proceeds on the principal's- explicit instruction with the gap flagged in the response. The gate- DMs the approver itself via `handle_message_person` before yielding- (no other component delivers built-in gate questions) and resolves the- approver via `people.store.find_approvers(HIRING_SIGNOFF)` with the- principal as fallback.+ NO BUILT-IN workflow currently yields the gate — `offer_approval` did,+ and it was removed with the talent vertical. (`exec_search_brief` survived+ that removal — it is an advisory CHRO brief with no gate and no pipeline+ dependency.) Only user-created dynamic+ workflows pause today. A dynamic workflow that pauses must be designed+ AROUND the resume gap: yield `result` + `artifact` BEFORE the gate (the+ runner never reaches `complete_run` on a paused run) and persist anything+ downstream code needs, so the gate's only job is to RECORD the decision and+ an explicit follow-up action performs the real state transition.+dynamic_user_created: |Users create reusable workflows on the fly — from the executive chat or abuilder UI on /jobs — without shipping a Workflow subclass. A dynamic@@ -2477,8 +2481,7 @@ workflows:Guardrail: `_CHAT_LAUNCH_BLOCKLIST` excludes `executive_research` (it has thededicated `run_executive_research` tool). The principal-targeting recurringworkflows (`morning_brief`, `end_of_day_digest`, `executive_reflection`) stay- launchable but the tool description warns they dispatch real messages. Talent- workflows are still better served by `start_talent_workflow`. A successful+ launchable but the tool description warns they dispatch real messages. A successful`run_workflow` emits an `action_taken` chip (in `action_chips`) linking to`/jobs/runs/{run_id}`.notable_recent:@@ -2505,292 +2508,6 @@ workflows:- "morning_brief — Shift 3 recurring workflow. Fires once per day from the scheduler (default 08:00 UTC, override via PRINCIPAL_BRIEF_MORNING_TIME env var). Targets the principal: utility_fast model renders a ≤200-word Markdown briefing. CHANGE-AWARE: the window is 'since the last DELIVERED morning brief' (`briefing.brief_state.since_for`, 24 h on a cold store, clamped to 7 d); activity comes from `_build_activity(20, since=…)`; proposals (action category only) split into NEW SINCE LAST BRIEF (enumerated, with why_now / next move) vs a one-line CARRIED OVER count (with the likely-stale count); a REWRITTEN block lists carried items the review rewrote in the window (`brief_state.rewritten_since`: verdict `changed`, still open — reported under 'what changed', never as done); a HANDLED OVERNIGHT block lists the alert review's completed moves (`brief_state.handled_since`, `changed` excluded). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A fingerprint of the inputs (`build_brief_fingerprint`, date-free) is compared to the last delivered one: unchanged ⇒ the artifact is the one-liner 'Nothing new since yesterday's brief — N items still waiting on you.' and no model call (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`, bypass with `force_full=true` on a manual run). The workflow yields a `result` event `{brief_fingerprint, suppressed, since}`; only `_run_principal_brief` records the fingerprint, after a successful delivery (`brief_state.record_delivered`, stored in `briefing_narrative` under scope `brief:<kind>`). Artifact is DM'd via the principal's preferred_channel (slack_dm → discord_dm → telegram → email fallback chain)."- "end_of_day_digest — Shift 3 recurring workflow. Fires once per day from the scheduler (default 18:00 UTC, override via PRINCIPAL_BRIEF_EOD_TIME). Same shape as morning_brief but framed as a recap since the last DELIVERED digest (`brief_state.since_for`, 24 h on a cold store): what OE did today (activity since), alerts it handled today (completed moves only; rewritten-but-open items render as a REWRITTEN block under still pending), what's still pending (NEW SINCE LAST BRIEF, action category only, carried-over as one line), what's at risk for tomorrow, one optional 'sleep on this' question. Same fingerprint / one-liner suppression and `force_full` as morning_brief, under scope `brief:principal_brief_eod`."- "executive_reflection — Shift 5 recurring workflow. Fires once per day ~30 minutes before the morning brief (default 07:30 UTC, override via PRINCIPAL_REFLECTION_TIME). The first workflow OE runs ON ITSELF — not for a department, not for the principal, but for its own org-coordination judgment. Three steps: (1) gather /today + /today/activity + recent open alerts, (2) single LLM call with the full outbound toolkit (schedule_followup, send_*_dm, send_department_message, send_company_broadcast, suggest_workflow, create_alert, etc.) bounded to ≤4 iterations — the model decides per signal whether to act now, notify the right audience via the persona's 'Choosing Who to Tell' rule, raise it for the morning brief, or ignore, (3) emit a short Markdown summary with a structured tool-call log. MEMORY: the context carries a YESTERDAY'S STANDUP block (the previous done run's artifact, capped at 1500 chars) and the prompt forbids re-acting on or re-notifying about anything listed there unless it changed; open alerts render with `alert_id`, the review verdict, note and recommended move. Reflection never closes alerts (the alert review does, with evidence) — the prompt does not instruct `ack_alert`. The artifact is stored via complete_run but NOT DM'd — the morning brief surfaces what was decided via /today/activity. This operationalizes the 'When You Notice Something on Your Own' persona section (Shift 1)."- - "candidate_screen — Talent-platform (Phase 1) workflow. Screens one candidate against one executive-search engagement: loads the engagement + candidate from `talent.store`, consults the `talent` specialist for a fit assessment, parses the 0-100 fit score from the response, and persists score + summary back onto the candidate via `talent.store.record_screening` (which advances a raw `lead` to `screened`). Emits a structured `result` event plus a Markdown scorecard artifact. See the `talent:` key."- - "candidate_outreach — Talent-platform (Phase 3) recruiting-automation workflow. Drafts a personalized first-touch + N follow-ups for a candidate via the `talent` specialist and schedules each touch as a REMINDER TO THE PRINCIPAL (a `scheduled_actions` row, assigned_to_person_id=principal, run_at = now + i*interval) — never a direct message to the candidate. Draft-and-approve posture: each reminder is the human checkpoint (the Executive DMs the principal the ready-to-send draft at fire time; the principal sends it manually). Deliberately uses reminders rather than a `wait_for_human` gate because gate-resume is deferred (a gate would pause and never schedule). Channel resolution maps the principal's people-channel → scheduled-actions vocabulary (slack→slack_dm etc.). See the `talent:` key."- - "interview_coordination — Talent-platform (Phase 3) workflow. Designs an N-round interview loop + a candidate-facing availability-request via the `talent` specialist, then schedules ONE reminder to the principal to kick off scheduling (line up the panel, send the availability request). Never contacts the candidate directly. See the `talent:` key."- - "reference_check — Talent-platform (Phase 3) workflow. Drafts a reference-check rubric (questions + the concerning-answer signal) + a reference-facing outreach via the `talent` specialist, then schedules ONE reminder to the principal to conduct the checks. Never contacts references directly. See the `talent:` key."- - "offer_approval — Talent-platform (close-the-hire-loop) workflow, and the first BUILT-IN to pause on a WaitForHumanEvent gate. Drafts the offer package for an interviewed candidate — terms via the `chro` specialist anchored on the engagement's comp_band, closing plan (risks, competing-offer posture, recommended expiry window) via the `talent` specialist — persists an Offer row (status pending_approval, full package Markdown on `package_md`), advances the candidate interviewed→offer, DMs the HIRING_SIGNOFF approver (find_approvers, principal fallback) the sign-off request via handle_message_person, yields result+artifact, THEN yields the gate (timeout 72h, on_timeout=escalate, expected_reply_shape=approve_reject, context_summary prefixed `offer_id=<n>` for later matching). The run stays awaiting_human/resolved; the extended transition is the explicit extend_offer follow-up. OE never sends the offer to the candidate. See the `talent:` key."- - "new_hire_onboarding — Talent-platform (close-the-hire-loop) workflow: the placed→Person handoff. Requires the candidate to be `placed` OR hold an accepted offer. Idempotently creates/updates the Person record (match by case-insensitive email, else exact full_name; role = engagement.role_title; department_slugs only when the engagement's free-text department resolves in the department registry; NO authority scopes granted), drafts a role-specific 30/60/90 plan via the `chro` specialist, and schedules day-7/30/60/90 check-in reminders to the PRINCIPAL (past milestones skipped when start_date is in the past). Never contacts the new hire directly. See the `talent:` key."--talent:- status: |- The talent-intelligence / executive-search vertical built on OpenExecutive.- IN-HOUSE hiring: searches are run- WITHIN this company, not on behalf of external clients. Single-tenant; reuses- the existing agent runtime, RAG, workflow engine, and shared SQLite DB.- module: openexecutive.talent- entities: |- THREE core entities, persisted in the shared `episodic_memory.db` via- `talent.store` (same idempotent `CREATE TABLE IF NOT EXISTS` +- `_resolve_db_path` convention as `people.store`):- - Engagement — one search: a role we're hiring for in THIS company- (`engagements` table, status open/on_hold/filled/cancelled). Optional- free-text `department` label (e.g. "Drilling") for in-house grouping —- NOT a FK to the departments entity.- - Candidate — a person considered for an engagement (`candidates` table,- FK engagement_id) moving through the pipeline- lead → screened → interviewed → offer → placed (rejected is a terminal- off-ramp). `fit_score` (0-100) + `screening_summary` are owned by- `record_screening`, never by the plain `upsert_candidate` path.- - Offer — an offer to a candidate (`offers` table, FKs candidate_id +- engagement_id). Lifecycle enforced by a transition map in- `set_offer_status`: draft → pending_approval → extended →- accepted/declined/expired/rescinded (rescind also legal from- draft/pending_approval; pending_approval may fall back to draft;- terminals are immutable — re-offering means a NEW row). INVARIANT: at- most ONE open offer (draft/pending_approval/extended) per candidate —- `create_offer` raises on a duplicate. `expires_at` is set at EXTEND- time, not draft time, and expiry NEVER auto-flips the status — only- `record_offer_decision` does, on the principal's say-so. `package_md`- carries the full offer-package artifact (persisted by offer_approval so- the UI can render it after the run pauses); `extended_at`/`decided_at`- are stamped by the transition; `approval_run_id` /- `approved_by_person_id` record the sign-off when one was resolved;- `nudge_action_ids_json` tracks the scheduled expiry reminders so a- decision can cancel them. Terms (`comp_summary`/`package_md`/`note`)- are editable only while draft/pending_approval — an extended offer's- terms are the record of what went out.- NOTE: the original external-`Client` entity was REMOVED — engagement is now- top-level. `initialize_db` does a one-time reset (drops the legacy talent- tables when a `clients` table is detected, then rebuilds the new shape), as- there is no migration tooling. Workflows that named the hiring org now use- THIS company's name from the profile (`reminders.company_name()` →- `load_or_create_profile().name`), not a client lookup.- specialist: |- `talent` — Head of Talent & Executive Search (openexecutive.agents.talent,- TalentAgent, deep-reasoning). Registered in SPECIALIST_REGISTRY; prompt- `TALENT_PROMPT` in prompts/domain_prompts.py. RAG alias maps `talent` →- ["hr", "strategy"] until a dedicated talent knowledge corpus is seeded.- TALENT_PROMPT is anchored to the live pipeline vocabulary (engagement,- stages lead→…→placed, fit_score) so the specialist's read lines up with- what the principal sees on the briefing.- chat_briefing: |- The vertical is wired into BOTH chat and the briefing so it isn't a siloed- UI. Chat: `openexecutive.orchestrator.talent_tools` adds tools to the- Executive's main loop (registered in executive.py `_ALL_SKILL_TOOLS` /- `_ALL_SKILL_HANDLERS`) — `list_engagements` (the shared- `briefing.talent_digest` rollup), `list_candidates`, `get_candidate`,- `match_candidates` (talent-graph semantic ranking) and `list_offers` are- read-only and never emit an action chip; the side-effecting tools- (registered in `action_chips.SIDE_EFFECTING_TOOLS`) are- `set_candidate_stage` (a light, reversible pipeline move — when the target- stage is `placed` the response carries a read-only `suggestion` to record- the offer decision and run new_hire_onboarding, with NO implicit writes),- `start_talent_workflow` (runs candidate_screen / candidate_outreach /- interview_coordination / reference_check / exec_search_brief /- new_hire_onboarding to completion via WORKFLOW_REGISTRY + the runs store,- mirroring `run_executive_research`; `offer_approval` instead pauses on its- sign-off gate — the handler mirrors run_workflow's WaitForHumanEvent- branch: save_checkpoint + a `status='awaiting_human'` response), the create- tools `create_engagement` / `create_candidate`, and the offer-lifecycle- tools `create_offer` (manual draft path when the principal dictates terms;- the workflow is the full drafted-and-approved path), `extend_offer`- (records that the PRINCIPAL sent the offer — OE never sends it — checks- the recorded sign-off via talent.offers, schedules expiry nudges to the- principal at T−3d/T−1d/T+12h as kind=ad_hoc scheduled_actions, future ones- only), and `record_offer_decision` (terminal outcome; cancels pending- nudges; `accepted` also moves the candidate to placed + the engagement to- filled — documented side effects, PLACED coincides with FILLED — and- suggests new_hire_onboarding; declined/expired/rescinded leave the- candidate's stage for the principal to decide). The shared extend/decide- logic lives in `openexecutive.talent.offers` so the chat tools and the- /offers routes can't drift. (There is NO `create_client`/`list_clients` — the- external-client entity was removed; in-house searches have no client.) The- create tools call the talent DATA layer (`talent.store.upsert_*`) directly,- mirroring the `/talent` API routes: `create_engagement` opens a role for THIS- company (required `role_title`, optional `department`; no client), and- `create_candidate` re-indexes the new person into the talent graph- (`talent.graph.index_candidate` against a `ChromaDBStore`) just as- `api/routes/talent.py` does after an insert, so `match_candidates` sees it.- `fit_score` / `screening_summary` stay workflow-owned (not settable via- create). NOTE: action_chips suppresses the chip when a write returns- `{status: not_found}` (nothing changed), alongside the existing error/noop- suppression; the `create_engagement` chip links to `/talent/searches`.- Heavier editing (updates, soft-archive) and bulk work stay in the `/talent`- UI (the old `/talent/clients` pages are gone; searches live at- `/talent/searches`). Briefing: `briefing.talent_digest` is the single rollup the- `/today` `talent` field, the 'Executive search' briefing card, the narrative- synthesis, and the chat `<briefing>` block all share — so the cards, the- header, and chat never disagree about pipeline state. See the `today:` key.-- MCP: the pipeline is also exposed to EXTERNAL agents over the outbound MCP- server (see `mcp_server:`) as a READ-ONLY search surface — an- oe://talent/engagements resource plus list_candidates / get_candidate /- match_candidates / find_similar_candidates tools that call talent.store /- talent.graph directly (NOT the chat handlers). The `talent` specialist's- advice is reachable there via consult_specialist. Writes and workflow- execution are not exposed over MCP.- graph: |- Phase 2 — semantic candidate matching (openexecutive.talent.graph). Each- non-archived candidate is indexed into a dedicated ChromaDB collection- `talent_candidates` (kept separate from builtin/company/research collections- so candidate profiles never blend into RAG). The doc text is the candidate's- name/title/company/location/source/notes/screening_summary; metadata carries- candidate_id, engagement_id, stage. Two queries: match_candidates_for_- engagement (ranks the WHOLE candidate pool against an engagement's role +- must-haves — a cross-engagement talent pool) and find_similar_candidates- (excludes the query candidate). Because KnowledgeStore.query only filters by- `domain`, archived rows are kept out of the index entirely and the query- candidate is removed by over-fetch + post-filter (mirrors the knowledge- retriever). Indexing is best-effort, driven from the API layer after a store- mutation (the store stays pure SQLite) and from the candidate_screen- workflow after a screen; failures are logged and swallowed so candidate CRUD- never breaks on a vector-store outage. `reindex_all` rebuilds from the store- (upsert active, drop archived).- api: |- `openexecutive.api.routes.talent` exposes CRUD for the two entities:- /engagements (in-house searches; create takes role_title + optional- department, no client) and /candidates (filter by engagement_id and stage),- plus /candidates/{id}/stage and per-entity /archive. (The /clients endpoints- were removed with the Client entity.) Mirrors the /people route shape. Phase- 2 adds the talent-graph endpoints: GET /engagements/{id}/matches, GET- /candidates/{id}/similar, and POST /talent/reindex. The hire-loop slice- adds /offers: GET /offers (filter by candidate_id / engagement_id /- status), GET+PATCH /offers/{id} (PATCH = terms, 409 unless- draft/pending_approval), POST /offers (201; 404 unknown candidate; 409 when- an open offer exists), POST /offers/{id}/extend and- /offers/{id}/decision (both return OfferActionResponse — the offer plus- approval_state / nudges_scheduled / cancelled_nudges / side_effects /- warnings; lifecycle conflicts are 409s, a malformed expiry is 400), and- POST /offers/{id}/archive. Extend/decision route through the shared- `talent.offers` logic, same code path as the chat tools.- automation: |- Phase 3 — recruiting automation, draft-and-approve posture. Three workflows- (see `workflows.notable_recent`): `candidate_outreach` (first-touch + timed- follow-up reminders), `interview_coordination` (loop + availability request),- and `reference_check` (rubric + reference outreach). All schedule reminders- to the PRINCIPAL only and never message candidates/references directly. They- share `openexecutive.talent.reminders` — `resolve_reminder_context` (resolves- candidate→engagement→principal→channel or an error string),- `principal_channel` (people-channel → scheduled-actions vocab; the raw- people-vocab pair is exposed as `person_channel_raw` for the- WaitForHumanEvent channel fields), and `schedule_reminder` (the single- place a reminder's recipient is set, always the principal). Multi-LLM is- intentionally NOT a build: non-Claude models already route via OpenRouter- (providers/registry.py) by model slug.- hire_loop: |- Close-the-hire-loop slice: the funnel no longer goes dark after- "interviewed". Two workflows + the Offer entity:- - `offer_approval` drafts the package (chro terms anchored on comp_band +- talent closing plan), persists the Offer (pending_approval, package on- the row), advances the candidate to `offer`, DMs the HIRING_SIGNOFF- approver, and pauses on the first built-in WaitForHumanEvent gate (see- `workflows.human_in_the_loop` for how the design works around the- generator-resume gap — the extended transition is the explicit- extend_offer follow-up that consults the recorded resolution; the- gate's context_summary is `offer_id=<n>`-prefixed and matched by- `talent.offers.find_offer_approval` scanning offer_approval runs).- - `new_hire_onboarding` is the placed→Person handoff: idempotent Person- creation (email match, else exact name; engagement free-text- department only mapped when it resolves to a real slug; no authority- scopes), a chro-drafted 30/60/90 plan, and day-7/30/60/90 check-in- reminders to the principal. Person creation is NEVER an implicit side- effect of a stage change — `record_offer_decision(accepted)` and- `set_candidate_stage(placed)` only SUGGEST running it. It COMPOSES- with the `staff_onboarding:` subsystem rather than competing:- new_hire_onboarding supplies the roster Person that staff-onboarding- plan delivery + the ramp drip require, and the merged- `set_candidate_stage(placed)` onboarding_suggestion chains- record_offer_decision → new_hire_onboarding →- create_onboarding_plan/start_onboarding.- Expiry posture: extend_offer schedules T−3d/T−1d/T+12h reminder nudges- (kind=ad_hoc, assigned to the principal; no new scheduled-action kind);- nudges remind, they never write — only record_offer_decision flips the- status. The /today digest's `offers_expiring_soon` is computed straight- from `expires_at`, so a missed nudge can't make the briefing stale. The- candidate-contact invariant extends to offers and onboarding: OE never- sends an offer to a candidate and never messages a new hire — the approver- gets the sign-off request, the principal gets the reminders. UI: the- candidate detail page (`/talent/candidates/{id}`) renders an OfferPanel- (status pill, terms, collapsible package, expiry countdown, lifecycle- buttons, onboarding launcher) between the stage control and the workflow- row.- deferred: |- CRM/ATS integration (rest of Phase 3) and multi-tenancy (Phase 4) are NOT in- these slices. Direct candidate sends (OE emailing candidates itself, outside- the roster-gated Person/DM model) are deferred as "Phase 3b". The- /architecture UI page (sections.py / page.tsx / prebuilt JSON) is- intentionally not wired for the talent module yet.--staff_onboarding:- status: |- The staff-onboarding framework (openexecutive.staff_onboarding) onboards a- PERSON into the company — distinct from the company-setup wizard in- `onboarding/` and the people roster in `people/`. A first-class subsystem,- sibling to `talent`, that turns existing company context (profile,- departments, roster, company-doc RAG, talent pipeline) into a role-tailored- onboarding experience for any hire (exec or IC, fractional or full-time).- entities: |- Three Pydantic models in the shared episodic_memory.db (idempotent- CREATE TABLE IF NOT EXISTS, mirroring talent/store.py):- - OnboardingTemplate (onboarding_templates): reusable role/department- blueprint — task specs (phase + owner-by-role + due_offset_days),- brief_sections, ramp_days, checkin_cadence. Defaults seeded idempotently- at startup (generic, engineering, go_to_market, finance) via- staff_onboarding/seed.py; operator edits are preserved.- - OnboardingPlan (onboarding_plans): one per hire — role, start_date,- manager/buddy, brief_artifact + reading_list, ramp_segments +- ramp_next_index, optional engagement_id/candidate_id back-links to- talent. completion_pct computed from tasks on read (never stored).- - OnboardingTask (onboarding_tasks): phased checklist item (pre_start /- week_1 / day_30 / day_60 / day_90), owner, due_date, status- (pending/in_progress/done/skipped; skipped excluded from completion).- instantiation: |- service.instantiate_plan turns a template into a plan: each task spec →- a task with due_date = start_date + due_offset_days and an owner resolved- against the plan/roster (hire→person_id, manager/buddy→plan ids,- department_head→department head). Plans start in `draft`. service.advance_phase- walks pre_start→week_1→day_30→day_60→day_90 and stops at the final phase.- content_workflow: |- role_onboarding (WORKFLOW_REGISTRY, section People) generates the welcome- brief section-by-section via the role's lead specialist — resolved by- department specialist_key → function map → cso fallback (staff_onboarding/- specialists.py). Sections: company landscape (cso), function state (domain),- people map (chro + roster), 30/60/90, week-one questions. Also generates an- optional per-day ramp drip and writes brief/reading_list/ramp_segments back- onto the plan. ramp_days is tri-state: None=use template, 0=force off,- >0=override.- chat_integration: |- orchestrator/onboarding_tools.py exposes list/get/create plans, list- templates, complete task, advance phase, and start_onboarding (runs the- workflow), spliced into the Executive's _ALL_SKILL_TOOLS/_ALL_SKILL_HANDLERS.- briefing/onboarding_digest.py (build_onboarding_brief_items /- format_onboarding_for_prompt) joins the per-turn chat briefing_context- (beside the talent digest) and powers a /today onboarding panel, so the- Executive proactively knows who is onboarding and what's overdue.- recurring: |- Bounded ramp drip (IMPLEMENTED): service.activate_plan sets the plan active- and enqueues the first `onboarding_ramp` scheduled action (kind handled in- scheduler/runner.py). Each fire claims the next segment via- store.claim_next_ramp_segment — an atomic compare-and-swap on ramp_next_index- — DMs it to the hire via message_person, and chains the next BUSINESS-day- occurrence ONLY while segments remain (self-terminating; every other- recurring kind chains forever). The drip only fires once the plan has a- roster person_id + pre-generated ramp_segments; enqueue_ramp is a no-op- otherwise.-- Stakeholder orchestration + milestone check-ins (IMPLEMENTED,- staff_onboarding/orchestration.py). activate_plan also enqueues, idempotently:- - `onboarding_kickoff` (one-shot, fires next tick): a welcome notice to the- hire's department channel ONLY when one is configured (no accidental- broadcast; routed via the privacy-gated, audited- broadcast_tools.post_department_notice — same length cap + privacy- backstop + audit trail as send_department_message — to the first- configured slack/discord/telegram channel), plus intro-1:1 nudge DMs to- the manager and buddy.- - `onboarding_checkin` (day 7/30/60/90): each milestone is its own- pre-scheduled row (no self-chaining); past-due milestones are skipped at- enqueue time. On fire it DMs the hire + manager a check-in and advances- the plan's phase deterministically (forward-only). wait_for_human resume- is a Phase-7 item, so reply-folding rides the chat-integrated path: the- recipient's reply lands in chat where the Executive's onboarding tools- update tasks/phase. Both kinds are handled in scheduler/runner.py- (`_run_onboarding_kickoff` / `_run_onboarding_checkin`).- talent_tie_in: |- Suggest-on-placed: when a talent candidate moves to `placed`, OE surfaces an- "onboard {name}" suggestion (no auto-fire, never messages the candidate).- Plan creation can pull role context from the engagement; delivery + ramp- activate only once the hire exists as a roster Person.artifacts:summary: |@@ -3299,30 +3016,18 @@ integrations:resources, and the specialist council as tools.Resources: oe://company/profile, oe://today/briefing, oe://today/activity,oe://people/roster, oe://departments/state, oe://memory/{decisions,- initiatives,advice}, oe://talent/engagements (active executive-search- engagements rolled up by pipeline stage via- briefing.talent_digest.build_talent_brief_items — the same rollup /today- and the briefing card use). Pure reads of existing service functions+ initiatives,advice}. Pure reads of existing service functions(load_or_create_profile, today._build_today/_build_activity,people.list_people, departments.list_departments, episodic list_*); noLLM calls. The warm ChromaDB store is handed to handlers viamcp_server.set_store() from the lifespan (handlers have no Request).Tools: consult_specialist (flagship — orchestrator.router.route_to_specialist,stateless, the specialist enum is a Literal pinned to SPECIALIST_REGISTRY- by a unit test — includes `talent`, so the executive-search specialist's- ADVICE is already reachable here), search_knowledge (knowledge.retriever.retrieve),- list_workflows (workflows.list_workflows → Workflow.meta), ask_executive+ by a unit test), search_knowledge (knowledge.retriever.retrieve),+ list_workflows (workflows.list_workflows → Workflow.meta), and ask_executive(Executive.chat fallback — non-streaming, resolves caller to principal or- by caller_email), and a READ-ONLY executive-search suite: list_candidates- / get_candidate (browse a search's pipeline via talent.store) and- match_candidates / find_similar_candidates (semantic candidate search via- talent.graph against the warm store, results enriched with candidate- name/title). These call the talent DATA layer (talent.store/graph/digest)- directly — NOT the orchestrator.talent_tools chat handlers, which audit as- actor=executive and build their own ChromaDB. Talent WRITES- (set_candidate_stage) and workflow execution (start_talent_workflow) are- intentionally NOT exposed over MCP — same read-only posture as the rest of- the server. limit is clamped to 1-50.+ by caller_email). All reads — no tool here mutates company state, the same+ read-only posture as the resources.DEFERRED by design: workflow EXECUTION is not exposed — workflows arelong-running async generators (minutes) that would exceed a single MCP@@ -3642,8 +3347,8 @@ clients:slot_contents: |company/_client_slots/<slug>/ (gitignored — client data is nevercommittable): state.db (VACUUM INTO copy of the shared episodic_memory.db- — chat history, scheduled actions, onboarding plans, talent pipeline,- departments, people, watchlist, audit/runs), profile.yaml, docs/ (all file+ — chat history, scheduled actions, departments, people, watchlist,+ audit/runs), profile.yaml, docs/ (all filetypes), skills/, mcp_servers.json (per-client external MCP tools, e.g.one client's Crayon credentials), meta.json (display name + timestamps).restore_mechanics: |@@ -3656,8 +3361,8 @@ clients:the restored dirs, and recent_research artifacts are wiped (same rule asfixtures: per-company research never crosses companies). Activating ablank 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.+ re-seeds defaults (departments, 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@@ -3781,7 +3486,7 @@ clients:state.db read-only IN PLACE (sqlite file:...?mode=ro URI — noactivation, no lock, cannot block or be blocked by a switch). Counts:pending + overdue scheduled actions, awaiting replies, unread alerts,- onboarding tasks due within 7 days or already overdue (deliberate — overdue ramp tasks must not drop off the board); plus engagement metadata and+ plus engagement metadata anddays_to_renewal. Honesty contract: parked data is as fresh as theslot's saved_at (stamped on every card); a broken slot degrades to oneerror-flagged card, never a failed board. Every table query isdiff --git a/packages/core/openexecutive/architecture/prebuilt/agents.json b/packages/core/openexecutive/architecture/prebuilt/agents.jsonindex 4bd870c2..cb23f956 100644--- a/packages/core/openexecutive/architecture/prebuilt/agents.json+++ b/packages/core/openexecutive/architecture/prebuilt/agents.json@@ -1,7 +1,7 @@{"section_id": "agents","title": "Agent Council",- "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe ten entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `talent` | `TalentAgent` | talent |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. With `OPENROUTER_ENABLED`, the Council dropdown's non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Six Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), and `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments). The last three share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nMost specialists only *advise* — they return analysis the Executive synthesizes. The `talent` specialist (Head of Talent & Executive Search) additionally backs a vertical the Executive can *act* on: `orchestrator.talent_tools` gives the main tool loop read access to the live search pipeline (`list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`) plus two side-effecting tools (`set_candidate_stage`, `start_talent_workflow`), so a chat turn can move a candidate or fire a screen/outreach workflow, not just opine. See the Talent section.\n\nBeyond the talent vertical, the Executive can launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",- "mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / talent / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external",+ "markdown": "The Executive (`openexecutive.orchestrator.executive.Executive`) is a single coherent persona that fans out to specialist sub-agents via Anthropic tool use. Each specialist subclasses `openexecutive.agents.base.BaseAgent`, carrying a `name`, `domain`, and `model`, and exposes `analyze(...)`, which wraps the question in user-turn context and calls Claude through the per-call provider.\n\nRouting uses one `consult_specialist` tool. Multiple parallel `tool_use` blocks in a single assistant turn fan out concurrently through `router.route_parallel`, each running its own domain-filtered ChromaDB query before the specialist sees the question. The Executive then synthesizes the returned analyses into one reply.\n\nThe nine entries in `SPECIALIST_REGISTRY` (`openexecutive.orchestrator.router`):\n\n| Key | Agent | Domain |\n| --- | --- | --- |\n| `cso` | `StrategyAgent` | strategy |\n| `cfo` | `FinanceAgent` | finance |\n| `chro` | `HRAgent` | hr |\n| `gc` | `LegalAgent` | legal |\n| `coo` | `OperationsAgent` | operations |\n| `cmo` | `MarketingAgent` | marketing |\n| `cpo` | `ProductAgent` | product |\n| `board_comms` | `BoardCommsAgent` | board |\n| `triage` | `TriageAgent` | triage |\n\nModels: specialists default to `claude-sonnet-5`; a deep-reasoning tier uses `claude-opus-5` (adaptive thinking); routing/fast classification uses `claude-haiku-4-5`. The Council's **Deep reasoning** toggle is honoured on Claude Opus/Sonnet (direct or via OpenRouter) and on any OpenRouter model whose live catalog entry supports `reasoning` (today all OpenAI, Gemini, DeepSeek and Grok entries; not Llama) — the request translator turns Anthropic adaptive thinking + effort into OpenRouter's `reasoning` parameter. It is a silent no-op on models that can't reason, and disabled for Haiku, which rejects adaptive thinking. With `OPENROUTER_ENABLED`, the Council dropdown's non-Anthropic entries come from OpenRouter's live `/models` catalog (fetched at startup, refreshed in the background, filtered to tool-capable paid text models from an allowlisted vendor set), falling back to a built-in snapshot if the fetch fails. Six Council-only agents are model/prompt-overridable in the UI but NOT callable via `consult_specialist`, because they are deliberately kept out of `SPECIALIST_REGISTRY`: `quality_judge` (committee review), `utility_fast` (gates, titles, decision parsing), `research` (the `executive_research` fan-out), `fixture_generator` (invents demo companies), `engagement_intake` (models a real client from intake material), and `onboarding_interviewer` (interviews a new user about their own company and drafts its profile, people and departments). The last three share one shape — a forced tool call producing a whole company, validated for referential integrity, with a single repair retry — but opposite epistemics: the fixture author invents, the other two extract and leave unstated facts empty rather than guessing.\n\nOne more structured-output utility agent sits beside `triage`: `openexecutive.agents.alert_review.AlertReviewAgent` (routing model, one forced `emit_alert_reviews` tool call, never raises). The alert review job hands it a batch of open alerts with evidence and gets back, per alert, a verdict (relevant / changed / resolved / stale), a confidence, the evidence it relied on, a one-line note, why-now, an optional deadline, and a recommended move (none / route / nudge / escalate / draft / suggest_workflow / merge / close) with its parameters. Like `triage`, it never mutates state — `alerts.review.apply_verdict` executes the verdicts deterministically within authority, so the model's job is judgment, not action.\n\nEvery specialist *advises* — each returns domain analysis the Executive synthesizes into one voice. None of them act on the company's behalf; the side-effecting tools in the main loop (schedule, people, departments, broadcast, watchlist, workflows) belong to the Executive, not to a specialist.\n\nThe Executive can also launch *any* workflow conversationally: `orchestrator.workflow_run_tools` adds `list_workflows` (the launchable catalog with each workflow's inputs) and `run_workflow` (runs a built-in or custom workflow to completion and returns its artifact, checkpointing approval gates as `awaiting_human`). This makes the `/jobs` catalog reachable from chat — see the Workflows section.\n\nThe Executive also backs the **Ask OE** panel's form-fill tier via `orchestrator.form_tools.propose_form_values`: when a chat turn arrives with a `<page_context>` block describing a form on the user's screen, the Executive can propose values for it. The proposal is delivered to the UI as a `form_patch` SSE event and placed into the form as highlighted suggestions — the tool never saves or submits anything; the user reviews and saves manually. The tool is **always** in the tool list (tool definitions sit at the top of the cached prompt prefix, so a conditionally-present tool would invalidate the prompt cache whenever panel and non-panel turns alternate); its description restricts usage to turns that carry a form descriptor.",+ "mermaid": "flowchart TD\n User([User message]) --> Exec[\"Executive<br/>orchestrator\"]\n Exec -->|consult_specialist| Cso[\"cso: StrategyAgent\"]\n Exec -->|consult_specialist| Cfo[\"cfo: FinanceAgent\"]\n Exec -->|consult_specialist| Gc[\"gc: LegalAgent\"]\n Exec -->|consult_specialist| More[\"chro / coo / cmo / cpo<br/>board_comms / triage\"]\n Cso --> Claude[\"Claude (Anthropic)\"]\n Cfo --> Claude\n Gc --> Claude\n More --> Claude\n Claude --> Exec\n class User entry\n class Exec compute\n class Cso compute\n class Cfo compute\n class Gc compute\n class More compute\n class Claude external","generated_at": "2026-09-11T19:18:55+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/api.json b/packages/core/openexecutive/architecture/prebuilt/api.jsonindex 2a211c17..64685142 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` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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. |\n| `talent` | `GET|POST|PATCH /engagements`, `GET|POST|PATCH /candidates`, `POST /candidates/{id}/stage`, `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, `GET|POST|PATCH /offers`, `POST /offers/{id}/{extend,decision,archive}` | Executive-search pipeline: searches, candidates, semantic matching, and the offer lifecycle (extend/decision return the offer plus approval state, scheduled/cancelled expiry nudges, side effects, and warnings; lifecycle conflicts are 409s). |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\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}` | Episodic-memory record management. |\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| `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` | Allowed sign-in emails. |\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` | 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. |\n| `sessions` | `GET /sessions`, `GET /sessions/{id}/messages` | List and read saved chat sessions. |\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` | Roster CRUD and scope lookups. |\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. |\n| `agents` | `GET /agents`, `PATCH /agents/{id}`, `POST /agents/{id}/test` | Specialist metadata and Council overrides. |\n| `personas` | `GET\\|PUT\\|POST\\|DELETE /personas` | Executive persona definitions. |\n| `alerts` | `POST /alerts/{id}/ack`, `POST /alerts/bulk-ack`, `POST /alerts/{id}/reopen`, `POST /alerts/review` | Groom the briefing queue. `ack` (`read`/`ack`/`dismissed`, optional `mute_topic`) also teaches a watch-sourced alert's watch (`trust_score`); `bulk-ack` takes explicit `alert_ids` and/or `older_than_days` + `category` (exempt sources skipped); `reopen` is the Undo for a `resolved` / `expired` / `dismissed` alert (never `ack` or an artifact / decision row; back to `unread` with every review stamp cleared and its TTL anchor refreshed, so it is live again even if older than its TTL); `review` runs the Executive's relevance review on demand (ignores the interval; still honours `ALERT_REVIEW_ENABLED`, the per-pass caps, the single-flight lock and per-alert idempotency) and returns the move counts. `bulk-ack` caps ids at 500, needs `older_than_days >= 1`, and applies watch feedback per row; `mute_topic` must be one of the alert's tags or a scoped `external:` / `department:` pattern. Alerts still surface only through the briefing (`/today` reads the live view) — there is no list, prefs, mutes, or live-stream endpoint. |\n| `artifacts` | `GET /artifacts`, `POST /artifacts/{id}/archive` | Browsable research/document artifacts. |\n| `decisions` | `GET /decisions`, `POST /decisions/{id}/{approve,reject,cancel}`, `GET /audit/reliability` | Approval-gated decision instances (e.g. calendar bookings). A proposed booking is surfaced on the briefing as a companion alert; approve/reject/cancel here also clear that alert. Reviewed in the briefing — there is no separate proposals page. |\n| `audit` | `GET /audit/logs`, `GET /audit/logs/{id}`, `GET /audit/sessions/{id}`, `GET /audit/usage`, `POST /audit/log` | Durable audit trail of side effects. `/audit/sessions/{id}` adds a per-session token cost summary; `/audit/usage` aggregates token usage and OpenRouter cost across all sessions (totals, by day, by model, and by source — the part of the system that made the calls — including server-side web-search counts). |\n| `architecture` | `GET /architecture/sections`, `.../sections/{id}` | This documentation surface. |\n| `guide` | `GET /guide/sections`, `.../sections/{id}` | Plain-language user-guide content surface — mirrors `architecture` (static, version-controlled files; no LLM on the serving path). |\n| `health` | `GET /health`, `GET /health/honcho` | Liveness probes (unauthenticated). |\n| `documents` | `POST\\|GET\\|DELETE /documents`, `GET /documents/{filename}` | Upload, list, view extracted text, and delete indexed company docs. Upload is keyed on the filename, so re-uploading a document replaces its chunks rather than duplicating them, and `DELETE` removes the rows as well as the file. `domain` must be one of the eight specialist domains or `general`; anything else is a 400 rather than a 200 that indexes where no specialist can retrieve. |\n| `scheduled` | `GET\\|DELETE` scheduled actions (`?status=…&order=asc\\|desc`) | Pending and fired scheduled actions; `order` flips the `run_at` sort (asc=soonest-first for the upcoming queue, desc=most-recent-first for terminal-status history). |\n| `watchlist` | `GET\\|POST\\|PATCH\\|DELETE /watchlist`, `POST /watchlist/{slug}/approve`, `POST /watchlist/{slug}/decline` | External-monitoring watchlist + signals. Rows carry `origin` (`manual` \\| `executive` \\| `research` \\| `research_proposed`); `approve` turns a research suggestion (`research_proposed`, `dry_run`) into a live watch, `decline` `{reason: not_relevant \\| too_noisy \\| wrong_source}` removes it and records the decline (or, for `too_noisy`, keeps it live at a high floor), both 409 unless the row is a pending suggestion; `DELETE ?reason=` on a research-origin row records the decline too. |\n| `workflows` | `GET /workflows`, `POST /workflows/{name}/runs`, `GET\\|POST\\|PUT\\|DELETE /workflows/custom` | Workflow catalog, run management, and user-created (dynamic) workflow CRUD. |\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}` | Episodic-memory record management. |\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| `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` | Allowed sign-in emails. |\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-16T13:15:55.101359+00:00"+ "generated_at": "2026-09-17T14:16:08.593444+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/clients.json b/packages/core/openexecutive/architecture/prebuilt/clients.jsonindex 1f3b48b9..0f72afdb 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* — 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 — client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB — 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. The isolated per-company collections are wiped in the same pass — `recent_research`, `notion_wiki`, and `inbound_attachments` (attachments are dropped and recreated rather than re-indexed: they have no source directory to rebuild from, and a row surviving a slot switch would be one client's attachment visible to the next). 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 — departments, onboarding templates, principal briefs, cadences — so the new client's Today page works without a restart. That wipe covers the **derived caches** — `briefing_narrative` and `person_insights` — 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 — 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 — 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 — 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` — 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 — 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 — 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 — 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 — 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 — 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** — your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact — 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** — 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** — 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 — 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** — 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 — 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 → advanced tools.\n\n**Knowledge review state per slot.** `_ensure_schemas` re-runs the idempotent schema inits after a restore, including `ReviewStore.initialize_db` followed by `sync_builtin_registrations`. Without that second call a freshly activated slot carried an empty `review_items` table until the next process restart; now it gets the shipped docs as trusted defaults straight away, matching a normal boot.",+ "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* — 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 — client data is never committable):\n\n| Artifact | What it carries |\n| --- | --- |\n| `state.db` | A transactionally-consistent copy of the shared SQLite DB — chat history, scheduled actions, 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. The isolated per-company collections are wiped in the same pass — `recent_research`, `notion_wiki`, and `inbound_attachments` (attachments are dropped and recreated rather than re-indexed: they have no source directory to rebuild from, and a row surviving a slot switch would be one client's attachment visible to the next). 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 — departments, principal briefs, cadences — so the new client's Today page works without a restart. That wipe covers the **derived caches** — `briefing_narrative` and `person_insights` — 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 — 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 — 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 — 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` — 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 — 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 — 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 — 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 — 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 — 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** — your role for the client, engagement status (active/paused/winding down/completed), start and renewal dates, retainer (display only), and primary contact — 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** — no activation, no lock. Cards roll up pending/overdue follow-ups, awaiting replies, unread alerts, 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** — 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 — 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** — 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 — 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 → advanced tools.\n\n**Knowledge review state per slot.** `_ensure_schemas` re-runs the idempotent schema inits after a restore, including `ReviewStore.initialize_db` followed by `sync_builtin_registrations`. Without that second call a freshly activated slot carried an empty `review_items` table until the next process restart; now it gets the shipped docs as trusted defaults straight away, matching a normal boot.","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-16T22:54:43.608081+00:00"+ "generated_at": "2026-09-17T14:16:08.593444+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/mcp_server.json b/packages/core/openexecutive/architecture/prebuilt/mcp_server.jsonindex 2fcd62be..10b3dd20 100644--- a/packages/core/openexecutive/architecture/prebuilt/mcp_server.json+++ b/packages/core/openexecutive/architecture/prebuilt/mcp_server.json@@ -1,7 +1,7 @@{"section_id": "mcp_server","title": "MCP Server",- "markdown": "Open Executive can run **as an MCP server**, the inverse of the MCP *gateway* (which lets the Executive consume external MCP servers). The server exposes Open Executive's company-grounded context and its specialist council to external MCP clients — Claude Desktop, Cursor, Claude Code, or any other agent — so they can ground themselves in *this* company and pull domain analysis **inside their own loop**, without re-explaining anything.\n\nThis is deliberately *not* another chat channel: Open Executive already has six of those (web, Slack, Discord, Telegram, email, Google Chat). The value here is structured, attachable context plus on-demand specialist analysis.\n\n## Transport & mount\n\nThe server speaks **Streamable-HTTP** and is mounted into the existing FastAPI app at `/mcp` (built with the `FastMCP` SDK, `streamable_http_path=\"/\"` mounted under `/mcp` so the endpoint is exactly `/mcp`). Mounting a sub-app does not run its lifespan, so the API lifespan runs `mcp.session_manager.run()` for the life of the process — without it every `/mcp` request would fail. The module lives at `openexecutive/mcp_server/` and is wired in `api/main.py`.\n\n## Auth\n\nThe `/mcp` endpoint is **not** exempt from the shared-secret middleware, so it is gated exactly like every other route: clients send `x-api-key: $BACKEND_SHARED_SECRET`. There is no second auth system. FastMCP's DNS-rebinding (Host-header) check is disabled because the endpoint authenticates with a header secret rather than a cookie — a browser rebinding attack cannot supply the key — and traffic arrives through the deployment's TLS terminator.\n\n## Resources (read-only context)\n\nThe highest-value surface: curated company state, pure reads, no LLM calls.\n\n| Resource URI | Contents |\n|---|---|\n| `oe://company/profile` | Structured company profile, as a prompt block |\n| `oe://today/briefing` | Morning-brief snapshot: department health, roster, proposals |\n| `oe://today/activity` | Recent self-initiated Executive activity |\n| `oe://people/roster` | Active people on the roster |\n| `oe://departments/state` | Departments with goals and cadences |\n| `oe://memory/decisions` · `…/initiatives` · `…/advice` | Episodic memory |\n| `oe://talent/engagements` | Active executive-search engagements, rolled up by pipeline stage |\n\n## Tools (capabilities)\n\n| Tool | What it does |\n|---|---|\n| `consult_specialist(specialist, query, context)` | **Flagship.** Domain analysis from one of ten specialists (cso, cfo, chro, gc, coo, cmo, cpo, board_comms, talent, triage), each grounded in company knowledge. Stateless. |\n| `search_knowledge(query)` | Raw retrieval over the MBA knowledge base + indexed company docs |\n| `list_workflows()` | Catalog of multi-step executive workflows and their input schemas |\n| `ask_executive(message, caller_email?)` | A single synthesized Executive answer — a fallback; prefer the specialist tool and resources |\n| `list_candidates(engagement_id, stage?)` · `get_candidate(candidate_id)` | Browse one executive-search engagement's candidate pipeline (read-only) |\n| `match_candidates(engagement_id, limit?)` · `find_similar_candidates(candidate_id, limit?)` | Semantic candidate search over the talent graph — ranked, name-enriched results |\n\nThe talent suite is **read-only**: it reads `talent.store` and ranks via `talent.graph`, the same data layer the `/talent` UI and the briefing use. Candidate writes and workflow runs are not exposed (see below). The `talent` specialist's *advice* is reachable via `consult_specialist`.\n\n## What's intentionally deferred\n\n**Workflow *execution*** is not exposed over MCP yet. Workflows are long-running async generators (minutes), which would exceed a single tool call's request/response window. The catalog is listed via `list_workflows()`; if execution is added later it will use a job-handle pattern (`start_workflow` → `run_id`, then poll) over the existing run persistence. MCP *prompts* are also skipped — OE workflows are server-executed orchestrations, not message templates.\n\n## Why prompt caching is unaffected\n\nThis path is parallel to chat. Resources are pure reads; `consult_specialist` delegates to the same `BaseAgent.analyze` that the chat path uses, reusing the existing cached system blocks. Nothing here touches the cache layout.",- "mermaid": "flowchart TD\n Client[\"External MCP client<br/>(Claude Desktop / Cursor / agent)\"]:::entry\n Gate[\"Shared-secret middleware<br/>x-api-key\"]:::entry\n Mount[\"/mcp Streamable-HTTP<br/>(FastMCP, mounted in FastAPI)\"]:::compute\n Res[\"Resources<br/>profile · today · people<br/>departments · memory · talent\"]:::compute\n Tools[\"Tools<br/>consult_specialist · search_knowledge<br/>list_workflows · ask_executive<br/>talent search (list/get/match/similar)\"]:::compute\n Spec[\"Specialist council<br/>route_to_specialist → BaseAgent.analyze\"]:::compute\n Store[(\"ChromaDB + SQLite<br/>company state\")]:::storage\n\n Client -->|x-api-key| Gate --> Mount\n Mount --> Res\n Mount --> Tools\n Res --> Store\n Tools --> Spec\n Tools --> Store\n Spec --> Store\n\n classDef entry fill:#1e3a8a,stroke:#60a5fa,color:#fff;\n classDef compute fill:#312e81,stroke:#a5b4fc,color:#fff;\n classDef storage fill:#365314,stroke:#a3e635,color:#fff;",+ "markdown": "Open Executive can run **as an MCP server**, the inverse of the MCP *gateway* (which lets the Executive consume external MCP servers). The server exposes Open Executive's company-grounded context and its specialist council to external MCP clients — Claude Desktop, Cursor, Claude Code, or any other agent — so they can ground themselves in *this* company and pull domain analysis **inside their own loop**, without re-explaining anything.\n\nThis is deliberately *not* another chat channel: Open Executive already has six of those (web, Slack, Discord, Telegram, email, Google Chat). The value here is structured, attachable context plus on-demand specialist analysis.\n\n## Transport & mount\n\nThe server speaks **Streamable-HTTP** and is mounted into the existing FastAPI app at `/mcp` (built with the `FastMCP` SDK, `streamable_http_path=\"/\"` mounted under `/mcp` so the endpoint is exactly `/mcp`). Mounting a sub-app does not run its lifespan, so the API lifespan runs `mcp.session_manager.run()` for the life of the process — without it every `/mcp` request would fail. The module lives at `openexecutive/mcp_server/` and is wired in `api/main.py`.\n\n## Auth\n\nThe `/mcp` endpoint is **not** exempt from the shared-secret middleware, so it is gated exactly like every other route: clients send `x-api-key: $BACKEND_SHARED_SECRET`. There is no second auth system. FastMCP's DNS-rebinding (Host-header) check is disabled because the endpoint authenticates with a header secret rather than a cookie — a browser rebinding attack cannot supply the key — and traffic arrives through the deployment's TLS terminator.\n\n## Resources (read-only context)\n\nThe highest-value surface: curated company state, pure reads, no LLM calls.\n\n| Resource URI | Contents |\n|---|---|\n| `oe://company/profile` | Structured company profile, as a prompt block |\n| `oe://today/briefing` | Morning-brief snapshot: department health, roster, proposals |\n| `oe://today/activity` | Recent self-initiated Executive activity |\n| `oe://people/roster` | Active people on the roster |\n| `oe://departments/state` | Departments with goals and cadences |\n| `oe://memory/decisions` · `…/initiatives` · `…/advice` | Episodic memory |\n\n## Tools (capabilities)\n\n| Tool | What it does |\n|---|---|\n| `consult_specialist(specialist, query, context)` | **Flagship.** Domain analysis from one of nine specialists (cso, cfo, chro, gc, coo, cmo, cpo, board_comms, triage), each grounded in company knowledge. Stateless. |\n| `search_knowledge(query)` | Raw retrieval over the MBA knowledge base + indexed company docs |\n| `list_workflows()` | Catalog of multi-step executive workflows and their input schemas |\n| `ask_executive(message, caller_email?)` | A single synthesized Executive answer — a fallback; prefer the specialist tool and resources |\n\n\n## What's intentionally deferred\n\n**Workflow *execution*** is not exposed over MCP yet. Workflows are long-running async generators (minutes), which would exceed a single tool call's request/response window. The catalog is listed via `list_workflows()`; if execution is added later it will use a job-handle pattern (`start_workflow` → `run_id`, then poll) over the existing run persistence. MCP *prompts* are also skipped — OE workflows are server-executed orchestrations, not message templates.\n\n## Why prompt caching is unaffected\n\nThis path is parallel to chat. Resources are pure reads; `consult_specialist` delegates to the same `BaseAgent.analyze` that the chat path uses, reusing the existing cached system blocks. Nothing here touches the cache layout.",+ "mermaid": "flowchart TD\n Client[\"External MCP client<br/>(Claude Desktop / Cursor / agent)\"]:::entry\n Gate[\"Shared-secret middleware<br/>x-api-key\"]:::entry\n Mount[\"/mcp Streamable-HTTP<br/>(FastMCP, mounted in FastAPI)\"]:::compute\n Res[\"Resources<br/>profile · today · people<br/>departments · memory\"]:::compute\n Tools[\"Tools<br/>consult_specialist · search_knowledge<br/>list_workflows · ask_executive\"]:::compute\n Spec[\"Specialist council<br/>route_to_specialist → BaseAgent.analyze\"]:::compute\n Store[(\"ChromaDB + SQLite<br/>company state\")]:::storage\n\n Client -->|x-api-key| Gate --> Mount\n Mount --> Res\n Mount --> Tools\n Res --> Store\n Tools --> Spec\n Tools --> Store\n Spec --> Store\n\n classDef entry fill:#1e3a8a,stroke:#60a5fa,color:#fff;\n classDef compute fill:#312e81,stroke:#a5b4fc,color:#fff;\n classDef storage fill:#365314,stroke:#a3e635,color:#fff;","generated_at": "2026-09-11T14:33:24Z"}diff --git a/packages/core/openexecutive/architecture/prebuilt/scheduler.json b/packages/core/openexecutive/architecture/prebuilt/scheduler.jsonindex 2f2fc0d6..37a1884d 100644--- a/packages/core/openexecutive/architecture/prebuilt/scheduler.json+++ b/packages/core/openexecutive/architecture/prebuilt/scheduler.json@@ -1,7 +1,7 @@{"section_id": "scheduler","title": "Scheduler & Cadences",- "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n### Bounded onboarding ramp drip\n\nStaff onboarding adds the `onboarding_ramp` action kind — the one *self-terminating* recurring action (every other recurring kind chains forever). `staff_onboarding.service.activate_plan` enqueues the first occurrence; on each fire the runner claims the plan's next pre-generated ramp segment via an atomic compare-and-swap on `ramp_next_index` (`store.claim_next_ramp_segment`), DMs it to the hire with `message_person`, and chains the next **business-day** occurrence ONLY while segments remain — then stops. It no-ops unless the plan has a roster `person_id` and generated `ramp_segments`.\n\n### Onboarding orchestration & check-ins\n\n`activate_plan` also enqueues two more kinds (idempotently, via `staff_onboarding.orchestration`):\n\n- `onboarding_kickoff` — one-shot, fires the next tick: a welcome notice to the hire's **department channel only when one is configured** (no accidental broadcast — routed through the privacy-gated, audited `broadcast_tools.post_department_notice`, which applies the same length cap + privacy backstop + audit trail as `send_department_message`, to the first configured Slack/Discord/Telegram channel), plus intro-1:1 nudge DMs to the manager and buddy.\n- `onboarding_checkin` — milestone check-ins at **day 7 / 30 / 60 / 90**. Each milestone is its own pre-scheduled row (no self-chaining); milestones already in the past at activation are skipped. On fire it DMs the hire + manager a check-in and advances the plan's phase deterministically (forward-only). Because `wait_for_human` resume is a Phase-7 item, replies aren't auto-resumed — they land in chat, where the Executive's onboarding tools fold them into task/plan progress.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.",+ "markdown": "The scheduler is an asyncio task started in the FastAPI lifespan (`openexecutive.scheduler.runner.run_scheduler`). It polls every 30s and reads due rows from `scheduled_actions` (in `episodic_memory.db`). The due query uses `claim_due_actions`, an UPDATE…RETURNING claim, so each row fires at most once per process — this assumes a single scheduler instance per database. Polls are gated on an active company profile via `_company_profile_active()`; before onboarding, due rows stay `pending`.\n\n### Cadence DSL\n\n`openexecutive.departments.cadence` supports, all in UTC:\n\n- `daily@HH:MM`\n- `weekly@DOW@HH:MM` or `weekly@DOW-HH:MM` (DOW is a 3-letter day, e.g. `weekly@thu@09:00`)\n- `quarterly@DD-HH:MM`\n\nWhen a department cadence is due, the runner invokes the `department_check_in` workflow and chains the following occurrence via `cadence.enqueue_next()`. Deleting a department cancels its pending `dept_cadence` rows, and `cancel_orphaned_cadences()` sweeps orphans on boot.\n\nUser-created (dynamic) workflows can carry the same cadence DSL. A cadence-enabled definition enqueues a `dynamic_workflow` action (`workflows.dynamic_cadence`); when due, the runner runs the stored `DynamicWorkflow`, DMs the artifact to the definition's `cadence_person_id`, and re-chains the next occurrence. Saving/updating/deleting the definition reconciles its pending `dynamic_workflow` rows.\n\n### Channel routing & nudges\n\nThe delivery channel lives on the `scheduled_actions` row (`channel` / `channel_ref`); the runner dispatches through whichever was set at enqueue time — `telegram`, `slack_dm`, `discord_dm`, `email`, or `__internal__` (workflow steps and heartbeats bypass outbound dispatch). Rows left pending by the removed staff-onboarding kinds drain through that same `__internal__` short-circuit (marked done, no dispatch); the removed talent workflows' *ad-hoc* reminders sat on the principal's real DM channel instead, so a one-shot startup sweep (`memory.episodic.cancel_orphaned_talent_reminders`) cancels them — `ad_hoc`, no department, `pending` or `running`, matching the five generated reminder shapes (outreach, interview coordination, reference checks, onboarding check-in, offer expiry) — and clears the awaiting-reply flag on delivered ones so the nudge engine stops chasing them. The marker row in `app_migrations` is claimed first with `INSERT OR IGNORE` in the same transaction, so concurrent boots cannot double-run or crash. The nudge engine (`scheduler.nudge_engine`, default 15 min) scans stalled `awaiting_human` runs, stale commitments, and idle initiatives, then emits `proactive_nudge` rows routed via `people.channel.prefer_channel_for` — honouring each Person's preferred (last-used) channel and availability windows, deferring those outside their window and skipping those with no reachable channel. Emission is capped per `scope_key` (`NUDGE_MAX_PER_SCOPE`, default 3 delivered nudges) so a parked item is not chased forever.\n\n### Alert lifecycle: expiry sweep and the review heartbeat\n\nTwo alert-maintenance jobs live here. The **expiry sweep** is loop-level, not a heartbeat row: `_maybe_sweep_alerts` runs `alerts.lifecycle.expire_stale_alerts` (and, on the same 15-minute throttle, `monitoring.research.watch_policy.sweep` — expiring unreviewed research watch suggestions, auto-disabling research-added watches that proved noisy or dead, and filing one `watchlist_suggestions` nudge when ≥3 suggestions have waited ≥7 days; see External monitoring) once at boot and every 15 minutes at the top of the tick — before the company-profile and rotation gates, so an old backlog expires even before onboarding completes, flipping `unread` alerts past their category TTL to `expired` and auditing `alert_sweep`. Pure DB hygiene, no model call, reversible via `POST /alerts/{id}/reopen`.\n\nThe **Executive alert review** is a real heartbeat — kind `alert_review_scan`, `__internal__` channel, bootstrapped idempotently at startup when `ALERT_REVIEW_ENABLED` and chained every `ALERT_REVIEW_INTERVAL_HOURS` (6) with the same crash-resilient run → mark-done → chain shape as `nudge_scan`. `_run_principal_brief` also runs a `pre_brief` pass right before the morning brief (a review failure never blocks the brief). Each pass re-examines open alerts with evidence and, within department authority and the privacy rule, routes, nudges, escalates, drafts, merges or resolves them — see the Today section for the policy. The moves go through the real handlers (`message_person`, `draft_artifact`), so the outbound anti-spam guard applies, and `ALERT_REVIEW_MAX_MOVES_PER_SCAN` bounds side effects per pass.\n\n## Client rotation claim pause\n\nThe `client_rotation` kind (multi-client practice mode, opt-in via `CLIENT_ROTATION_ENABLED`) adds one loop-level behavior: while a rotation's `.rotation_in_progress` marker exists, the scheduler **skips claiming entirely** for that tick. Rotation switches the live company context between parked clients; claiming during the window would fire the just-activated client's overdue outbound follow-ups from a context nobody is watching. Everything due fires on the first tick after the original client is restored. Stale markers (crash mid-rotation) are reconciled at scheduler startup, and the rotation row is idempotently re-seeded both at boot and after every slot activation (scheduled rows swap with the client). See the Client Companies section for the rotation's full design.\n\nAn optional `notion_sync_scan` heartbeat (`NOTION_SYNC_ENABLED`, off by default) incrementally re-indexes Notion pages the workspace integration can see into the isolated `notion_wiki` collection (not COMPANY), reconciles un-shared pages, then chains the next tick.","mermaid": "flowchart TD\n Loop[\"run_scheduler<br/>poll every 30s\"]\n Claim[\"claim_due_actions<br/>(status=pending, by kind)\"]\n Table[(\"scheduled_actions\")]\n Dispatch[\"dispatch via row channel<br/>(ad_hoc / proactive_nudge)\"]\n Dept[\"dept_cadence →<br/>department_check_in\"]\n Nudge[\"nudge_scan →<br/>nudge_engine scan\"]\n Brief[\"principal_brief_morning / _eod →<br/>morning_brief / end_of_day_digest\"]\n Reflect[\"executive_reflection →<br/>reflection (artifact only)\"]\n ExtMon[\"external_monitor_scan →<br/>monitoring pipeline\"]\n Research[\"watchlist_research_scan →<br/>executive_research (skip-if-unchanged)\"]\n Notion[\"notion_sync_scan →<br/>isolated wiki ingest\"]\n Chain[\"enqueue_next<br/>(re-arm recurring tick)\"]\n Prefer[\"prefer_channel_for<br/>(availability + last-used)\"]\n Channels[\"Slack / Discord<br/>Telegram / Email\"]\n Principal[\"DM principal\"]\n Alerts[\"alerts pipeline → /today\"]\n Loop --> Claim\n Claim -- \"claim due rows\" --> Table\n Claim -- \"ad_hoc / proactive_nudge\" --> Dispatch\n Claim -- \"dept_cadence\" --> Dept\n Claim -- \"nudge_scan\" --> Nudge\n Claim -- \"principal_brief_*\" --> Brief\n Claim -- \"executive_reflection\" --> Reflect\n Claim -- \"external_monitor_scan\" --> ExtMon\n Claim -- \"watchlist_research_scan\" --> Research\n Claim -- \"notion_sync_scan\" --> Notion\n Nudge -- \"prefer_channel_for\" --> Prefer\n Prefer -- \"emits proactive_nudge\" --> Table\n Dispatch --> Channels\n Brief --> Principal\n ExtMon --> Alerts\n Dept --> Chain\n Nudge --> Chain\n Brief --> Chain\n Reflect --> Chain\n ExtMon --> Chain\n Research --> Chain\n Notion --> Chain\n Chain --> Table\n class Loop entry\n class Claim compute\n class Table storage\n class Dispatch compute\n class Dept compute\n class Nudge compute\n class Brief compute\n class Reflect compute\n class ExtMon compute\n class Research compute\n class Notion compute\n class Chain compute\n class Prefer compute\n class Channels external\n class Principal external\n class Alerts hot",- "generated_at": "2026-09-12T10:45:28.240804+00:00"+ "generated_at": "2026-09-17T14:24:32.137561+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/schemas.json b/packages/core/openexecutive/architecture/prebuilt/schemas.jsonindex 479e5566..50773d77 100644--- a/packages/core/openexecutive/architecture/prebuilt/schemas.json+++ b/packages/core/openexecutive/architecture/prebuilt/schemas.json@@ -1,7 +1,7 @@{"section_id": "schemas","title": "Data Schemas",- "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at` |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run). `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Talent tables\n\n| Table | Key columns |\n|---|---|\n| `engagements` | `id`, `role_title`, `department` (free text, not a FK), `status`, `location`, `comp_band`, `must_haves`, `description`, `archived` |\n| `candidates` | `id`, `engagement_id` (FK), `full_name`, `current_title`, `current_company`, `email`, `linkedin_url`, `source`, `stage`, `fit_score`, `screening_summary`, `notes`, `archived` |\n| `offers` | `id`, `candidate_id` (FK), `engagement_id` (FK), `status`, `comp_summary`, `package_md`, `note`, `expires_at`, `extended_at`, `decided_at`, `approval_run_id`, `approved_by_person_id`, `nudge_action_ids_json`, `archived` |\n\n`candidates.stage` ∈ lead / screened / interviewed / offer / placed / rejected. `offers.status` ∈ draft / pending_approval / extended / accepted / declined / expired / rescinded, enforced by a transition map in `talent.store.set_offer_status` (terminals immutable); at most one open offer per candidate. `expires_at` is set at extend time, and expiry never auto-flips the status — only `record_offer_decision` does. See the [Talent](#talent) section.\n\n`outbound_context` links an outbound DM OE sent back to the conversation that triggered it, so the recipient's reply can be hydrated with that backstory instead of starting from an empty per-person session. `status` ∈ open / consumed; the row is one-shot consumed on the first matched reply within a 72h window. See Integrations → Cross-session DM context.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `department_slugs` |\n| Contact | `email`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.",+ "markdown": "The shapes below are the load-bearing data structures: episodic SQLite tables (in `episodic_memory.db`) and the Pydantic models for departments and people.\n\n### Episodic tables\n\n| Table | Key columns |\n|---|---|\n| `decisions` | `id`, `timestamp`, `domain`, `summary`, `rationale`, `outcome`, `tags`, `department`, `session_id` |\n| `initiatives` | `id`, `title`, `status`, `created_at`, `updated_at`, `summary`, `department` |\n| `advice_given` | `id`, `timestamp`, `domain`, `query_summary`, `advice_summary`, `department`, `session_id` |\n| `scheduled_actions` | `id`, `created_at`, `run_at`, `channel`, `channel_ref`, `intent_text`, `status`, `attempts`, `kind`, `department`, `assigned_to_person_id`, `awaiting_response_since`, `scope_key`, `required_scope` |\n| `outbound_context` | `id`, `created_at`, `channel`, `channel_ref`, `recipient_person_id`, `outbound_text`, `originating_session_id`, `outbound_message_id`, `consumed_at`, `status` |\n\n| `dynamic_workflows` | `name` (PK), `definition` (JSON of `DynamicWorkflowDef`), `is_active`, `created_at`, `updated_at` |\n| `app_migrations` | `name` (PK), `applied_at` — one-shot data migrations (sweeps that must run exactly once per DB); schema DDL stays idempotent and is not recorded here |\n\n`department` and `session_id` are additive columns (default `''`); `session_id` scopes per-thread recall. `scheduled_actions.status` ∈ pending / running / done / failed / cancelled, and `scheduled_actions.kind` includes `dynamic_workflow` (a cadence-fired user-created workflow run). `dynamic_workflows` stores user-created (dynamic) workflow definitions interpreted by the generic `DynamicWorkflow` engine; the JSON `definition` holds free-text input fields and an ordered step list (specialist / approval_gate / synthesis) plus an optional cadence.\n\n### Legacy tables (talent / staff onboarding)\n\nThe talent (executive-search) and staff-onboarding features were removed. Their tables —\n`engagements`, `candidates`, `offers`, `onboarding_templates`, `onboarding_plans`,\n`onboarding_tasks` — are **not dropped**: no code creates, reads or writes them any more,\nbut rows survive on upgraded installs. `clients.slots` still wipes them when a blank client\nslot is activated (existence-guarded, a no-op on fresh installs) so a slot can never inherit\na previous client's candidate data.\n\n### Department / Goal / ChecklistItem\n\n| Model | Fields |\n|---|---|\n| `DepartmentConfig` | `slug`, `title`, `specialist_key`, `charter`, `authority_level`, `head_person_id`, `head_persona_slug`, `cadences`, `slack_channel_id`, `discord_channel_id`, `telegram_chat_id` |\n| `Goal` | `id`, `department_slug`, `period_type`, `period_value`, `key_result`, `target`, `current`, `status`, `created_at`, `updated_at`, `last_reviewed_at` |\n| `DepartmentState` | `config`, `goals`, `headcount`, `budget_usd`, `member_person_ids`, `updated_at` |\n\n`authority_level` ∈ `auto_execute` / `propose_only` / `escalate`; `Goal.status` ∈ `on_track` / `at_risk` / `off_track`.\n\n### Person\n\n| Field group | Fields |\n|---|---|\n| Identity | `id`, `full_name`, `role`, `is_principal`, `department_slugs` |\n| Contact | `email`, `slack_user_id`, `telegram_chat_id`, `discord_user_id`, `preferred_channel` |\n| Routing | `availability`, `authority_scope`, `response_sla_hours`, `on_leave_until`, `reports_to_person_id` |\n| Lifecycle | `archived`, `created_at`, `updated_at` |\n\nExactly one `Person` should have `is_principal=True` — the fallback approver when no delegated person matches.","mermaid": null,- "generated_at": "2026-06-10T00:00:00+00:00"+ "generated_at": "2026-09-17T14:16:08.593444+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/staff_onboarding.json b/packages/core/openexecutive/architecture/prebuilt/staff_onboarding.jsondeleted file mode 100644index 4a212a8b..00000000--- a/packages/core/openexecutive/architecture/prebuilt/staff_onboarding.json+++ /dev/null@@ -1,7 +0,0 @@-{- "section_id": "staff_onboarding",- "title": "Staff Onboarding",- "markdown": "The **staff_onboarding** module (`openexecutive.staff_onboarding`) onboards a *person into the company* — a new hire, exec or IC, fractional or full-time. It is distinct from the company-setup wizard in `onboarding/` (which captures the company profile) and from the people roster in `people/`. It is a first-class subsystem, a sibling to `talent`, and it leans on the context Open Executive already holds: the company profile, departments, the people roster, company-doc RAG, and the talent pipeline.\n\n## Entities\n\nThree Pydantic models persist to the shared `episodic_memory.db` (idempotent `CREATE TABLE IF NOT EXISTS`, no migration tooling), mirroring `talent/store.py`:\n\n- **`OnboardingTemplate`** (`onboarding_templates`) — a reusable, role/department blueprint: an ordered set of task specs (phase + owner-by-role + due offset from start date), the brief sections to generate, a ramp length, and a check-in cadence. Default templates (`generic`, `engineering`, `go_to_market`, `finance`) are seeded idempotently at startup; operator edits are never clobbered.\n- **`OnboardingPlan`** (`onboarding_plans`) — one per hire. Carries the hire, role, start date, manager/buddy, the generated welcome brief + reading list, the pre-generated ramp segments + the next-segment index, and optional `engagement_id`/`candidate_id` links back to talent. `completion_pct` is computed from the plan's tasks on read (never stored).\n- **`OnboardingTask`** (`onboarding_tasks`) — one checklist item: phase (`pre_start` / `week_1` / `day_30` / `day_60` / `day_90`), category, owner person, due date, and status (`pending` / `in_progress` / `done` / `skipped`; skipped is excluded from completion).\n\n## Instantiation\n\n`service.instantiate_plan` turns a template into a concrete plan: each task spec becomes a task with a real `due_date` (`start_date + due_offset_days`) and an owner resolved against the plan/roster (`hire` → person_id, `manager`/`buddy` → the plan's ids, `department_head` → the department's configured head). Plans start in `draft`; orchestration and the ramp are fired explicitly on activation, not at instantiation.\n\n## Content workflow — `role_onboarding`\n\nA registered workflow (`WORKFLOW_REGISTRY[\"role_onboarding\"]`, section People) generates the role-tailored **welcome brief** section by section via the role's domain specialist — resolved by department `specialist_key` → a function-name map → `cso` fallback, so any role gets a relevant lens. Sections: company landscape (`cso`), state of the function (domain specialist), people map (`chro` + roster), a 30/60/90 plan, and week-one questions. It also generates an optional per-day **ramp drip** and writes the brief, reading list, and ramp segments back onto the plan. `ramp_days` is tri-state: omitted = use the template's value, `0` = force no drip, `>0` = override.\n\n## Chat + /today integration\n\nThe subsystem is driven and surfaced from chat exactly as `talent` is:\n\n- **Chat tools** (`orchestrator/onboarding_tools.py`, spliced into the Executive's `_ALL_SKILL_TOOLS` / `_ALL_SKILL_HANDLERS`): `list_onboarding_plans`, `get_onboarding_plan`, `list_onboarding_templates`, `create_onboarding_plan`, `complete_onboarding_task`, `advance_onboarding_plan`, and `start_onboarding` (runs the workflow and returns the brief).\n- **Proactive briefing** (`briefing/onboarding_digest.py`): a compact one-line-per-plan digest joins the per-turn chat `briefing_context` (beside the talent digest) and powers a `/today` onboarding section, so the Executive knows who is onboarding and what's overdue without being asked.\n\n## Activation — drip, kickoff & check-ins\n\n`service.activate_plan` flips the plan to `active` and enqueues three families of scheduled action (all idempotent; the async scheduler does the sending — see the Scheduler section):\n\n- **Ramp drip** (`onboarding_ramp`) — walks the plan's pre-generated `ramp_segments` via an atomic claim that advances `ramp_next_index`, one per business day, and self-terminates when exhausted. No-ops without a roster `person_id` + segments.\n- **Kickoff** (`onboarding_kickoff`, one-shot) — a welcome notice to the hire's department channel *only when one is configured*, plus intro-1:1 nudge DMs to the manager and buddy.\n- **Milestone check-ins** (`onboarding_checkin`, day 7/30/60/90) — DM the hire + manager and advance the plan's phase forward-only. Past-due milestones are skipped at activation. Reply-folding rides the chat tools (the `wait_for_human` resume path is a Phase-7 item), so a manager's reply lets the Executive mark tasks done or advance the phase via its onboarding tools.",- "mermaid": "flowchart TD\n Template[\"OnboardingTemplate (seeded)\"] -->|instantiate_plan| Plan[\"OnboardingPlan (draft)\"]\n Plan --> Tasks[\"OnboardingTask checklist (phased)\"]\n Plan -->|role_onboarding workflow| Brief[\"Welcome brief + reading list + ramp segments\"]\n Brief --> Plan\n Placed[\"talent: candidate placed\"] -.suggest.-> Plan\n Plan --> Chat[\"Chat tools + briefing digest\"]\n Plan --> Today[\"/today onboarding panel\"]\n Plan -.scheduler.-> Drip[\"bounded ramp drip + check-ins\"]",- "generated_at": "2026-06-10T00:00:00Z"-}diff --git a/packages/core/openexecutive/architecture/prebuilt/talent.json b/packages/core/openexecutive/architecture/prebuilt/talent.jsondeleted file mode 100644index d996535f..00000000--- a/packages/core/openexecutive/architecture/prebuilt/talent.json+++ /dev/null@@ -1,7 +0,0 @@-{- "section_id": "talent",- "title": "Talent / Executive Search",- "markdown": "The **talent** module (`openexecutive.talent`) is a vertical built on top of Open Executive that turns the executive-advisor runtime into an executive-search platform. It is single-tenant and reuses the existing agent runtime, RAG, scheduler, workflow engine, and shared SQLite database rather than introducing new infrastructure.\n\nThis is **in-house hiring**: searches are run *within* this company, not on behalf of external clients.\n\n## Entities\n\nThree core records, persisted in the shared `episodic_memory.db` via `talent.store` (the same idempotent `CREATE TABLE IF NOT EXISTS` + `_resolve_db_path` convention as `people.store`):\n\n- **Engagement** — one search: a role we're hiring for in this company (`engagements`, status `open` / `on_hold` / `filled` / `cancelled`). Optional free-text `department` label (e.g. \"Drilling\") for in-house grouping — not a FK to the departments entity.\n- **Candidate** — a person considered for an engagement (`candidates`, FK `engagement_id`) moving through the pipeline `lead → screened → interviewed → offer → placed`, with `rejected` as a terminal off-ramp. `fit_score` (0-100) and `screening_summary` are owned by `record_screening` (set by the `candidate_screen` workflow), never by the plain candidate-edit path.\n- **Offer** — an offer to a candidate (`offers`, FKs `candidate_id` + `engagement_id`). Lifecycle is enforced by a transition map in `set_offer_status`: `draft → pending_approval → extended → accepted / declined / expired / rescinded` (rescind is also legal from draft/pending; pending may fall back to draft; terminals are immutable — re-offering means a new row). At most **one open offer per candidate**. `expires_at` is set at *extend* time, and expiry never auto-flips the status — only `record_offer_decision` does, on the principal's say-so. `package_md` carries the full offer-package artifact; `approval_run_id` / `approved_by_person_id` record the sign-off; `nudge_action_ids_json` tracks the scheduled expiry reminders so a decision can cancel them.\n\nThe original external-**Client** entity was removed; engagement is now top-level. Because there is no migration tooling, `initialize_db` does a one-time reset — it drops the legacy talent tables when it detects a `clients` table, then rebuilds the new shape. Recruiting workflows that named the hiring org now use *this* company's name (from the profile via `reminders.company_name()`).\n\n## Talent specialist\n\n`talent` — Head of Talent & Executive Search (`openexecutive.agents.talent`, deep-reasoning), registered in `SPECIALIST_REGISTRY`. Prompt `TALENT_PROMPT` in `prompts/domain_prompts.py`; the RAG alias maps `talent → [\"hr\", \"strategy\"]` until a dedicated talent corpus is seeded.\n\n## Matching graph (Phase 2)\n\nNon-archived candidates are indexed into a dedicated ChromaDB collection `talent_candidates` (kept separate from the knowledge/company collections so candidate profiles never blend into RAG). `talent.graph` exposes `match_candidates_for_engagement` (ranks the whole pool against a role's must-haves) and `find_similar_candidates` (excludes the query candidate). Indexing is best-effort — a vector-store outage degrades search but never breaks candidate CRUD.\n\n## Recruiting workflows (Phase 3)\n\nFour workflows, all **draft-and-approve** — they schedule reminders to the **principal** and never message candidates or references directly (candidates are not roster `Person` records). They share `talent.reminders` (`resolve_reminder_context`, `principal_channel`, `schedule_reminder`):\n\n- **candidate_screen** — scores a candidate against an engagement; persists the fit score + scorecard.\n- **candidate_outreach** — first-touch + timed follow-up reminders.\n- **interview_coordination** — interview loop + availability request.\n- **reference_check** — reference rubric + reference outreach.\n\nMulti-LLM is intentionally not a separate build: non-Claude models already route via OpenRouter by model slug.\n\n## Closing the hire loop\n\nTwo workflows take the funnel past \"interviewed\" — through the offer and into the first 90 days:\n\n- **offer_approval** — drafts the offer package for an interviewed candidate (terms via the `chro` specialist anchored on the engagement's `comp_band`; closing plan — risks, competing-offer posture, recommended expiry window — via the `talent` specialist), persists the Offer (`pending_approval`, package on the row), advances the candidate to `offer`, DMs the **HIRING_SIGNOFF** approver (`find_approvers`, principal fallback), and pauses on a `WaitForHumanEvent` gate — the **first built-in workflow to use the gate**. Because paused runs never auto-resume (see [Workflows](#workflows)), the gate exists to *record* the sign-off: the `pending_approval → extended` transition is the explicit `extend_offer` follow-up (chat tool or `POST /offers/{id}/extend`), which consults the recorded resolution via `talent.offers` — a recorded rejection blocks it; a pending/absent sign-off proceeds on the principal's explicit instruction with the gap flagged in the response.\n- **new_hire_onboarding** — the placed → `Person` handoff. Requires the candidate to be `placed` or hold an accepted offer. Idempotently creates/updates the roster Person (match by email, else exact name; role from the engagement; no authority scopes granted), drafts a role-specific 30/60/90 plan via the `chro` specialist, and schedules day-7/30/60/90 check-in reminders to the principal. Person creation is **never** an implicit side effect of a stage change — `record_offer_decision(accepted)` and `set_candidate_stage(placed)` only *suggest* running it.\n\nExpiry posture: `extend_offer` schedules T−3d / T−1d / T+12h reminder nudges (plain `ad_hoc` scheduled actions assigned to the principal). Nudges remind; they never write. The candidate-contact invariant extends here: OE never sends an offer to a candidate and never messages a new hire — the approver gets the sign-off request, the principal gets the reminders.\n\n## Chat & briefing integration\n\nThe vertical is wired into the three surfaces that make Open Executive feel like one assistant, so it is not a siloed UI:\n\n- **MCP server** — the executive-search pipeline is exposed to *external* agents over the [MCP server](#mcp_server): an `oe://talent/engagements` resource plus read-only search tools (`list_candidates`, `get_candidate`, `match_candidates`, `find_similar_candidates`) that read `talent.store` and rank via `talent.graph`. The `talent` specialist's advice is reachable there via `consult_specialist`. Writes and workflow execution are deliberately not exposed over MCP.\n- **Chat tools** (`orchestrator.talent_tools`, registered in the Executive's main loop) let the Executive act on the pipeline in conversation. Read tools — `list_engagements`, `list_candidates`, `get_candidate`, `match_candidates`, `list_offers` — never emit an action chip; the write tools are side-effecting and chipped: `set_candidate_stage` (a light, reversible pipeline move), `start_talent_workflow` (runs the talent workflows via the runs store; `offer_approval` pauses on its gate and reports `awaiting_human` instead of completing), `create_engagement` / `create_candidate` (build the pipeline from chat, mirroring the `/talent` API routes), and the offer-lifecycle tools `create_offer` (manual draft when the principal dictates terms), `extend_offer`, and `record_offer_decision` (`accepted` also places the candidate and fills the engagement). The shared extend/decide logic lives in `talent.offers` so chat and HTTP can't drift. The `/talent` UI remains the home for heavier editing and bulk work.\n- **Briefing** — `briefing.talent_digest` rolls active engagements up by pipeline stage (`offers_expiring_soon` / `needs_screening` / `offers_out` / `stalled` signals — expiring offers are computed straight from `expires_at`, so a missed nudge can't make the briefing stale). This one rollup feeds the `/today` `talent` field, the briefing's **Executive search** card (click-to-discuss → chat), the 'what's going on' narrative, and the chat `<briefing>` block — so the cards, the header, and chat never disagree about a search's state.\n\n## API & UI\n\n`api.routes.talent` exposes CRUD for `/engagements`, `/candidates` (plus `/candidates/{id}/stage`, per-entity `/archive`), the graph endpoints `GET /engagements/{id}/matches`, `GET /candidates/{id}/similar`, `POST /talent/reindex`, and the offer lifecycle: `GET`/`POST /offers`, `GET`/`PATCH /offers/{id}`, `POST /offers/{id}/extend`, `POST /offers/{id}/decision`, `POST /offers/{id}/archive` (lifecycle conflicts are 409s). The `/talent` UI renders the pipeline board, the **Searches** list at `/talent/searches`, and candidate detail — which now carries an **Offer panel** (status pill, terms, collapsible package, expiry countdown, lifecycle buttons, and the onboarding launcher once the candidate is hired).\n\n## Deferred\n\nCRM/ATS integration, direct candidate sends (\"Phase 3b\"), automated resume intake, and multi-tenancy (Phase 4) are not yet built.",- "mermaid": "flowchart TD\n Engagement[Engagement / search] --> Candidate[Candidate]\n Candidate -->|indexed| Graph[(talent_candidates<br/>ChromaDB)]\n Engagement -->|match| Graph\n Candidate --> WF{Recruiting workflows}\n WF --> Screen[candidate_screen]\n WF --> Outreach[candidate_outreach]\n WF --> Interview[interview_coordination]\n WF --> Reference[reference_check]\n Screen --> Reminder[Reminder to principal]\n Outreach --> Reminder\n Interview --> Reminder\n Reference --> Reminder\n Candidate --> OfferWF[offer_approval]\n OfferWF --> Offer[Offer row<br/>pending_approval]\n OfferWF -->|gate| Approver[HIRING_SIGNOFF approver]\n Approver -->|approve recorded| Extend[extend_offer]\n Extend --> Nudges[Expiry nudges to principal]\n Extend --> Decision{record_offer_decision}\n Decision -->|accepted| Placed[Candidate placed<br/>engagement filled]\n Placed --> Onboard[new_hire_onboarding]\n Onboard --> Person[Person on roster<br/>+ 30/60/90 check-ins]",- "generated_at": "2026-06-10T00:00:00Z"-}diff --git a/packages/core/openexecutive/architecture/prebuilt/today.json b/packages/core/openexecutive/architecture/prebuilt/today.jsonindex e81f01ff..c7e297a1 100644--- a/packages/core/openexecutive/architecture/prebuilt/today.json+++ b/packages/core/openexecutive/architecture/prebuilt/today.json@@ -1,7 +1,7 @@{"section_id": "today","title": "Today / Morning Brief",- "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory).\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n- **`talent`** — the active executive-search pipeline, rolled up by `briefing.talent_digest.build_talent_brief_items`: one item per non-terminal engagement (FILLED/CANCELLED dropped) with role, department, status, candidate count, per-stage counts, and four attention signals — `offers_expiring_soon` (extended offers within 72h of `expires_at`, or past it with no decision recorded — computed straight from the offers table so a missed nudge can't make the briefing stale), `needs_screening` (leads), `offers_out` (offers), and `stalled_count` (active candidates not touched in ≥7 days). Items sort expiring → offers → stalled → leads → size. It renders as the briefing's **Executive search** card (one per search; click-to-discuss hands off to chat via the same `onContinue` path), feeds the narrative (an offer landing or a search going cold re-writes the header — the narrative cache hash folds a talent fingerprint), and the same digest's `format_talent_for_prompt` is appended to the chat `<briefing>` block so the Executive can discuss live searches by client or role. One rollup, shared by all four surfaces, so the card / header / chat never disagree. See the Talent section.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",- "mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n TALENT[\"talent<br/>(open searches, by stage)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n BUILD --> TALENT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class TALENT storage\n class NARR compute\n class MB compute",+ "markdown": "`openexecutive.api.routes.today` serves the morning brief — a one-screen, read-only view of what is happening across the org. It is the default landing surface (the Next.js root renders `<Briefing>`).\n\n`GET /today` returns `TodayResponse` assembled by `_build_today()`, which is synchronous and caller-agnostic:\n\n- **`departments`** — per-department goal health, rolling up each department's goal counts (`total`, `at_risk`, `off_track`) plus its awaiting-workflow count, and `attention_goals`: the actual off-track/at-risk goals (worst first, capped at 3) with `key_result`, `current`, `target`, and `status`, so the briefing's Department card shows *which* goal is off and how far without a click. Empty for healthy/inactive departments.\n- **`people`** — an attention-ranked roster. Each person carries `awaiting_action` count, soonest SLA, a `status` (`on_leave` / `needs_reply` / `awaiting` / `clear`), reachability, `overdue`, a server `priority` sort key, and a cached one-line `insight`. Sorted by `(-priority, full_name)`.\n- **`proposals`** — the *live* unread alerts (workflow approvals, triage-classified inbound, Executive signals, flagged artifacts, and gated calendar bookings): unread, inside their category TTL, not snoozed — see *Alert lifecycle* below. Each carries `score`, `category` (`action` vs `monitoring`), `surfaced_reason` from `openexecutive.briefing.ranking`, the lifecycle fields (`occurrence_count`, `last_seen_at`, `last_reviewed_at`, `review_verdict`, `review_note`, `recommended_move`, `why_now`, `due_at`, `superseded_count`, `suggested_workflow`), and `decision_instance_id` (set only when the proposal is backed by a decision-ledger row — a calendar booking awaiting approval). The UI splits them into 'mine' vs 'across the team' using `caller_person_id`. For decision-backed proposals the card's Approve/Reject call the `/decisions` endpoints (which book or cancel the event server-side and clear the alert) instead of the ack-and-hand-off-to-chat flow — so meeting bookings are reviewed in the briefing itself rather than on a separate page.\n- **`narrative`** — a per-viewer Executive-voice header synthesized by `synthesize_briefing_narrative`; the principal gets the whole-company scope, teammates a role-scoped one. In the web UI each bullet of this narrative is a click target: clicking one hands off to chat (the same `onContinue` path as the proposal cards) seeded to discuss that item. The Executive recognizes it because every chat turn now carries a `<briefing>` digest of open alerts (see Memory).\n- **`in_flight`** / **`awaiting`** — upcoming Executive commitments and people we are waiting on.\n- **`handled_overnight`** — the autonomous moves the Executive *completed* since the last delivered morning brief: the alert review's (routed, nudged, escalated, drafted, merged, closed) plus the research watch policy's (`watching` — a watch added on its own because it was grounded in company data; `stopped_watching` — a research watch auto-disabled as noisy or dead; no alert id, re-enable from `/watchlist`). A `changed` verdict (the review rewrote an open alert's headline / body / severity) is deliberately **not** here: the alert is still open in \"Needs you\" and its card carries the note, so the brief reports it under \"what changed\" (a REWRITTEN block) rather than as done. Each row is structured, not just a sentence: `kind`, the audit `summary` (nudge bookkeeping marker stripped), `at`, `alert_id`, `event_type` (for a pre-filtered `/audit` deep link), `headline` (the alert's headline at move time; a watch's slug), `target` (person name for routed / nudged, survivor headline for merged, new severity for escalated, draft title, workflow name), `detail` (the cited evidence or the watch policy's reason), `outcome` (`resolved` | `dismissed` for a close, `proposed` for a route that went through the authority gate), `evidence_ref` (S1 / R2 / A3), `superseded_by_alert_id`, and `status` — the alert's lifecycle state **now** (`open` = live in the queue per `lifecycle.is_live` | `resolved` | `dismissed` | `expired` | `merged` | `acked` | `inactive` for snoozed / past-TTL rows), looked up per row so a close the principal already undid renders as reopened instead of offering a second Undo, and a \"still open\" jump link only appears when there is a card to land on. The morning brief also carries a one-line count of research watch suggestions waiting on `/watchlist`.\n\nThe route resolves the caller from `x-caller-email`, then attaches the viewer-scoped narrative in a `BackgroundTask` so the request never blocks on an LLM call. `GET /today/activity` returns the recent self-initiated action rail — merged from fired scheduled actions (DMs, follow-ups, nudges, cadences), logged decisions, saved advice, completed workflow runs (briefings/check-ins/research), kicked-off initiatives, resolved gated decisions, and raised alerts, so it reflects all of the Executive's activity rather than just dispatched messages. The Pulse page (`/memories`) polls it (limit 100) every ~20s so new events stream into the 'Recent activity' card, which scrolls internally at a fixed height instead of growing the page. The `morning_brief` workflow calls `_build_today()` directly to build the standalone DM (via a different, enumerated prompt). `GET /morning-brief` is a deprecated alias.\n\n## Alert lifecycle & the Executive review\n\nAlerts used to be write-once: raised, then never looked at again, so the \"Needs you\" queue grew without bound and the briefs re-listed it daily. Three things now keep it live:\n\n- **Time-to-live** (`openexecutive.alerts.lifecycle`). Action items expire after `ALERT_TTL_DAYS_ACTION` (14 d), unrouted low/medium monitoring signals after `ALERT_TTL_DAYS_MONITORING` (3 d). Every surface reads `list_live_alerts` (the same predicate the scheduler's 15-minute sweep persists as status `expired`), so `/today` is right even before the sweep runs. Artifacts and decision-backed alerts are exempt. `POST /alerts/{id}/reopen` is the Undo.\n- **Coalescing** (`alerts.pipeline` + `store.coalesce_alert`). A repeat of an open alert with the same `(source, dedup_key)` updates that row — `occurrence_count`, `last_seen_at`, severity max — instead of stacking a second card, and only re-pings when severity rose to high/urgent. Monitoring alerts carry a stable `watch:<slug>` key, so one watch means one card.\n- **The review** (`openexecutive.alerts.review`, heartbeat `alert_review_scan`, every 6 h and right before the morning brief). For each open alert the Executive sees what changed since it was raised — newer signals from the same watch, related alerts, activity since, the roster with SLAs, department authority — and returns a verdict (relevant / changed / resolved / stale) plus a recommended move. Deterministic policy then acts: **route** (assign + DM the owner; `propose_via_alert` for propose-only departments), **nudge**, **escalate** (severity + `due_at` + DM the principal only), **draft** (`draft_artifact`), **suggest a workflow** (a link, never a run), **merge** (`superseded_by_alert_id`), or **resolve** — only on high confidence citing a server-minted evidence ref (a newer signal, a related alert, an activity item shown for that alert); free text never closes a card, and anything weaker is annotated `likely_stale`, demoted 30 ranking points, and left for one click. Everything that came from outside is rendered as inert data inside the review prompt, so an injected email body cannot steer the batch. Board / comp / legal matters only ever go to a scope-holder or the principal and keep their text. Route and escalate are idempotent across passes, every DM carries an \"[Alert review] Re: …\" header, outbound moves are capped per pass, passes are single-flight, `ALERT_REVIEW_ENABLED=false` stops every caller, every move is audited with its evidence and prior state, and a distinct `resolved` status keeps Executive closes separate from `ack` (user approved).\n\nOn the page, cards read as decisions: the one-line \"what changed since you last looked\" (`review_note`) leads, the recommended move is the primary control (Nudge <owner> → chat; Run <workflow> → `/jobs/<name>`), with chips for age, seen ×N, why-now / due, folded-in and draft-ready, a \"Reviewed <ago>\" footer, and an amber Likely-stale treatment with one-click Dismiss. \"Needs you\" shows *Start here* + 8 cards + \"Show N more\", a \"Dismiss N older than 7 days\" footer (explicit ids to `POST /alerts/bulk-ack` — never a server-side age sweep, which would hit teammates' routed items), and \"Re-check relevance\" (`POST /alerts/review`). The handled rail (anchor of the \"Executive handled N overnight\" pill) is deliberately one sentence by default: a first-person heading built from counts only — \"Since your last brief: N off your plate (closes still standing, and merges whose survivor is not itself listed; a merge into a listed survivor counts on that survivor's row), N in others' hands (routed / nudged), N waiting on you (escalated)\", plus \"N drafts ready\", \"N workflows suggested\", \"N watch changes\", \"N other moves\" (a kind the UI does not know) and \"N back on your plate\" (a close that is open again) when present — with the rows behind a \"details\" disclosure, and nothing rendered at all when the grouped rows are empty. The pure logic (grouping, headline, links) lives in `packages/ui/src/lib/handled.ts` and is covered by `npm test`. Expanded, it shows one first-person row per alert (\"Resolved *X* — evidence\", \"Dismissed *X* as stale — evidence\", \"Handed *X* to Dana Kim\" / \"Proposed *X* to Dana Kim (awaiting their approval)\", \"Chased Dana Kim on *X*\", \"Raised *X* to high\", \"Drafted *T* from *X*\", \"Folded *X* into *Y*\", \"Started watching *slug*\"), escalations first; rows sharing an alert collapse to the newest move with the others as an \"also …\" trailer — a close always keeps the visible slot (it carries Undo), otherwise an escalation beats routed / nudged / drafted; a merge whose survivor is listed becomes \"N duplicates folded in\" on the survivor. Every row links its `evidence_ref` (or \"evidence\") to `/audit?event_type=…&q=…` (the audit page pre-fills those filters from the query string), a still-open row jumps to its card (`#alert-<id>`), drafted rows link `/artifacts`, watch rows `/watchlist`. Undo is offered only while the close still stands (`status` not `open`); a reverted close shows \"Reopened\". Dismissing a watch-sourced alert lowers that watch's `trust_score` (which discounts ranking and is shown to the review as evidence); the ack body may carry `mute_topic`.\n\n## Multi-client practice section\n\nIn multi-client practice mode (2+ client slots — see the Client Companies section), the response gains an additive `practice_clients` list: rollup cards for the **parked** clients (overdue follow-ups, awaiting replies, unread alerts, onboarding due soon, renewal countdowns), each stamped with the save point its data reflects. Single-company installs always receive an empty list and the UI renders nothing.",+ "mermaid": "flowchart TD\n REQ[\"GET /today\"]\n BUILD[\"_build_today()\"]\n DEPTS[\"departments<br/>(per-dept goal health)\"]\n ROSTER[\"people<br/>(attention-ranked roster)\"]\n PROPS[\"proposals<br/>(unread alerts, routed)\"]\n INFLIGHT[\"in_flight<br/>(pending follow-ups / nudges)\"]\n AWAIT[\"awaiting<br/>(replies we await)\"]\n NARR[\"viewer-scoped narrative (BackgroundTask)\"]\n MB[\"morning_brief workflow\"]\n REQ --> BUILD\n BUILD --> DEPTS\n BUILD --> ROSTER\n BUILD --> PROPS\n BUILD --> INFLIGHT\n BUILD --> AWAIT\n REQ -->|\"resolve caller, attach\"| NARR\n MB -->|\"calls directly for standalone DM\"| BUILD\n class REQ entry\n class BUILD compute\n class DEPTS storage\n class ROSTER storage\n class PROPS storage\n class INFLIGHT storage\n class AWAIT storage\n class NARR compute\n class MB compute","generated_at": "2026-09-13T00:00:00+00:00"}diff --git a/packages/core/openexecutive/architecture/prebuilt/workflows.json b/packages/core/openexecutive/architecture/prebuilt/workflows.jsonindex 1cb6ca51..e0cf777e 100644--- a/packages/core/openexecutive/architecture/prebuilt/workflows.json+++ b/packages/core/openexecutive/architecture/prebuilt/workflows.json@@ -1,7 +1,7 @@{"section_id": "workflows","title": "Workflows",- "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 30 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design` — people and org artifacts.\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status`.\n- `offer_approval`, `new_hire_onboarding` — the talent vertical's hire-loop pair: offer package + sign-off gate, and the placed-candidate → roster-Person handoff with 30/60/90 check-ins (see [Talent](#talent)); `new_hire_onboarding` creates the roster Person that the staff-onboarding subsystem's plan delivery and ramp drip need — see [Staff Onboarding](#staff_onboarding).\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run, writes an `awaiting_human` row into `scheduled_actions`, and returns control to the user. `propose_only` departments route scheduled actions through this approval path rather than executing immediately. When the human replies on any channel, the `inbound_resolver` workflow matches the response to the paused run via its resume token, and `resumer.apply_resolution` records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The captured outcome surfaces on the Today dashboard.\n\nFull generator resume is **not yet implemented**: a paused run records the human's decision and stops — it does not re-enter the generator to run its remaining steps. `offer_approval` is the first *built-in* workflow to yield the gate (previously only dynamic workflows did), and it is designed around that gap: it yields its `result` and `artifact` events *before* the gate and persists the offer package onto the Offer row, so the gate's only job is to record the HIRING_SIGNOFF decision — the actual `pending_approval → extended` transition is the explicit `extend_offer` tool/route, which consults the recorded resolution.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — it never hangs waiting on a human. `executive_research` is excluded (it has the dedicated `run_executive_research` tool); the principal-targeting recurring workflows (`morning_brief`, `end_of_day_digest`, `executive_reflection`) stay launchable but the tool description flags that they dispatch real messages. Talent workflows remain better served by `start_talent_workflow`. A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat or a builder UI on `/jobs` — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of three kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The builder UI drives the `/workflows/custom` CRUD endpoints directly. An optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. Limitation: a gate followed by further steps pauses at `awaiting_human` and does not auto-continue (generator resume is deferred upstream), so gates belong immediately before synthesis.\n\nCompleted artifacts are discoverable in the unified Artifacts section (`/artifacts`) alongside their run-detail page at `/jobs/runs/{run_id}`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.",+ "markdown": "Workflows are deterministic, multi-step orchestrations. The built-ins are registered in `openexecutive.workflows.WORKFLOW_REGISTRY`; user-created (dynamic) workflows are stored as data (see below). Each follows the same contract: structured input feeds an ordered list of named steps that render a Markdown artifact, persisted via `complete_run` into `workflow_runs.artifact`. Every step emits a `WorkflowEvent` (start/progress/complete) streamed over SSE at `/workflows/{name}/runs`.\n\nThe registry holds 24 built-in workflows, plus any number of user-created ones. Representative built-ins:\n\n- `board_prep`, `quarterly_plan`, `annual_plan` — planning and governance deliverables.\n- `performance_review`, `comp_refresh`, `org_design`, `exec_search_brief` — people and org artifacts (the last is an advisory hiring brief / scorecard from the CHRO, kept when the recruiting pipeline was removed).\n- `crisis_comms`, `churn_deep_dive`, `competitive_teardown` — situational analyses.\n- `department_check_in` — runs on department cadence; its `goal_status` step returns structured verdicts persisted back to `department_goals.status`.\n\n### Change-aware principal briefs\n\n`morning_brief` and `end_of_day_digest` are the two recurring briefs the scheduler DMs to the principal. Both are now a *delta*, not a re-list: the window is \"since the last **delivered** brief\" (`briefing.brief_state.since_for`; 24 h on a cold store, clamped to 7 days), activity comes from `_build_activity(limit, since=…)`, proposals (action category only) split into *new since last brief* — enumerated, with each item's why-now and next move — versus a one-line carried-over count, a *rewritten* block lists carried items the review rewrote inside the window (`brief_state.rewritten_since`: verdict `changed`, still open — the brief reports them under \"what changed\", never as done), and a *handled overnight* block lists what the Executive's alert review **completed** on its own (`brief_state.handled_since`; the `changed` verdict is excluded because the alert is still open). Section order: top call → what changed → handled overnight → needs you (new only) → waiting on → at risk. A date-free fingerprint of the inputs is compared to the last delivered one; if unchanged the artifact is the one-liner \"Nothing new since yesterday's brief — N items still waiting on you.\" and no model call is made (`PRINCIPAL_BRIEF_SUPPRESS_UNCHANGED`; `force_full=true` on a manual run bypasses it). The workflow yields a `result` event with the fingerprint; only the scheduler records it, after a successful delivery, in `briefing_narrative` under scope `brief:<kind>` — so manual runs never advance the window.\n\n`executive_reflection` now carries memory: yesterday's standup (the previous completed run's artifact) is rendered into the context and the prompt forbids re-acting on anything listed there unless it changed; open alerts render with their id, review verdict and recommended move. Reflection never closes alerts — the alert review does, with evidence.\n\n### Wait-for-human pause\n\n`wait_for_human` (`openexecutive/workflows/wait_for_human.py`) is a first-class step primitive that pauses a run, writes an `awaiting_human` row into `scheduled_actions`, and returns control to the user. `propose_only` departments route scheduled actions through this approval path rather than executing immediately. When the human replies on any channel, the `inbound_resolver` workflow matches the response to the paused run via its resume token, and `resumer.apply_resolution` records the decision, marks the run `resolved`, and writes an audit row. A timeout applies the step's `on_timeout` policy (escalate / auto_proceed / fail). The captured outcome surfaces on the Today dashboard.\n\nFull generator resume is **not yet implemented**: a paused run records the human's decision and stops — it does not re-enter the generator to run its remaining steps. No built-in workflow currently yields the gate; only user-created dynamic workflows do, and a dynamic workflow that pauses must be designed around that gap — emit the `result` and `artifact` events *before* the gate and persist anything downstream code needs, so the gate's only job is to record the decision.\n\n### Launching from chat\n\nWorkflows are not only reachable from the `/jobs` UI — the Executive can list and run any of them mid-conversation. `openexecutive.orchestrator.workflow_run_tools` wires two tools into the main chat loop: `list_workflows` (the launchable catalog, with each workflow's input fields) and `run_workflow` (runs one to completion and returns its Markdown artifact, using the same engine as `POST /workflows/{name}/runs`). `run_workflow` resolves both built-ins and custom workflows via `get_workflow`, validates `inputs` against the workflow's input model, persists the run (`create_run` → `complete_run` / `fail_run`), and on an approval-gate step checkpoints the run as `awaiting_human` exactly as the HTTP route does — it never hangs waiting on a human. `executive_research` is excluded (it has the dedicated `run_executive_research` tool); the principal-targeting recurring workflows (`morning_brief`, `end_of_day_digest`, `executive_reflection`) stay launchable but the tool description flags that they dispatch real messages. A successful run surfaces an `action_taken` chip linking to `/jobs/runs/{run_id}`.\n\n### Dynamic (user-created) workflows\n\nUsers create reusable workflows on the fly — from the executive chat or a builder UI on `/jobs` — without shipping code. A dynamic workflow is a stored JSON definition (the `dynamic_workflows` table) interpreted at runtime by one generic `DynamicWorkflow` engine (`openexecutive/workflows/dynamic.py`) that implements the same `Workflow` ABC as the built-ins, so the run path, SSE streaming, run persistence, and `/jobs/[name]` form rendering are unchanged. `get_workflow` / `list_workflows` fall through to the dynamic store after the static registry (built-ins win on a name collision).\n\nA definition declares free-text input fields and an ordered step list of three kinds: **specialist** (consult a specialist with a goal prompt, optionally grounded by RAG), **approval_gate** (a `wait_for_human` pause), and a terminal **synthesis** step that assembles the artifact. `validate_definition` enforces the structural rules: exactly one terminal synthesis step, valid specialists, `{placeholder}` tokens that reference declared input fields, rostered approval/cadence people, and a parseable cadence.\n\nAuthoring from chat uses a **draft → confirm** handshake: the Executive calls `draft_workflow` (validate; return a `confirm_token` plus a plan summary), shows the user the plan, then calls `save_workflow` with the same definition and token — a token mismatch is rejected, so the saved workflow is exactly what the user approved. The builder UI drives the `/workflows/custom` CRUD endpoints directly. An optional cadence (`daily@` / `weekly@` / `quarterly@`) re-uses the scheduler via the `dynamic_workflow` action kind, which runs the workflow on schedule and DMs the artifact to a rostered recipient. Limitation: a gate followed by further steps pauses at `awaiting_human` and does not auto-continue (generator resume is deferred upstream), so gates belong immediately before synthesis.\n\nCompleted artifacts are discoverable in the unified Artifacts section (`/artifacts`) alongside their run-detail page at `/jobs/runs/{run_id}`.\n\n## Data-driven retrospectives\n\n`engagement_value_report` introduces a new workflow pattern: instead of the user typing the substance into a form (the `investor_update` / `mbr` shape), the workflow **reads its substance from the database**. A deterministic gatherer (`clients/engagement_activity.py`) pulls the period's decisions, initiatives, advisory consultations, delivered workflow artifacts (excluding prior value reports), follow-through counts, and alerts handled — from the live DB for the active client, or a parked client slot's `state.db` opened read-only. A single board-comms call narrates those facts (the prompt forbids inventing anything not in them; an empty period skips the LLM entirely), and the artifact's lists are assembled deterministically. Built for renewal conversations — the engagement record is the evidence.","mermaid": "flowchart TD\n Input[\"Structured input\"]\n Steps[\"Ordered named steps\"]\n Wait[\"wait_for_human pause\"]\n Sched[\"scheduled_actions<br/>(awaiting_human)\"]\n Resolver[\"inbound_resolver<br/>+ resumer\"]\n Artifact[\"Markdown artifact<br/>(workflow_runs.artifact)\"]\n Today[\"Today / Artifacts\"]\n Input --> Steps\n Steps --> Wait\n Wait --> Sched\n Sched -- \"human reply\" --> Resolver\n Resolver -- \"resolved\" --> Steps\n Steps -- \"complete_run\" --> Artifact\n Artifact --> Today\n class Input entry\n class Steps compute\n class Wait compute\n class Sched storage\n class Resolver compute\n class Artifact storage\n class Today external",- "generated_at": "2026-09-13T00:00:00+00:00"+ "generated_at": "2026-09-17T14:16:08.593444+00:00"}diff --git a/packages/core/openexecutive/architecture/sections.py b/packages/core/openexecutive/architecture/sections.pyindex 36fd029c..64a6b3ac 100644--- a/packages/core/openexecutive/architecture/sections.py+++ b/packages/core/openexecutive/architecture/sections.py@@ -233,29 +233,6 @@ SECTIONS: list[SectionSpec] = [wants_mermaid=True,diagram_kind="flowchart",),- # `talent` — the talent-intelligence / executive-search vertical built on- # OE (new top-level module under packages/core; see `talent:` in- # architecture-facts.yaml). Phases 1-3: entities + store, candidate- # matching graph, and recruiting-automation workflows, plus the /talent UI.- SectionSpec(- id="talent",- title="Talent / Executive Search",- sub="The executive-search vertical: clients, engagements, candidates, the ChromaDB matching graph, and the draft-and-approve recruiting workflows — surfaced in the /talent UI.",- kb_query="talent executive search candidate engagement client pipeline matching outreach screening",- wants_mermaid=True,- diagram_kind="flowchart",- ),- # `staff_onboarding` — onboarding a person INTO the company (distinct from- # the company-setup wizard in `onboarding/` and the people roster). New- # top-level module; see `staff_onboarding:` in architecture-facts.yaml.- SectionSpec(- id="staff_onboarding",- title="Staff Onboarding",- sub="Role-tailored onboarding for new hires: reusable templates, per-hire plans with phased task checklists, the role_onboarding brief workflow, a bounded ramp drip, and chat + /today integration.",- kb_query="staff onboarding new hire ramp plan template task checklist welcome brief role_onboarding completion",- wants_mermaid=True,- diagram_kind="flowchart",- ),# `clients` — named client-company slots for fractional / multi-client# use. New top-level module; see `clients:` in architecture-facts.yaml.SectionSpec(diff --git a/packages/core/openexecutive/briefing/narrative.py b/packages/core/openexecutive/briefing/narrative.pyindex ca5b2d6d..55bcd2b4 100644--- a/packages/core/openexecutive/briefing/narrative.py+++ b/packages/core/openexecutive/briefing/narrative.py@@ -23,10 +23,6 @@ from openexecutive.alerts.lifecycle import parse_awarelogger = logging.getLogger(__name__)-# Cap how many open searches the narrative lists before it stops enumerating —-# the header is a synthesis, not an exhaustive roster (the cards carry the rest).-_TALENT_NARRATIVE_CAP = 8-# Standalone morning-brief DM prompt. Unlike the /today header, this is# delivered as a DM with NO cards beside it — so it MUST enumerate what needs# the principal's attention (it's the only thing they see). Whole-company,@@ -229,27 +225,6 @@ def render_briefing_context()parts.append("")- talent = today_data.get("talent", [])- notable_searches = [- t for t in talent- if t.get("offers_out", 0) or t.get("stalled_count", 0) or t.get("needs_screening", 0)- ]- if notable_searches:- parts.append("OPEN EXECUTIVE SEARCHES NEEDING ATTENTION:")- for t in notable_searches[:_TALENT_NARRATIVE_CAP]:- flags = []- if t.get("offers_out", 0):- flags.append(f"{t['offers_out']} offer(s) out")- if t.get("stalled_count", 0):- flags.append(f"{t['stalled_count']} stalled")- if t.get("needs_screening", 0):- flags.append(f"{t['needs_screening']} to screen")- role = t.get("role_title", "")- dept = t.get("department", "")- label = f"{role} ({dept})" if dept else role- parts.append(f"- {label}: {', '.join(flags)}")- parts.append("")-if activity:parts.append("OE ACTIVITY SINCE LAST BRIEF (most recent first):")for item in activity[:15]:diff --git a/packages/core/openexecutive/briefing/narrative_cache.py b/packages/core/openexecutive/briefing/narrative_cache.pyindex 990d9ea9..8329fb20 100644--- a/packages/core/openexecutive/briefing/narrative_cache.py+++ b/packages/core/openexecutive/briefing/narrative_cache.py@@ -117,19 +117,6 @@ def build_narrative_input_hash(for p in today_data.get("people", [])if p.get("awaiting_count", 0))- # Fingerprint the talent pipeline by the signals the narrative actually- # surfaces (offers out, stalled, leads to screen) so a search going cold —- # or an offer landing — re-writes the brief, while volatile fields (ids- # aside, timestamps) don't churn it.- talent = sorted(- (- t.get("engagement_id", 0),- t.get("needs_screening", 0),- t.get("offers_out", 0),- t.get("stalled_count", 0),- )- for t in today_data.get("talent", [])- )payload = {"scope": scope,"prompt_version": NARRATIVE_PROMPT_VERSION,@@ -137,7 +124,6 @@ def build_narrative_input_hash("proposals": proposals,"depts": depts,"awaiting": awaiting,- "talent": talent,}blob = json.dumps(payload, sort_keys=True, default=str)return hashlib.sha256(blob.encode("utf-8")).hexdigest()diff --git a/packages/core/openexecutive/briefing/onboarding_digest.py b/packages/core/openexecutive/briefing/onboarding_digest.pydeleted file mode 100644index 00562f86..00000000--- a/packages/core/openexecutive/briefing/onboarding_digest.py+++ /dev/null@@ -1,183 +0,0 @@-"""Staff-onboarding digest for the briefing surfaces.--Mirrors ``briefing/talent_digest.py``: one rollup that both ``/today`` and the-chat ``<briefing>`` block share, so the structured cards and the chat digest-never disagree.--- :func:`build_onboarding_brief_items` → structured ``OnboardingBriefItem`` list- for a dedicated ``/today`` section.-- :func:`format_onboarding_for_prompt` → a compact one-line-per-plan digest the- chat route appends to the user-turn briefing so the Executive proactively- knows who is onboarding and what's overdue.--Every entry point swallows its own errors and returns an empty result, so an-onboarding-store hiccup can never break a brief or a chat turn.-"""-from __future__ import annotations--import logging-from datetime import UTC, date, datetime-from pathlib import Path--from pydantic import BaseModel--from openexecutive.staff_onboarding.models import OnboardingStatus, TaskStatus--logger = logging.getLogger(__name__)--# Plans in these statuses are still in flight; COMPLETED / ARCHIVED drop off.-_ACTIVE_STATUSES: frozenset[OnboardingStatus] = frozenset(- {OnboardingStatus.DRAFT, OnboardingStatus.ACTIVE}-)--_OPEN_TASK_STATUSES: frozenset[TaskStatus] = frozenset(- {TaskStatus.PENDING, TaskStatus.IN_PROGRESS}-)--_MAX_PLANS = 25---class OnboardingBriefItem(BaseModel):- """One in-flight onboarding plan, rolled up for the briefing surfaces."""-- plan_id: int- full_name: str- role: str = ""- status: str- current_phase: str- completion_pct: int = 0- open_tasks: int = 0- overdue_tasks: int = 0- days_to_start: int | None = None # negative once the hire has started---def _parse_date(iso: str) -> date | None:- try:- return date.fromisoformat(iso[:10])- except (ValueError, TypeError):- return None---def build_onboarding_brief_items(- db_path: Path | None = None,- *,- limit: int = _MAX_PLANS,-) -> list[OnboardingBriefItem]:- """Roll in-flight onboarding plans up into briefing items.-- Returns ``[]`` on any failure (e.g. the tables don't exist yet on a fresh- install) rather than raising, so callers never have to guard it.- """- from openexecutive.staff_onboarding import store-- try:- plans = store.list_plans(db_path=db_path)- except Exception:- logger.exception("onboarding_digest.list_plans_failed")- return []-- today = datetime.now(UTC).date()- items: list[OnboardingBriefItem] = []-- for plan in plans:- if plan.status not in _ACTIVE_STATUSES or plan.id is None:- continue- try:- tasks = store.list_tasks(plan.id, db_path=db_path)- except Exception:- logger.exception("onboarding_digest.list_tasks_failed plan_id=%s", plan.id)- tasks = []-- open_tasks = 0- overdue = 0- for t in tasks:- if t.status not in _OPEN_TASK_STATUSES:- continue- open_tasks += 1- due = _parse_date(t.due_date) if t.due_date else None- if due is not None and due < today:- overdue += 1-- start = _parse_date(plan.start_date)- days_to_start = (start - today).days if start is not None else None-- items.append(- OnboardingBriefItem(- plan_id=plan.id,- full_name=plan.full_name,- role=plan.role,- status=plan.status.value,- current_phase=plan.current_phase.value,- completion_pct=plan.completion_pct,- open_tasks=open_tasks,- overdue_tasks=overdue,- days_to_start=days_to_start,- )- )-- # Most attention-worthy first: overdue tasks, then least complete, then- # soonest to start. Stable so ties keep store order.- items.sort(- key=lambda i: (- -i.overdue_tasks,- i.completion_pct,- i.days_to_start if i.days_to_start is not None else 9999,- )- )- return items[:limit]---def format_onboarding_for_prompt(- db_path: Path | None = None,- *,- limit: int = _MAX_PLANS,-) -> str:- """Render in-flight onboardings as a compact digest, or ``""`` when none.-- One line per plan::-- [plan <id>] <name> — <role> (<phase>, <pct>% done): N open · K overdue · starts in D days-- Pure synchronous reads — wrap in ``asyncio.to_thread`` at the call site.- Never raises.- """- items = build_onboarding_brief_items(db_path=db_path, limit=limit)- if not items:- return ""-- lines: list[str] = []- for it in items:- parts = [f"{it.completion_pct}% done"]- if it.open_tasks:- parts.append(f"{it.open_tasks} open")- if it.overdue_tasks:- parts.append(f"{it.overdue_tasks} overdue")- if it.days_to_start is not None:- if it.days_to_start > 0:- parts.append(f"starts in {it.days_to_start}d")- elif it.days_to_start < 0:- # Start date is day 1, so the day after start (days_to_start=-1)- # is day 2 — hence abs()+1.- parts.append(f"day {abs(it.days_to_start) + 1}")- else:- parts.append("starts today")- role = f" — {it.role}" if it.role else ""- lines.append(- f"[plan {it.plan_id}] {it.full_name}{role} "- f"({it.current_phase}): " + " · ".join(parts)- )-- header = (- "New hires currently onboarding — the principal sees these as cards on "- "/today. Each line is [plan <id>] name — role (phase): progress rollup. "- "When the user asks about a hire's onboarding, this is what they mean; "- "use the onboarding tools to pull or update plan detail."- )- return header + "\n" + "\n".join(lines)---__all__ = [- "OnboardingBriefItem",- "build_onboarding_brief_items",- "format_onboarding_for_prompt",-]diff --git a/packages/core/openexecutive/briefing/talent_digest.py b/packages/core/openexecutive/briefing/talent_digest.pydeleted file mode 100644index 97947376..00000000--- a/packages/core/openexecutive/briefing/talent_digest.py+++ /dev/null@@ -1,253 +0,0 @@-"""Talent / executive-search pipeline digest for the briefing surfaces.--The talent vertical (in-house searches / candidates) shipped as a standalone-``/talent`` UI plus a set of workflows, but neither ``/today`` nor ``/chat`` knew-it existed. This module is the single rollup the two surfaces share, mirroring-``briefing/context.py`` (which does the same job for open alerts):--- :func:`build_talent_brief_items` → structured ``TalentBriefItem`` list rendered- as a dedicated section on ``/today`` and the briefing UI.-- :func:`format_talent_for_prompt` → a compact one-line-per-engagement digest the- chat route appends to the user-turn ``<briefing>`` block so the Executive can- discuss live search progress.--Both read the same active engagements + their candidate pipelines and roll the-candidates up by stage, so the structured cards and the chat digest never-disagree. Every entry point swallows its own errors and returns an empty result-so a talent-store hiccup can never break a brief or a chat turn.-"""-from __future__ import annotations--import logging-from datetime import UTC, datetime-from pathlib import Path--from pydantic import BaseModel, Field--from openexecutive.talent.models import CandidateStage, EngagementStatus, OfferStatus--logger = logging.getLogger(__name__)--# A candidate counts as "stalled" once it has sat in a non-terminal stage this-# many days without an update. The search principal usually wants these surfaced-# first — they are the ones quietly going cold.-STALL_THRESHOLD_DAYS = 7--# Candidates in these stages are still in play; PLACED / REJECTED are terminal-# off-ramps and never count toward "stalled".-_ACTIVE_STAGES: frozenset[CandidateStage] = frozenset(- {- CandidateStage.LEAD,- CandidateStage.SCREENED,- CandidateStage.INTERVIEWED,- CandidateStage.OFFER,- }-)--# Cap how many engagements the brief / digest carries so a large book of-# business can't blow the /today payload or the per-turn token budget.-_MAX_ENGAGEMENTS = 25--# An extended offer counts as "expiring soon" once it is within this many-# hours of its expiry (or already past it without a recorded decision).-OFFER_EXPIRY_SOON_HOURS = 72---class TalentBriefItem(BaseModel):- """One open search engagement, rolled up for the briefing surfaces.-- ``stage_counts`` maps each :class:`CandidateStage` value to the number of- active (non-archived) candidates currently in it. ``needs_screening``- (leads), ``offers_out`` (offers), and ``stalled_count`` are the three- attention signals the UI badges and the narrative can lead with.- """-- engagement_id: int- role_title: str- department: str = ""- status: str- location: str = ""- candidate_count: int = 0- stage_counts: dict[str, int] = Field(default_factory=dict)- needs_screening: int = 0- offers_out: int = 0- # Extended offers whose expires_at is within OFFER_EXPIRY_SOON_HOURS (or- # already past, with no decision recorded) — the most time-critical signal.- offers_expiring_soon: int = 0- stalled_count: int = 0---def _age_days(iso_ts: str, *, now: datetime) -> float | None:- """Whole-and-fractional days between *iso_ts* and *now*, or None if unparseable."""- if not iso_ts:- return None- try:- parsed = datetime.fromisoformat(iso_ts)- except ValueError:- return None- if parsed.tzinfo is None:- parsed = parsed.replace(tzinfo=UTC)- return (now - parsed).total_seconds() / 86400.0---def build_talent_brief_items(- db_path: Path | None = None,- *,- limit: int = _MAX_ENGAGEMENTS,-) -> list[TalentBriefItem]:- """Roll active (open / on-hold) engagements up into briefing items.-- FILLED and CANCELLED engagements are dropped — the brief is about searches- that still need attention. Returns ``[]`` on any failure (e.g. the talent- tables don't exist yet on a fresh install) rather than raising, so callers- never have to guard it.- """- from openexecutive.talent import store as talent_store-- try:- engagements = talent_store.list_engagements(db_path=db_path)- except Exception:- logger.exception("talent_digest.list_engagements_failed")- return []-- now = datetime.now(UTC)- items: list[TalentBriefItem] = []-- for eng in engagements:- if eng.status in (EngagementStatus.FILLED, EngagementStatus.CANCELLED):- continue- if eng.id is None:- continue-- try:- candidates = talent_store.list_candidates(engagement_id=eng.id, db_path=db_path)- except Exception:- logger.exception("talent_digest.list_candidates_failed engagement_id=%s", eng.id)- candidates = []-- stage_counts: dict[str, int] = {}- stalled = 0- for cand in candidates:- stage_counts[cand.stage.value] = stage_counts.get(cand.stage.value, 0) + 1- if cand.stage in _ACTIVE_STAGES:- age = _age_days(cand.updated_at, now=now)- if age is not None and age >= STALL_THRESHOLD_DAYS:- stalled += 1-- items.append(- TalentBriefItem(- engagement_id=eng.id,- role_title=eng.role_title,- department=eng.department,- status=eng.status.value,- location=eng.location,- candidate_count=len(candidates),- stage_counts=stage_counts,- needs_screening=stage_counts.get(CandidateStage.LEAD.value, 0),- offers_out=stage_counts.get(CandidateStage.OFFER.value, 0),- offers_expiring_soon=_count_expiring_offers(eng.id, now=now, db_path=db_path),- stalled_count=stalled,- )- )-- # Most attention-worthy first: expiring offers, then offers out, then- # stalled, then leads waiting to be screened, then larger pipelines.- # Stable so ties keep store order.- items.sort(- key=lambda i: (- i.offers_expiring_soon, i.offers_out, i.stalled_count,- i.needs_screening, i.candidate_count,- ),- reverse=True,- )- return items[:limit]---def _count_expiring_offers(- engagement_id: int, *, now: datetime, db_path: Path | None = None-) -> int:- """Extended offers on this engagement within (or past) the expiry window.-- Computed straight from ``expires_at`` — a missed nudge can't make the- digest go stale. Swallows failures to 0, like every rollup here.- """- from openexecutive.talent import store as talent_store-- try:- offers = talent_store.list_offers(- engagement_id=engagement_id, status=OfferStatus.EXTENDED, db_path=db_path- )- except Exception:- logger.exception("talent_digest.list_offers_failed engagement_id=%s", engagement_id)- return 0- soon = 0- for offer in offers:- if not offer.expires_at:- continue- try:- expiry = datetime.fromisoformat(offer.expires_at)- except ValueError:- continue- if expiry.tzinfo is None:- expiry = expiry.replace(tzinfo=UTC)- if (expiry - now).total_seconds() <= OFFER_EXPIRY_SOON_HOURS * 3600:- soon += 1- return soon---def format_talent_for_prompt(- db_path: Path | None = None,- *,- limit: int = _MAX_ENGAGEMENTS,-) -> str:- """Render active engagements as a compact digest, or ``""`` when none.-- One line per engagement::-- [eng <id>] <role> [· <department>] (<status>): N candidates · M need- screening · K offers out · S stalled >7d-- Pure synchronous reads — wrap in ``asyncio.to_thread`` at the call site.- Never raises: any failure logs and returns ``""`` so a chat turn is never- blocked by a talent-store hiccup.- """- items = build_talent_brief_items(db_path=db_path, limit=limit)- if not items:- return ""-- lines: list[str] = []- for it in items:- parts = [f"{it.candidate_count} candidate{'s' if it.candidate_count != 1 else ''}"]- if it.needs_screening:- parts.append(f"{it.needs_screening} need screening")- if it.offers_out:- parts.append(f"{it.offers_out} offer{'s' if it.offers_out != 1 else ''} out")- if it.offers_expiring_soon:- parts.append(- f"{it.offers_expiring_soon} offer"- f"{'s' if it.offers_expiring_soon != 1 else ''} expiring ≤3d"- )- if it.stalled_count:- parts.append(f"{it.stalled_count} stalled >{STALL_THRESHOLD_DAYS}d")- dept = f" · {it.department}" if it.department else ""- lines.append(- f"[eng {it.engagement_id}] {it.role_title}{dept} "- f"({it.status}): " + " · ".join(parts)- )-- header = (- "Open searches we're hiring for in this company — the principal sees "- "these as cards on /today. Each line is [eng <id>] role · department "- "(status): pipeline rollup. When the user asks about a search by role, "- "this is what they mean; use the talent tools to pull candidate detail."- )- return header + "\n" + "\n".join(lines)---__all__ = [- "OFFER_EXPIRY_SOON_HOURS",- "STALL_THRESHOLD_DAYS",- "TalentBriefItem",- "build_talent_brief_items",- "format_talent_for_prompt",-]diff --git a/packages/core/openexecutive/clients/cockpit.py b/packages/core/openexecutive/clients/cockpit.pyindex 6508ee60..089c7348 100644--- a/packages/core/openexecutive/clients/cockpit.py+++ b/packages/core/openexecutive/clients/cockpit.py@@ -5,7 +5,7 @@ The slot architecture's deliberate ceiling is that only the active client isanyway, without touching that ceiling: every parked slot's ``state.db`` is acomplete SQLite snapshot sitting on disk, so we open it **read-only, inplace** and count what matters — overdue follow-ups, awaiting replies,-unread alerts, onboarding tasks coming due. The active client is read from+unread alerts. The active client is read fromthe live DB instead (its slot copy is only as fresh as the last save-back).Honesty contract: parked data is as fresh as each slot's ``saved_at``; every@@ -20,7 +20,7 @@ from __future__ import annotationsimport loggingimport sqlite3-from datetime import UTC, datetime, timedelta+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -35,9 +35,6 @@ from openexecutive.clients.slots import (logger = logging.getLogger(__name__)-# Onboarding tasks due within this window count as "due soon".-_ONBOARDING_DUE_SOON_DAYS = 7-class ClientCockpitCard(BaseModel):"""One client's practice-level rollup for the cockpit board."""@@ -57,9 +54,6 @@ class ClientCockpitCard(BaseModel):overdue_actions: int | None = Noneawaiting_replies: int | None = Noneunread_alerts: int | None = None- # Onboarding tasks due within the window OR already overdue (both need- # attention — see the deliberate no-lower-bound note in _fill_state_counts).- onboarding_due_soon: int | None = None# Freshness + degradation.saved_at: str | None = None # parked cards: when this data was capturedhas_state: bool = False@@ -161,23 +155,6 @@ def _fill_state_counts(card.unread_alerts = _one(conn, "SELECT COUNT(*) FROM alerts WHERE status='unread'")- if "onboarding_tasks" in tables and "onboarding_plans" in tables:- # Deliberately no lower bound: this counts tasks due within the- # window AND tasks already overdue — both demand the operator's- # attention, and an overdue ramp task dropping OFF the practice- # board would be the worse failure mode.- horizon = (- datetime.now(UTC) + timedelta(days=_ONBOARDING_DUE_SOON_DAYS)- ).isoformat()- card.onboarding_due_soon = _one(- conn,- "SELECT COUNT(*) FROM onboarding_tasks t "- "JOIN onboarding_plans p ON p.id = t.plan_id "- "WHERE p.status IN ('draft','active') "- "AND t.status IN ('pending','in_progress') "- "AND t.due_date <= ?",- (horizon,),- )finally:conn.close()diff --git a/packages/core/openexecutive/clients/rotation.py b/packages/core/openexecutive/clients/rotation.pyindex 975cb14d..7f27e56c 100644--- a/packages/core/openexecutive/clients/rotation.py+++ b/packages/core/openexecutive/clients/rotation.py@@ -288,8 +288,6 @@ def _compose_digest(bits.append(f"{c.awaiting_replies} awaiting reply")if c.unread_alerts:bits.append(f"{c.unread_alerts} alerts")- if c.onboarding_due_soon:- bits.append(f"{c.onboarding_due_soon} onboarding due")if isinstance(c.days_to_renewal, int) and c.days_to_renewal <= 30:bits.append("renewal due"diff --git a/packages/core/openexecutive/clients/slots.py b/packages/core/openexecutive/clients/slots.pyindex e7453f9f..c75b24b0 100644--- a/packages/core/openexecutive/clients/slots.py+++ b/packages/core/openexecutive/clients/slots.py@@ -5,8 +5,8 @@ of one client company:- ``state.db`` — transactionally-consistent copy of the shared SQLite DB(``VACUUM INTO`` on save, online backup API on restore). This carries chat- history, scheduled actions, onboarding plans, talent pipeline, departments,- people, watchlist — everything the stores keep.+ history, scheduled actions, departments, people, watchlist — everything the+ stores keep.- ``profile.yaml`` / ``docs/`` / ``skills/`` — the company directory artifacts.- ``mcp_servers.json`` — per-client external MCP tools (e.g. one client'sCrayon credentials). The MCP gateway reads this at process startup, so a@@ -119,6 +119,12 @@ _BLANK_WIPE_TABLES = ("watchlist","page_watch_state","outbound_context",+ # Legacy talent / staff-onboarding tables. Both features are gone and+ # nothing writes these any more, but the rows may still exist on upgraded+ # installs and they carry candidate PII (names, employers, screening+ # summaries, offer comp) — keep wiping them so a blank slot never inherits+ # a previous client's pipeline. Existence-guarded, so a no-op on fresh+ # installs where the tables were never created."onboarding_tasks","onboarding_plans","onboarding_templates",@@ -546,22 +552,28 @@ def _ensure_schemas() -> None:from openexecutive.departments.store import initialize_db as init_departmentsfrom openexecutive.fixtures.store import initialize_db as init_fixturesfrom openexecutive.knowledge.review_store import ReviewStore+ from openexecutive.memory.episodic import cancel_orphaned_talent_remindersfrom openexecutive.memory.episodic import initialize_db as init_episodicfrom openexecutive.monitoring.store import initialize_db as init_monitoringfrom openexecutive.people.store import initialize_db as init_people- from openexecutive.staff_onboarding.store import initialize_db as init_onboarding- from openexecutive.talent.store import initialize_db as init_talent# Pass the path explicitly everywhere: some initializers bind their# DB_PATH default at import time, which would ignore a runtime override.db_path = _episodic_db_path()init_episodic(db_path)+ # A parked slot's state.db may predate the talent removal; give it the+ # same one-shot reminder sweep the live DB gets at boot.+ try:+ swept = cancel_orphaned_talent_reminders(db_path)+ except Exception:+ logger.exception("client-slots: orphaned-reminder sweep failed")+ else:+ if swept:+ logger.info("client-slots: cancelled %d orphaned talent reminder(s)", swept)init_alerts(db_path)init_fixtures(db_path)initialize_overrides_db(db_path)init_people(db_path)- init_talent(db_path)- init_onboarding(db_path)init_departments(db_path)init_monitoring(db_path)ReviewStore.initialize_db(db_path)@@ -607,12 +619,6 @@ def _reseed_blank_defaults(*, seed_departments: bool = True) -> None:seed_default_departments()except Exception:logger.exception("client-slots: seed_default_departments failed")- try:- from openexecutive.staff_onboarding.seed import seed_default_templates-- seed_default_templates()- except Exception:- logger.exception("client-slots: seed_default_templates failed")try:from openexecutive.scheduler.runner import seed_principal_briefsdiff --git a/packages/core/openexecutive/evals/_scenarios/talent_001.yaml b/packages/core/openexecutive/evals/_scenarios/talent_001.yamldeleted file mode 100644index e3b30ce3..00000000--- a/packages/core/openexecutive/evals/_scenarios/talent_001.yaml+++ /dev/null@@ -1,20 +0,0 @@-id: talent_001-domain: talent-description: "Executive-search candidate fit assessment against engagement must-haves"-company_context:- stage: "Private equity portfolio"- industry: "Oil & Gas (upstream)"- headcount: 220-query: "We're running a VP Operations search for one of our portfolio companies — a 200-person independent that needs a turnaround. One finalist ran a 4,000-person operations org at a supermajor; the other led a 150-person turnaround at a struggling independent but has a shorter resume. Score them against the mandate and tell me who to advance."-expected_topics:- - stage_and_scale_fit- - turnaround_vs_scale_experience- - evidence_anchored_fit_score- - biggest_risk_and_probe-required_routing:- - talent-quality_criteria:- gives_fit_assessment: true- scores_against_mandate_not_generic: true- names_biggest_risk: true- gives_clear_recommendation: truediff --git a/packages/core/openexecutive/evals/_scenarios/talent_002.yaml b/packages/core/openexecutive/evals/_scenarios/talent_002.yamldeleted file mode 100644index 40a726f6..00000000--- a/packages/core/openexecutive/evals/_scenarios/talent_002.yaml+++ /dev/null@@ -1,18 +0,0 @@-id: talent_002-domain: talent-description: "Pipeline status question — Executive surfaces live search state and a concrete next step"-company_context:- stage: "Private equity portfolio"- industry: "Oil & Gas"- headcount: 220-query: "How are our open executive searches going, and what should I move on first?"-expected_topics:- - open_engagement_status- - candidates_needing_attention- - concrete_next_step-required_routing:- - talent-quality_criteria:- references_pipeline_state: true- recommends_specific_next_action: true- prioritizes_clearly: truediff --git a/packages/core/openexecutive/evals/_scenarios/talent_003.yaml b/packages/core/openexecutive/evals/_scenarios/talent_003.yamldeleted file mode 100644index b5c356f8..00000000--- a/packages/core/openexecutive/evals/_scenarios/talent_003.yaml+++ /dev/null@@ -1,20 +0,0 @@-id: talent_003-domain: talent-description: "Offer structuring and close — comp-band anchoring, expiry, sign-off, never-contact posture"-company_context:- stage: "Private equity portfolio"- industry: "Oil & Gas (upstream)"- headcount: 220-query: "We're ready to make an offer to our VP Drilling finalist. The band is 280-340k base plus 0.4-0.6% equity, and she just told us she's in late stages with a competitor. How should we structure the offer and run the close?"-expected_topics:- - comp_band_anchored_terms- - competing_offer_posture- - offer_expiry_window- - signoff_before_extending-required_routing:- - talent-quality_criteria:- anchors_terms_to_the_band: true- addresses_competing_offer: true- recommends_expiry_window: true- keeps_principal_as_sender_not_oe: truediff --git a/packages/core/openexecutive/evals/_scenarios/talent_004.yaml b/packages/core/openexecutive/evals/_scenarios/talent_004.yamldeleted file mode 100644index 6818c646..00000000--- a/packages/core/openexecutive/evals/_scenarios/talent_004.yaml+++ /dev/null@@ -1,20 +0,0 @@-id: talent_004-domain: hr-description: "New-hire onboarding — 30/60/90 structure with milestone check-ins after a closed search"-company_context:- stage: "Private equity portfolio"- industry: "Oil & Gas (upstream)"- headcount: 220-query: "We closed the VP Drilling search — she signed yesterday and starts in three weeks. What should her first 90 days look like, and how do we make sure it stays on track?"-expected_topics:- - thirty_sixty_ninety_structure- - role_specific_outcomes- - milestone_check_ins- - early_warning_signs-required_routing:- - chro-quality_criteria:- gives_structured_30_60_90: true- ties_outcomes_to_the_role: true- recommends_check_in_cadence: true- flags_early_drift_signals: truediff --git a/packages/core/openexecutive/guide/prebuilt/staff_onboarding.json b/packages/core/openexecutive/guide/prebuilt/staff_onboarding.jsondeleted file mode 100644index 3268320c..00000000--- a/packages/core/openexecutive/guide/prebuilt/staff_onboarding.json+++ /dev/null@@ -1,7 +0,0 @@-{- "section_id": "staff_onboarding",- "title": "Staff Onboarding",- "markdown": "**What it is:** Templated ramp-up plans for new hires — a checklist, a schedule, and a welcome brief, so nobody's first month depends on someone remembering.\n\n**What it does:**\n\n- Create a plan per hire from a **template**: tasks with assignees and due dates relative to the start date.\n- Track progress through phases — pre-start, day one, week one, and on through ramp — with a completion percentage.\n- Wire in a manager and a buddy from your People roster.\n- Generate a **welcome brief** (who they report to, the team, tools, policies) and drip check-ins at milestones like day 7 and day 30.\n- See active plans in your daily briefing, and move tasks along from chat.\n\n*Note: this is for ramping employees you've hired — company setup lives under Company Profile & Onboarding.*",- "mermaid": null,- "generated_at": "2026-06-11T00:00:00+00:00"-}diff --git a/packages/core/openexecutive/guide/prebuilt/talent.json b/packages/core/openexecutive/guide/prebuilt/talent.jsondeleted file mode 100644index 237c3293..00000000--- a/packages/core/openexecutive/guide/prebuilt/talent.json+++ /dev/null@@ -1,7 +0,0 @@-{- "section_id": "talent",- "title": "Talent",- "markdown": "**What it is:** The hiring pipeline — open searches (engagements) and the candidates moving through them, from first lead to signed offer.\n\n**What it does:**\n\n- Define an **engagement** for each open role: title, department, comp band, location, and must-haves.\n- Track candidates on a stage board — lead → screened → interviewed → offer → placed — with rejection possible at any stage.\n- Score each candidate (0–100 fit score) and keep screening summaries and notes on their record.\n- Manage **offers** through their own lifecycle: draft, approval, extended, then accepted or declined.\n- Ask about candidates and searches straight from chat — the Executive can look the pipeline up mid-conversation.\n\n*Note: offers that need sign-off route through the same approval flow as everything else, to whoever holds hiring authority.*",- "mermaid": null,- "generated_at": "2026-06-11T00:00:00+00:00"-}diff --git a/packages/core/openexecutive/guide/sections.py b/packages/core/openexecutive/guide/sections.pyindex 97a6dfe5..9f35b329 100644--- a/packages/core/openexecutive/guide/sections.py+++ b/packages/core/openexecutive/guide/sections.py@@ -74,16 +74,6 @@ GUIDE_SECTIONS: list[GuideSection] = [title="People",sub="Your roster — who the Executive coordinates with, their SLAs, channels, and approval scopes.",),- GuideSection(- id="talent",- title="Talent",- sub="Candidate searches and hiring — engagements, pipeline stages, scoring, and offers.",- ),- GuideSection(- id="staff_onboarding",- title="Staff Onboarding",- sub="Templated ramp-up plans for new hires — tasks, phases, check-ins, and welcome briefs.",- ),GuideSection(id="company_profile",title="Company Profile & Onboarding",diff --git a/packages/core/openexecutive/knowledge/retriever.py b/packages/core/openexecutive/knowledge/retriever.pyindex 732988f6..bf2a3d03 100644--- a/packages/core/openexecutive/knowledge/retriever.py+++ b/packages/core/openexecutive/knowledge/retriever.py@@ -154,9 +154,6 @@ DOMAIN_ALIASES: dict[str, list[str]] = {"cmo": ["marketing"],"cpo": ["product", "strategy"],"board_comms": ["board", "finance"],- # The talent specialist reuses the existing HR + strategy knowledge- # domains until a dedicated `talent` knowledge corpus is seeded (Phase 2).- "talent": ["hr", "strategy"],}diff --git a/packages/core/openexecutive/mcp_server/server.py b/packages/core/openexecutive/mcp_server/server.pyindex e012b9eb..c07c8c69 100644--- a/packages/core/openexecutive/mcp_server/server.py+++ b/packages/core/openexecutive/mcp_server/server.py@@ -48,7 +48,7 @@ logger = logging.getLogger(__name__)# ``orchestrator/router.SPECIALIST_REGISTRY`` by a unit test. Declared as a# ``Literal`` so MCP clients see a proper enum in the tool schema.SpecialistKey = Literal[- "board_comms", "cfo", "chro", "cmo", "coo", "cpo", "cso", "gc", "talent", "triage"+ "board_comms", "cfo", "chro", "cmo", "coo", "cpo", "cso", "gc", "triage"]_INSTRUCTIONS = (@@ -57,16 +57,12 @@ _INSTRUCTIONS = ("can ground itself in this company without re-explaining it.\n\n""Resources (read-only, company-internal): company profile, today's ""briefing and recent activity, the people roster, department state, "- "episodic memory (past decisions, initiatives, advice), and the "- "executive-search pipeline (active engagements by stage).\n\n"+ "and episodic memory (past decisions, initiatives, advice).\n\n""Tools: `consult_specialist` (domain analysis from a CFO/CSO/etc., grounded ""in company knowledge), `search_knowledge` (curated MBA + company-doc ""retrieval), `list_workflows` (catalog of multi-step executive workflows), "- "`ask_executive` (a single synthesized answer from the Executive — a "- "fallback; prefer the specialist tool and resources), and a read-only "- "executive-search suite — `list_candidates` / `get_candidate` (browse a "- "search's pipeline) and `match_candidates` / `find_similar_candidates` "- "(semantic candidate search over the talent graph)."+ "and `ask_executive` (a single synthesized answer from the Executive — a "+ "fallback; prefer the specialist tool and resources).")mcp = FastMCP(@@ -102,58 +98,6 @@ def _json(payload: Any) -> str:return json.dumps(payload, default=str, ensure_ascii=False)-# Upper bound on talent search result counts, so a client-supplied limit can't-# request an unbounded scan.-_MAX_MATCH_RESULTS = 50---def _clamp_match_limit(limit: int) -> int:- """Clamp a client-supplied search limit to 1..._MAX_MATCH_RESULTS."""- return max(1, min(limit, _MAX_MATCH_RESULTS))---def _candidate_brief(candidate: Any) -> dict[str, Any]:- """Compact candidate view for list / search results.-- Full detail (incl. screening_summary) is available via ``get_candidate``.- """- return {- "candidate_id": candidate.id,- "engagement_id": candidate.engagement_id,- "full_name": candidate.full_name,- "current_title": candidate.current_title,- "current_company": candidate.current_company,- "stage": candidate.stage.value,- "fit_score": candidate.fit_score,- }---def _enrich_matches(matches: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Add each match candidate's name/title so results name people, not ids.-- Runs synchronously inside an ``asyncio.to_thread`` wrapper alongside the- graph query, so there is no extra event-loop hop per candidate.- """- from openexecutive.talent import store as talent_store-- out: list[dict[str, Any]] = []- for match in matches:- cid = match.get("candidate_id")- full_name = current_title = None- # `cid` comes from ChromaDB metadata; coerce defensively so a malformed- # id degrades to an un-enriched row rather than raising out of the thread.- try:- cid_int = int(cid) if cid is not None else None- except (TypeError, ValueError):- cid_int = None- if cid_int is not None:- cand = talent_store.get_candidate(cid_int)- if cand is not None:- full_name, current_title = cand.full_name, cand.current_title- out.append({**match, "full_name": full_name, "current_title": current_title})- return out--# ---------------------------------------------------------------------------# Resources — company-grounded context. Read-only, no LLM calls. The unique# thing OE has that a generic agent does not.@@ -264,19 +208,6 @@ async def memory_advice() -> str:return _json([r.model_dump(mode="json") for r in rows])- "oe://talent/engagements",- name="Talent: active searches",- description="Active executive-search engagements rolled up by pipeline stage.",- mime_type="application/json",-)-async def talent_engagements() -> str:- from openexecutive.briefing.talent_digest import build_talent_brief_items-- items = await asyncio.to_thread(build_talent_brief_items)- return _json([it.model_dump(mode="json") for it in items])--# ---------------------------------------------------------------------------# Tools — structured capabilities. The flagship is consult_specialist.# ---------------------------------------------------------------------------@@ -290,8 +221,7 @@ async def consult_specialist(domain-expert read. Specialists: cso (strategy/M&A/OKRs), cfo (finance/uniteconomics/fundraising), chro (people/comp/org design), gc (legal/contracts/compliance), coo (operations/process/metrics), cmo (GTM/brand/PR), cpo- (product/roadmap), board_comms (board decks/IR/governance), talent (executive- search — candidate screening/fit scoring, energy-sector talent mapping),+ (product/roadmap), board_comms (board decks/IR/governance),triage (chief of staff — significance of inbound events).Args:@@ -391,136 +321,6 @@ async def ask_executive(message: str, caller_email: str = "") -> str:)-# ----------------------------------------------------------------------------# Talent / executive-search tools — read-only search over the candidate-# pipeline. The `oe://talent/engagements` resource exposes the engagement-# rollup; these parameterized tools read and rank candidates within a search.-# The talent specialist's ADVICE is already reachable via consult_specialist;-# writes and workflow execution are intentionally NOT exposed over MCP.-# ----------------------------------------------------------------------------async def list_candidates(engagement_id: int, stage: str = "") -> str:- """List the candidates in one executive-search engagement's pipeline.-- Returns a JSON list of candidates, each with id, name, current title /- company, pipeline stage, and fit_score. Discover engagement ids from the- ``oe://talent/engagements`` resource.-- Args:- engagement_id: The engagement (search) whose candidates to list.- stage: Optional pipeline stage filter — one of lead, screened,- interviewed, offer, placed, rejected. Empty returns all stages.- """- from openexecutive.talent import store as talent_store- from openexecutive.talent.models import CandidateStage-- stage_filter: CandidateStage | None = None- if stage:- try:- stage_filter = CandidateStage(stage)- except ValueError:- valid = ", ".join(s.value for s in CandidateStage)- return _json({"error": f"invalid stage {stage!r}. Valid: {valid}"})-- def _run() -> Any:- # Signal a missing engagement explicitly (matching get_candidate /- # match_candidates) so a client can tell "no such search" from "an- # empty pipeline" — list_candidates would otherwise return [] for both.- if talent_store.get_engagement(engagement_id) is None:- return {"error": "not_found", "engagement_id": engagement_id}- candidates = talent_store.list_candidates(- engagement_id=engagement_id, stage=stage_filter- )- return [_candidate_brief(c) for c in candidates]-- return _json(await asyncio.to_thread(_run))---async def get_candidate(candidate_id: int) -> str:- """Fetch full detail for one candidate by id.-- Includes the fit_score and screening_summary produced by the candidate- screen, plus contact fields. Returns ``{"error": "not_found", ...}`` when no- candidate has that id.-- Args:- candidate_id: The candidate to fetch.- """- from openexecutive.talent import store as talent_store-- candidate = await asyncio.to_thread(talent_store.get_candidate, candidate_id)- # `store.get_candidate` does not filter soft-deletes, but the rest of this- # external surface (list_candidates, the talent index behind match/similar)- # excludes archived rows — so honor the soft-delete here too rather than- # leaking a removed candidate's full PII by id.- if candidate is None or candidate.archived:- return _json({"error": "not_found", "candidate_id": candidate_id})- return _json(candidate.model_dump(mode="json"))---async def match_candidates(engagement_id: int, limit: int = 10) -> str:- """Rank the candidate pool against an engagement's role and must-haves.-- Semantic search over the talent graph: returns up to ``limit`` candidates,- best first, each with a 0-1 match ``score`` plus name, title, and current- stage. Use to answer "who's the strongest fit for this search".-- Args:- engagement_id: The engagement to rank candidates against.- limit: Maximum matches to return (1-50, default 10).- """- from openexecutive.talent import graph as talent_graph- from openexecutive.talent import store as talent_store-- capped = _clamp_match_limit(limit)-- def _run() -> dict[str, Any]:- engagement = talent_store.get_engagement(engagement_id)- if engagement is None:- return {"error": "not_found", "engagement_id": engagement_id}- store = get_store()- if store is None:- return {"error": "knowledge store unavailable"}- matches = talent_graph.match_candidates_for_engagement(- engagement, store, limit=capped- )- return {"engagement_id": engagement_id, "matches": _enrich_matches(matches)}-- return _json(await asyncio.to_thread(_run))---async def find_similar_candidates(candidate_id: int, limit: int = 5) -> str:- """Find candidates whose profile is semantically similar to a given one.-- Excludes the query candidate. Returns up to ``limit`` matches, best first,- each with a 0-1 ``score`` plus name, title, and stage. Returns- ``{"error": "not_found", ...}`` when the candidate id is unknown.-- Args:- candidate_id: The candidate to find lookalikes for.- limit: Maximum matches to return (1-50, default 5).- """- from openexecutive.talent import graph as talent_graph- from openexecutive.talent import store as talent_store-- capped = _clamp_match_limit(limit)-- def _run() -> dict[str, Any]:- candidate = talent_store.get_candidate(candidate_id)- if candidate is None:- return {"error": "not_found", "candidate_id": candidate_id}- store = get_store()- if store is None:- return {"error": "knowledge store unavailable"}- matches = talent_graph.find_similar_candidates(candidate, store, limit=capped)- return {"candidate_id": candidate_id, "matches": _enrich_matches(matches)}-- return _json(await asyncio.to_thread(_run))--# ---------------------------------------------------------------------------# Mount.# ---------------------------------------------------------------------------diff --git a/packages/core/openexecutive/memory/episodic.py b/packages/core/openexecutive/memory/episodic.pyindex 7c673775..899d8310 100644--- a/packages/core/openexecutive/memory/episodic.py+++ b/packages/core/openexecutive/memory/episodic.py@@ -373,6 +373,15 @@ def initialize_db(db_path: Path = DB_PATH) -> None:);CREATE INDEX IF NOT EXISTS idx_outbound_ctx_lookupON outbound_context(channel, channel_ref, status, created_at DESC);++ -- One-shot data migrations. Schema changes above are idempotent+ -- DDL and need no bookkeeping; this table is for sweeps that must+ -- run exactly once per DB (e.g. cancelling rows a removed feature+ -- left behind). A migration inserts its name when it has applied.+ CREATE TABLE IF NOT EXISTS app_migrations (+ name TEXT PRIMARY KEY,+ applied_at TEXT NOT NULL+ );""")@@ -1305,6 +1314,75 @@ def cancel_scheduled_action(action_id: int, db_path: Path | None = None) -> str:return "cancelled"+# Intent-text shapes of the ad-hoc reminders the removed talent /+# staff-onboarding workflows scheduled on the principal's real DM channel.+# Nothing creates these any more, but rows pending from before the removal+# would keep firing (for weeks, in the outreach case) about candidates whose+# records are unreachable. They were `kind="ad_hoc"` with `department=''` on+# a live channel, so the scheduler's `__internal__` drain never sees them.+# Each pattern is the full generated template up to its first free-text+# field — deliberately NOT a bare prefix like "Outreach reminder %", which+# would also catch a reminder the Executive phrased that way for the+# principal's own work. (`talent.reminders`, `workflows.candidate_outreach`,+# `interview_coordination`, `reference_check`, `new_hire_onboarding`,+# `talent.offers` at the pre-removal commit.)+_ORPHANED_TALENT_REMINDER_PATTERNS: tuple[str, ...] = (+ "Outreach reminder %/% (%) for the % search (%). Send the principal %",+ "Interview coordination for % on the % search (%). Send the principal %",+ "Reference checks (%) for % on the % search (%). Send the principal %",+ "Onboarding check-in (day %) for %, % at %. DM the principal %",+ "Offer expiry reminder: the offer to % for the % role (offer %) %. DM the principal %",+)+_TALENT_REMINDER_SWEEP = "2026-09-cancel-talent-reminders"+++def cancel_orphaned_talent_reminders(db_path: Path | None = None) -> int:+ """One-shot sweep: cancel reminders left by the removed talent and+ staff-onboarding features. Returns the number of rows cancelled.++ Bounded by ``app_migrations``: the marker row is claimed FIRST with+ ``INSERT OR IGNORE`` inside the same transaction as the sweep, so of two+ processes booting against one DB exactly one does the work and the other+ is a clean no-op (no ``IntegrityError``). Every later call is a no-op even+ if a matching row appears afterwards. ``running`` rows are included: the+ scheduler's ``requeue_orphaned_running`` runs AFTER this sweep at boot and+ would otherwise resurrect a crash-orphaned row as ``pending``. Delete this+ function (and its callers) in the release after next, once every install+ has booted on it once.+ """+ with _get_conn(_resolve_db_path(db_path)) as conn:+ claimed = conn.execute(+ "INSERT OR IGNORE INTO app_migrations (name, applied_at) VALUES (?, ?)",+ (_TALENT_REMINDER_SWEEP, datetime.now(UTC).isoformat()),+ )+ if claimed.rowcount == 0:+ return 0+ shape = " OR ".join(+ "intent_text LIKE ?" for _ in _ORPHANED_TALENT_REMINDER_PATTERNS+ )+ cur = conn.execute(+ "UPDATE scheduled_actions "+ "SET status = 'cancelled', "+ " awaiting_response_since = NULL, "+ " last_error = 'cancelled: talent/staff-onboarding feature removed' "+ "WHERE status IN ('pending', 'running') "+ " AND kind = 'ad_hoc' AND department = '' "+ f" AND ({shape})",+ _ORPHANED_TALENT_REMINDER_PATTERNS,+ )+ # Delivered talent reminders still marked as awaiting a reply would+ # keep feeding the nudge engine ("chase the open commitment …") about+ # a dead candidate. Clear the flag; leave the rows as history.+ conn.execute(+ "UPDATE scheduled_actions SET awaiting_response_since = NULL "+ "WHERE awaiting_response_since IS NOT NULL AND status = 'done' "+ " AND kind = 'ad_hoc' AND department = '' "+ f" AND ({shape})",+ _ORPHANED_TALENT_REMINDER_PATTERNS,+ )+ return int(cur.rowcount)++def get_scheduled_action(action_id: int, db_path: Path | None = None) -> ScheduledAction | None:diff --git a/packages/core/openexecutive/orchestrator/action_chips.py b/packages/core/openexecutive/orchestrator/action_chips.pyindex 495bed0e..a481d549 100644--- a/packages/core/openexecutive/orchestrator/action_chips.py+++ b/packages/core/openexecutive/orchestrator/action_chips.py@@ -53,14 +53,6 @@ SIDE_EFFECTING_TOOLS: frozenset[str] = frozenset({# Triage / alerts"create_alert","ack_alert",- # Talent / executive-search pipeline mutations- "create_engagement",- "create_candidate",- "set_candidate_stage",- "start_talent_workflow",- "create_offer",- "extend_offer",- "record_offer_decision",# Universal workflow launcher (any built-in / custom workflow from chat)"run_workflow",# Research artifacts flagged for review@@ -150,8 +142,8 @@ def summarize_action(# paint a green ✓ chip over a red outcome.return Noneif parsed is not None and parsed.get("status") == "not_found":- # The target row didn't exist, so nothing changed (e.g. create_candidate- # for an unknown engagement). No state change → no ✓ chip.+ # The target row didn't exist, so nothing changed (e.g. archive_person+ # for an unknown person). No state change → no ✓ chip.return Noneif parsed is not None and parsed.get("noop") is True:# Idempotent re-call (e.g. `ack_alert` after the briefing UI already@@ -311,65 +303,6 @@ def summarize_action(url = tool_input.get("url", "")payload["summary"] = f"Connected MCP server: {url}" if url else "Connected MCP server"payload["target"] = url or None- elif tool_name == "create_engagement":- role = str(tool_input.get("role_title", "")).strip()- payload["summary"] = f"Opened search: {role}" if role else "Opened a search"- payload["target"] = role or None- payload["link"] = "/talent/searches"- elif tool_name == "create_candidate":- name = str(tool_input.get("full_name", "")).strip()- payload["summary"] = f"Added candidate {name}" if name else "Added a candidate"- payload["target"] = name or None- eid = tool_input.get("engagement_id")- if isinstance(eid, int):- payload["link"] = f"/talent/engagements/{eid}"- elif tool_name == "set_candidate_stage":- cid = tool_input.get("candidate_id")- stage = str(tool_input.get("stage", "")).replace("_", " ")- payload["summary"] = (- f"Moved candidate #{cid} → {stage}" if cid is not None and stage- else "Moved a candidate"- )- payload["target"] = str(cid) if cid is not None else None- if isinstance(cid, int):- payload["link"] = f"/talent/candidates/{cid}"- elif tool_name == "start_talent_workflow":- wf = str(tool_input.get("workflow", "")).replace("_", " ")- awaiting_signoff = (parsed or {}).get("status") == "awaiting_human"- if wf and awaiting_signoff:- payload["summary"] = f"Started {wf} — awaiting sign-off"- else:- payload["summary"] = f"Ran {wf}" if wf else "Ran a talent workflow"- payload["target"] = tool_input.get("workflow") or None- elif tool_name == "create_offer":- oid = tool_input.get("candidate_id")- payload["summary"] = (- f"Drafted an offer for candidate #{oid}" if oid is not None- else "Drafted an offer"- )- payload["target"] = str(oid) if oid is not None else None- if isinstance(oid, int):- payload["link"] = f"/talent/candidates/{oid}"- elif tool_name == "extend_offer":- oid = tool_input.get("offer_id")- payload["summary"] = (- f"Marked offer #{oid} extended" if oid is not None else "Marked an offer extended"- )- payload["target"] = str(oid) if oid is not None else None- cid = ((parsed or {}).get("offer") or {}).get("candidate_id")- if isinstance(cid, int):- payload["link"] = f"/talent/candidates/{cid}"- elif tool_name == "record_offer_decision":- oid = tool_input.get("offer_id")- decision = str(tool_input.get("decision", "")).strip()- payload["summary"] = (- f"Offer #{oid} {decision}" if oid is not None and decision- else "Recorded an offer decision"- )- payload["target"] = str(oid) if oid is not None else None- cid = ((parsed or {}).get("offer") or {}).get("candidate_id")- if isinstance(cid, int):- payload["link"] = f"/talent/candidates/{cid}"elif tool_name == "run_workflow":wf = str(tool_input.get("workflow", "")).replace("_", " ")run_id = (parsed or {}).get("run_id")diff --git a/packages/core/openexecutive/orchestrator/executive.py b/packages/core/openexecutive/orchestrator/executive.pyindex 1d12f54b..67649757 100644--- a/packages/core/openexecutive/orchestrator/executive.py+++ b/packages/core/openexecutive/orchestrator/executive.py@@ -49,10 +49,6 @@ from openexecutive.orchestrator.form_tools import (build_form_patch_event,)from openexecutive.orchestrator.mcp_gateway import MCP_TOOL_NAMES, MCP_TOOLS, MCPGateway-from openexecutive.orchestrator.onboarding_tools import (- ONBOARDING_TOOL_HANDLERS,- ONBOARDING_TOOLS,-)from openexecutive.orchestrator.people_tools import (PEOPLE_TOOL_HANDLERS,PEOPLE_TOOLS,@@ -73,10 +69,6 @@ from openexecutive.orchestrator.schedule_tools import ()from openexecutive.orchestrator.session import Sessionfrom openexecutive.orchestrator.skills_tools import SKILL_TOOL_HANDLERS, SKILL_TOOLS-from openexecutive.orchestrator.talent_tools import (- TALENT_TOOL_HANDLERS,- TALENT_TOOLS,-)from openexecutive.orchestrator.watchlist_tools import (WATCHLIST_TOOL_HANDLERS,WATCHLIST_TOOLS,@@ -163,8 +155,6 @@ _ALL_SKILL_TOOLS = [*RESEARCH_TOOLS,*WORKFLOW_AUTHORING_TOOLS,*WORKFLOW_RUN_TOOLS,- *TALENT_TOOLS,- *ONBOARDING_TOOLS,*FORM_TOOLS,]_ALL_SKILL_HANDLERS = {@@ -180,8 +170,6 @@ _ALL_SKILL_HANDLERS = {**RESEARCH_TOOL_HANDLERS,**WORKFLOW_AUTHORING_TOOL_HANDLERS,**WORKFLOW_RUN_TOOL_HANDLERS,- **TALENT_TOOL_HANDLERS,- **ONBOARDING_TOOL_HANDLERS,**FORM_TOOL_HANDLERS,}diff --git a/packages/core/openexecutive/orchestrator/onboarding_tools.py b/packages/core/openexecutive/orchestrator/onboarding_tools.pydeleted file mode 100644index 633226ce..00000000--- a/packages/core/openexecutive/orchestrator/onboarding_tools.py+++ /dev/null@@ -1,432 +0,0 @@-"""Anthropic tool definitions + handlers for the staff-onboarding framework.--Exposed to the Executive alongside the talent tools so onboarding can be driven-and inspected from chat: list/create/advance plans, list templates, complete a-task, and run the ``role_onboarding`` workflow (which generates the welcome-brief). Mirrors the shape of ``orchestrator.talent_tools``.--Registered in ``_ALL_SKILL_TOOLS`` / ``_ALL_SKILL_HANDLERS`` in-``orchestrator.executive``.-"""-from __future__ import annotations--import json-import logging-import uuid-from collections.abc import Awaitable, Callable-from typing import Any--from openexecutive.audit import log_event as audit_log-from openexecutive.staff_onboarding import service, store-from openexecutive.staff_onboarding.models import OnboardingStatus, TaskStatus--logger = logging.getLogger(__name__)--_STATUS_VALUES = [s.value for s in OnboardingStatus]-_MAX_SHORT = 200---def _audit(tool: str, kind: str, ok: bool, summary: str, details: dict[str, Any]) -> None:- audit_log(- "tool_invocation", summary, actor="executive",- details={"tool": tool, "kind": kind, "ok": ok, **details},- )---def _err(tool: str, msg: str) -> str:- _audit(tool, "read", False, f"{tool}: {msg}", {"error": msg[:300]})- return json.dumps({"error": msg})---# --------------------------------------------------------------------------- #-# Tool definitions-# --------------------------------------------------------------------------- #--LIST_ONBOARDING_PLANS_TOOL: dict[str, Any] = {- "name": "list_onboarding_plans",- "description": (- "List in-flight staff-onboarding plans (one per new hire) with a progress "- "rollup: name, role, phase, completion %, open and overdue tasks. Use this "- "to answer 'how is onboarding going?' or to resolve a hire's name to a "- "plan_id before get_onboarding_plan / advance_onboarding_plan. Archived "- "plans are omitted unless include_archived is set; pass status to narrow "- "(e.g. status='active'), or status='completed' to see finished ones."- ),- "input_schema": {- "type": "object",- "properties": {- "status": {"type": "string", "enum": _STATUS_VALUES,- "description": "Optional status filter (draft/active/completed/archived)."},- "include_archived": {"type": "boolean",- "description": "Include archived plans (default false)."},- },- },-}--GET_ONBOARDING_PLAN_TOOL: dict[str, Any] = {- "name": "get_onboarding_plan",- "description": (- "Get one onboarding plan in full: the hire, role, phase, completion %, the "- "generated welcome brief (if any), and every checklist task with its phase, "- "owner, due date, and status. Call list_onboarding_plans first if you need "- "the plan_id."- ),- "input_schema": {- "type": "object",- "properties": {"plan_id": {"type": "integer"}},- "required": ["plan_id"],- },-}--LIST_ONBOARDING_TEMPLATES_TOOL: dict[str, Any] = {- "name": "list_onboarding_templates",- "description": (- "List the reusable onboarding templates (role/department blueprints) a new "- "plan can be instantiated from. Returns each template's name, title, "- "department, task count, and ramp length."- ),- "input_schema": {"type": "object", "properties": {}},-}--CREATE_ONBOARDING_PLAN_TOOL: dict[str, Any] = {- "name": "create_onboarding_plan",- "description": (- "Create an onboarding plan for a new hire, optionally instantiating tasks "- "from a template (use list_onboarding_templates to pick one). Pass "- "person_id once the hire exists on the roster (that's what later unlocks "- "delivery + ramp). The plan starts in 'draft'. After creating, call "- "start_onboarding to generate the welcome brief."- ),- "input_schema": {- "type": "object",- "properties": {- "full_name": {"type": "string", "description": "New hire's name."},- "start_date": {"type": "string", "description": "Start date, ISO YYYY-MM-DD."},- "role": {"type": "string", "description": "Role/title, e.g. 'Fractional CFO'."},- "template_name": {"type": "string",- "description": "Optional template to instantiate tasks from."},- "person_id": {"type": "integer", "description": "Roster person id, if hired."},- "manager_person_id": {"type": "integer"},- "buddy_person_id": {"type": "integer"},- "engagement_id": {"type": "integer",- "description": "Talent engagement this hire came from, if any."},- "candidate_id": {"type": "integer",- "description": "Talent candidate this hire came from, if any."},- },- "required": ["full_name", "start_date"],- },-}--COMPLETE_ONBOARDING_TASK_TOOL: dict[str, Any] = {- "name": "complete_onboarding_task",- "description": (- "Mark an onboarding checklist task done (or set another status). Use the "- "task_id from get_onboarding_plan. status defaults to 'done'."- ),- "input_schema": {- "type": "object",- "properties": {- "task_id": {"type": "integer"},- "status": {"type": "string", "enum": [s.value for s in TaskStatus],- "description": "Defaults to 'done'."},- "completed_by_person_id": {"type": "integer"},- },- "required": ["task_id"],- },-}--ADVANCE_ONBOARDING_PLAN_TOOL: dict[str, Any] = {- "name": "advance_onboarding_plan",- "description": (- "Advance a plan to its next phase (pre_start → week_1 → day_30 → day_60 → "- "day_90). No-op if already at the final phase."- ),- "input_schema": {- "type": "object",- "properties": {"plan_id": {"type": "integer"}},- "required": ["plan_id"],- },-}--ACTIVATE_ONBOARDING_PLAN_TOOL: dict[str, Any] = {- "name": "activate_onboarding_plan",- "description": (- "Activate a draft onboarding plan: starts the daily ramp drip, posts a "- "welcome notice to the hire's department channel (if one is configured), "- "DMs intro-1:1 nudges to the manager and buddy, and schedules the day "- "7/30/60/90 check-ins. The ramp/check-ins only fire once the plan has a "- "roster person_id. Generate the brief first with start_onboarding. "- "Idempotent — safe to call once per plan."- ),- "input_schema": {- "type": "object",- "properties": {"plan_id": {"type": "integer"}},- "required": ["plan_id"],- },-}--START_ONBOARDING_TOOL: dict[str, Any] = {- "name": "start_onboarding",- "description": (- "Generate the role-tailored welcome brief (and optional daily ramp drip) "- "for a hire by running the role_onboarding workflow to completion. Pass a "- "plan_id to generate for and save onto an existing plan, OR full_name + "- "role for an ad-hoc brief. Returns the brief Markdown."- ),- "input_schema": {- "type": "object",- "properties": {- "plan_id": {"type": "integer"},- "full_name": {"type": "string"},- "role": {"type": "string"},- "function": {"type": "string",- "description": "engineering/sales/finance/… — picks the lead specialist."},- "ramp_days": {"type": "integer",- "description": "Daily ramp messages to generate (omit to use template)."},- },- },-}--ONBOARDING_TOOLS: list[dict[str, Any]] = [- LIST_ONBOARDING_PLANS_TOOL,- GET_ONBOARDING_PLAN_TOOL,- LIST_ONBOARDING_TEMPLATES_TOOL,- CREATE_ONBOARDING_PLAN_TOOL,- COMPLETE_ONBOARDING_TASK_TOOL,- ADVANCE_ONBOARDING_PLAN_TOOL,- ACTIVATE_ONBOARDING_PLAN_TOOL,- START_ONBOARDING_TOOL,-]---# --------------------------------------------------------------------------- #-# Handlers-# --------------------------------------------------------------------------- #---async def handle_list_onboarding_plans(tool_input: dict[str, Any]) -> str:- status_raw = tool_input.get("status")- status = None- if status_raw is not None:- try:- status = OnboardingStatus(str(status_raw))- except ValueError:- return _err("list_onboarding_plans", f"invalid status: {status_raw!r}")- include_archived = bool(tool_input.get("include_archived", False))- try:- plans = store.list_plans(status=status, include_archived=include_archived)- except Exception as exc:- logger.exception("list_onboarding_plans: failed")- return _err("list_onboarding_plans", str(exc))- out = [- {- "plan_id": p.id, "full_name": p.full_name, "role": p.role,- "status": p.status.value, "current_phase": p.current_phase.value,- "completion_pct": p.completion_pct, "start_date": p.start_date,- }- for p in plans- ]- return json.dumps({"status": "ok", "plans": out})---async def handle_get_onboarding_plan(tool_input: dict[str, Any]) -> str:- try:- plan_id = int(tool_input["plan_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("get_onboarding_plan", f"bad arguments: {exc}")- plan = store.get_plan(plan_id)- if plan is None:- return json.dumps({"status": "not_found", "plan_id": plan_id})- return json.dumps({"status": "ok", "plan": plan.model_dump()})---async def handle_list_onboarding_templates(tool_input: dict[str, Any]) -> str:- try:- templates = store.list_templates(active_only=True)- except Exception as exc:- logger.exception("list_onboarding_templates: failed")- return _err("list_onboarding_templates", str(exc))- out = [- {- "name": t.name, "title": t.title, "department": t.department,- "task_count": len(t.task_specs), "ramp_days": t.ramp_days,- }- for t in templates- ]- return json.dumps({"status": "ok", "templates": out})---def _opt_int(tool_input: dict[str, Any], key: str) -> int | None:- """Coerce an optional integer arg. Absent/blank → None; a present but- non-integer value raises ValueError so the handler can surface an error- rather than silently dropping (e.g.) a person_id and reporting success."""- val = tool_input.get(key)- if val is None or val == "":- return None- try:- return int(val)- except (TypeError, ValueError) as exc:- raise ValueError(f"{key} must be an integer, got {val!r}") from exc---async def handle_create_onboarding_plan(tool_input: dict[str, Any]) -> str:- full_name = str(tool_input.get("full_name", "")).strip()- start_date = str(tool_input.get("start_date", "")).strip()- if not full_name or not start_date:- return _err("create_onboarding_plan", "full_name and start_date are required")- role = str(tool_input.get("role", "") or "")- if len(full_name) > _MAX_SHORT or len(role) > _MAX_SHORT or len(start_date) > _MAX_SHORT:- return _err("create_onboarding_plan", "full_name/role/start_date too long")-- template = None- template_name = str(tool_input.get("template_name", "") or "").strip()- if template_name:- template = store.get_template(template_name)- if template is None:- return _err("create_onboarding_plan", f"unknown template {template_name!r}")-- try:- plan_id = service.instantiate_plan(- full_name=full_name,- start_date=start_date,- role=role,- template=template,- person_id=_opt_int(tool_input, "person_id"),- manager_person_id=_opt_int(tool_input, "manager_person_id"),- buddy_person_id=_opt_int(tool_input, "buddy_person_id"),- engagement_id=_opt_int(tool_input, "engagement_id"),- candidate_id=_opt_int(tool_input, "candidate_id"),- )- plan = store.get_plan(plan_id)- except Exception as exc:- logger.exception("create_onboarding_plan: failed")- return _err("create_onboarding_plan", str(exc))- if plan is None:- return _err("create_onboarding_plan", f"created plan {plan_id} but could not reload it")- _audit("create_onboarding_plan", "write", True,- f"create_onboarding_plan {plan_id} {full_name}",- {"plan_id": plan_id, "full_name": full_name, "template": template_name})- return json.dumps({"status": "ok", "plan": plan.model_dump()})---async def handle_complete_onboarding_task(tool_input: dict[str, Any]) -> str:- try:- task_id = int(tool_input["task_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("complete_onboarding_task", f"bad arguments: {exc}")- status = TaskStatus.DONE- status_raw = tool_input.get("status")- if status_raw is not None:- try:- status = TaskStatus(str(status_raw))- except ValueError:- return _err("complete_onboarding_task", f"invalid status: {status_raw!r}")- if store.get_task(task_id) is None:- return json.dumps({"status": "not_found", "task_id": task_id})- try:- completed_by = _opt_int(tool_input, "completed_by_person_id")- except ValueError as exc:- return _err("complete_onboarding_task", str(exc))- store.set_task_status(task_id, status, completed_by_person_id=completed_by)- _audit("complete_onboarding_task", "write", True,- f"complete_onboarding_task {task_id} → {status.value}",- {"task_id": task_id, "status": status.value})- task = store.get_task(task_id)- return json.dumps({"status": "ok", "task": task.model_dump() if task else None})---async def handle_advance_onboarding_plan(tool_input: dict[str, Any]) -> str:- try:- plan_id = int(tool_input["plan_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("advance_onboarding_plan", f"bad arguments: {exc}")- if store.get_plan(plan_id) is None:- return json.dumps({"status": "not_found", "plan_id": plan_id})- new_phase = service.advance_phase(plan_id)- _audit("advance_onboarding_plan", "write", True,- f"advance_onboarding_plan {plan_id} → {new_phase}",- {"plan_id": plan_id, "new_phase": new_phase.value if new_phase else None})- return json.dumps({- "status": "ok", "plan_id": plan_id,- "new_phase": new_phase.value if new_phase else None,- "note": "already at final phase" if new_phase is None else "",- })---async def handle_activate_onboarding_plan(tool_input: dict[str, Any]) -> str:- try:- plan_id = int(tool_input["plan_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("activate_onboarding_plan", f"bad arguments: {exc}")- if store.get_plan(plan_id) is None:- return json.dumps({"status": "not_found", "plan_id": plan_id})- try:- service.activate_plan(plan_id)- except Exception as exc:- logger.exception("activate_onboarding_plan: failed")- return _err("activate_onboarding_plan", str(exc))- _audit("activate_onboarding_plan", "write", True,- f"activate_onboarding_plan {plan_id}", {"plan_id": plan_id})- plan = store.get_plan(plan_id)- return json.dumps({"status": "ok", "plan": plan.model_dump() if plan else None})---async def handle_start_onboarding(tool_input: dict[str, Any]) -> str:- from openexecutive.config import get_settings- from openexecutive.knowledge.store import ChromaDBStore- from openexecutive.workflows import WORKFLOW_REGISTRY- from openexecutive.workflows.persistence import complete_run, create_run, fail_run-- workflow = WORKFLOW_REGISTRY["role_onboarding"]- raw = {k: tool_input.get(k) for k in ("plan_id", "full_name", "role", "function", "ramp_days")- if tool_input.get(k) is not None}- try:- wf_inputs = workflow.input_model().model_validate(raw)- except Exception as exc:- return _err("start_onboarding", f"invalid inputs: {exc}")-- run_id = str(uuid.uuid4())- try:- create_run(run_id, "role_onboarding", f"{workflow.title} (chat-tool fire)",- wf_inputs.model_dump())- except Exception:- logger.exception("start_onboarding: create_run failed")-- artifact = ""- last_error = ""- chroma = ChromaDBStore(persist_directory=get_settings().vector_store_path)- try:- async for event in workflow.run(inputs=wf_inputs, store=chroma):- if event.type == "artifact" and event.content:- artifact = event.content- elif event.type == "error" and event.message:- last_error = event.message- except Exception as exc:- logger.exception("start_onboarding: workflow.run crashed")- last_error = str(exc)[:200]-- import contextlib- if last_error:- with contextlib.suppress(Exception):- fail_run(run_id, last_error)- return _err("start_onboarding", last_error)- with contextlib.suppress(Exception):- complete_run(run_id, artifact or "(no artifact)")- _audit("start_onboarding", "write", True, "start_onboarding generated brief",- {"plan_id": tool_input.get("plan_id"), "chars": len(artifact)})- return json.dumps({"status": "ok", "artifact": artifact})---ONBOARDING_TOOL_HANDLERS: dict[str, Callable[[dict[str, Any]], Awaitable[str]]] = {- "list_onboarding_plans": handle_list_onboarding_plans,- "get_onboarding_plan": handle_get_onboarding_plan,- "list_onboarding_templates": handle_list_onboarding_templates,- "create_onboarding_plan": handle_create_onboarding_plan,- "complete_onboarding_task": handle_complete_onboarding_task,- "advance_onboarding_plan": handle_advance_onboarding_plan,- "activate_onboarding_plan": handle_activate_onboarding_plan,- "start_onboarding": handle_start_onboarding,-}---__all__ = ["ONBOARDING_TOOLS", "ONBOARDING_TOOL_HANDLERS"]diff --git a/packages/core/openexecutive/orchestrator/router.py b/packages/core/openexecutive/orchestrator/router.pyindex e3d0d4af..e2870339 100644--- a/packages/core/openexecutive/orchestrator/router.py+++ b/packages/core/openexecutive/orchestrator/router.py@@ -16,7 +16,6 @@ from openexecutive.agents.marketing import MarketingAgentfrom openexecutive.agents.operations import OperationsAgentfrom openexecutive.agents.product import ProductAgentfrom openexecutive.agents.strategy import StrategyAgent-from openexecutive.agents.talent import TalentAgentfrom openexecutive.agents.triage import TriageAgentSPECIALIST_REGISTRY: dict[str, BaseAgent] = {@@ -28,7 +27,6 @@ SPECIALIST_REGISTRY: dict[str, BaseAgent] = {"cmo": MarketingAgent(),"cpo": ProductAgent(),"board_comms": BoardCommsAgent(),- "talent": TalentAgent(),"triage": TriageAgent(),}@@ -41,7 +39,6 @@ SPECIALIST_DESCRIPTIONS = {"cmo": "Chief Marketing Officer — GTM strategy, brand, messaging, PR, crisis communications","cpo": "Chief Product Officer — product roadmap, prioritization frameworks, product strategy","board_comms": "Board Communications Director — board decks, investor relations, governance",- "talent": "Head of Talent & Executive Search — candidate screening & fit scoring, executive sourcing, energy-sector talent-market mapping","triage": "Chief of Staff — evaluates inbound events (email/Slack/docs) for significance and decides alerting",}diff --git a/packages/core/openexecutive/orchestrator/talent_tools.py b/packages/core/openexecutive/orchestrator/talent_tools.pydeleted file mode 100644index 207cdb31..00000000--- a/packages/core/openexecutive/orchestrator/talent_tools.py+++ /dev/null@@ -1,1124 +0,0 @@-"""Anthropic tool definitions + handlers for the talent / executive-search vertical.--The ``TalentAgent`` specialist can *advise* on screening and sourcing from RAG,-but until now the Executive had no way to read the live pipeline (engagements,-candidates, matches) or start the talent workflows from a chat turn — so the-``/talent`` UI and the conversation were two disconnected worlds.--These tools close that gap. They sit alongside ``list_people`` / ``create_alert``-/ ``run_executive_research`` in the Executive's main tool loop:--- read tools (``list_engagements`` / ``list_candidates`` / ``get_candidate`` /- ``match_candidates``) expose the live pipeline,-- ``set_candidate_stage`` is a light, reversible write that keeps the pipeline- truthful from chat,-- ``create_engagement`` / ``create_candidate`` build the pipeline from chat —- they mirror the ``/talent`` API routes (the same ``upsert_*`` store calls), so- a search can be opened in conversation. ``create_engagement`` opens a role- we're hiring for in this company (no external client); ``create_candidate``- re-indexes the new person into the talent graph just like the API route does.-- ``start_talent_workflow`` fires one of the existing draft-and-approve talent- workflows to completion (mirroring ``run_executive_research``), so the- Executive can act on a search without an HTTP round-trip.--The ``/talent`` UI remains the home for heavier editing (updates, soft-archive)-and bulk work; chat covers create + the lightweight pipeline moves above.-JSON-in / JSON-out, matching the other orchestrator tools.-"""-from __future__ import annotations--import json-import logging-import uuid-from collections.abc import Awaitable, Callable-from typing import Any--from openexecutive.audit import log_event as audit_log-from openexecutive.talent.models import CandidateStage, EngagementStatus, OfferStatus--logger = logging.getLogger(__name__)--_STAGE_VALUES = [s.value for s in CandidateStage]-_ENGAGEMENT_STATUS_VALUES = [s.value for s in EngagementStatus]-_OFFER_STATUS_VALUES = [s.value for s in OfferStatus]--# match_candidates result-count bounds: the model's `limit` is clamped to-# [1, _MAX_MATCH_LIMIT]; _DEFAULT_MATCH_LIMIT applies when it omits one.-_DEFAULT_MATCH_LIMIT = 10-_MAX_MATCH_LIMIT = 50--# The talent workflows reachable from chat. ``exec_search_brief`` is generative-# (no existing candidate/engagement required); the rest operate on a candidate-# already in the pipeline. All are short and draft-and-approve. Only-# ``offer_approval`` pauses on a wait-for-human gate — the handler checkpoints-# the run and reports ``awaiting_human`` (mirroring ``run_workflow``); the-# others run to completion inside the tool handler.-_TALENT_WORKFLOWS = [- "candidate_screen",- "candidate_outreach",- "interview_coordination",- "reference_check",- "exec_search_brief",- "offer_approval",- "new_hire_onboarding",-]---# --------------------------------------------------------------------------- #-# Tool definitions-# --------------------------------------------------------------------------- #--LIST_ENGAGEMENTS_TOOL: dict[str, Any] = {- "name": "list_engagements",- "description": (- "List the active executive-search engagements (open / on-hold) with a "- "pipeline rollup per search: client name, role, status, candidate count, "- "how many need screening (leads), how many offers are out, and how many "- "candidates have stalled. Use this to answer 'how are our searches "- "going?' or to resolve a client/role to an engagement_id before calling "- "list_candidates, match_candidates, or start_talent_workflow. Filled and "- "cancelled searches are omitted."- ),- "input_schema": {"type": "object", "properties": {}},-}---LIST_CANDIDATES_TOOL: dict[str, Any] = {- "name": "list_candidates",- "description": (- "List the candidates in one engagement's pipeline, newest id last. "- "Optionally filter to a single stage. Returns a compact JSON list with "- "each candidate's id, name, current title/company, stage, and fit_score. "- "Call list_engagements first if you need the engagement_id."- ),- "input_schema": {- "type": "object",- "properties": {- "engagement_id": {- "type": "integer",- "description": "The engagement (search) whose candidates to list.",- },- "stage": {- "type": "string",- "enum": _STAGE_VALUES,- "description": "Optional pipeline stage to filter to.",- },- },- "required": ["engagement_id"],- },-}---GET_CANDIDATE_TOOL: dict[str, Any] = {- "name": "get_candidate",- "description": (- "Fetch full detail for one candidate by id, including fit_score and the "- "screening_summary produced by the candidate_screen workflow. Use before "- "discussing a specific candidate or starting a workflow for them."- ),- "input_schema": {- "type": "object",- "properties": {- "candidate_id": {"type": "integer", "description": "Id of the candidate."},- },- "required": ["candidate_id"],- },-}---MATCH_CANDIDATES_TOOL: dict[str, Any] = {- "name": "match_candidates",- "description": (- "Rank the candidate pool against an engagement's role and must-haves "- "using the semantic talent graph. Returns up to `limit` candidates best "- "first, each with a 0-1 match score, current stage, name, and title. Use "- "when the principal asks 'who's the best fit for X' or to surface "- "candidates worth advancing."- ),- "input_schema": {- "type": "object",- "properties": {- "engagement_id": {- "type": "integer",- "description": "The engagement to rank candidates against.",- },- "limit": {- "type": "integer",- "description": "Max matches to return (default 10).",- },- },- "required": ["engagement_id"],- },-}---SET_CANDIDATE_STAGE_TOOL: dict[str, Any] = {- "name": "set_candidate_stage",- "description": (- "Move a candidate to a pipeline stage (lead → screened → interviewed → "- "offer → placed, or the rejected off-ramp). A light, reversible update "- "that keeps the pipeline truthful when the principal tells you a "- "candidate advanced or dropped out. For a full screen with a fit score, "- "use start_talent_workflow('candidate_screen') instead — do not set "- "'screened' by hand to fake a score."- ),- "input_schema": {- "type": "object",- "properties": {- "candidate_id": {"type": "integer", "description": "Id of the candidate to move."},- "stage": {- "type": "string",- "enum": _STAGE_VALUES,- "description": "The stage to move the candidate to.",- },- },- "required": ["candidate_id", "stage"],- },-}---START_TALENT_WORKFLOW_TOOL: dict[str, Any] = {- "name": "start_talent_workflow",- "description": (- "Run one of the talent workflows to completion and return its artifact. "- "All are draft-and-approve — they schedule reminders/drafts to the search "- "principal and NEVER contact a candidate or reference directly.\n"- "Workflows and their `inputs`:\n"- " - candidate_screen: {engagement_id:int, candidate_id:int} — screen a "- "candidate against the role and persist a fit score.\n"- " - candidate_outreach: {candidate_id:int, follow_up_count?:int(0-5), "- "follow_up_interval_days?:int(1-30), angle?:str} — draft a first touch + "- "follow-up sequence.\n"- " - interview_coordination: {candidate_id:int, num_rounds?:int(1-7), "- "notes?:str} — design the interview loop.\n"- " - reference_check: {candidate_id:int, reference_count?:int(1-5), "- "reference_notes?:str} — draft a reference-check rubric.\n"- " - exec_search_brief: {role_title:str, function:str, business_context:str, "- "year_one_outcomes:str, non_negotiables?:str} — generate a hiring brief "- "for a NEW search (no candidate needed).\n"- " - offer_approval: {candidate_id:int, comp_notes?:str, angle?:str} — "- "draft the offer package and request hiring sign-off; the run PAUSES "- "until the approver replies (returns awaiting_human). After approval, "- "use extend_offer.\n"- " - new_hire_onboarding: {candidate_id:int, start_date?:str(ISO date), "- "focus_notes?:str} — placed-candidate handoff: roster Person + 30/60/90 "- "plan + milestone check-in reminders.\n"- "Resolve ids with list_engagements / list_candidates first."- ),- "input_schema": {- "type": "object",- "properties": {- "workflow": {- "type": "string",- "enum": _TALENT_WORKFLOWS,- "description": "Which talent workflow to run.",- },- "inputs": {- "type": "object",- "description": "The workflow's input fields (see the per-workflow list above).",- },- },- "required": ["workflow", "inputs"],- },-}---CREATE_ENGAGEMENT_TOOL: dict[str, Any] = {- "name": "create_engagement",- "description": (- "Open a new search — a role we're hiring for in this company. Only "- "role_title is required; `department` is an optional in-house grouping "- "(e.g. 'Drilling'). Use list_engagements to see existing searches first "- "so you don't open a duplicate."- ),- "input_schema": {- "type": "object",- "properties": {- "role_title": {"type": "string", "description": "The role being searched for."},- "department": {- "type": "string",- "description": "Optional in-house team/department this role sits in.",- },- "status": {- "type": "string",- "enum": _ENGAGEMENT_STATUS_VALUES,- "description": "Engagement status, optional (defaults to open).",- },- "location": {"type": "string", "description": "Role location, optional."},- "comp_band": {"type": "string", "description": "Compensation band, optional."},- "must_haves": {"type": "string", "description": "Must-have requirements, optional."},- "description": {"type": "string", "description": "Role description, optional."},- },- "required": ["role_title"],- },-}---CREATE_CANDIDATE_TOOL: dict[str, Any] = {- "name": "create_candidate",- "description": (- "Add a candidate to an EXISTING engagement's pipeline. You must pass a "- "valid engagement_id (resolve with list_engagements; returns not_found "- "for an unknown one). Only engagement_id and full_name are required; the "- "candidate is indexed for semantic matching automatically. Do NOT set a "- "fit score here — run start_talent_workflow('candidate_screen') for that."- ),- "input_schema": {- "type": "object",- "properties": {- "engagement_id": {"type": "integer", "description": "Id of the existing engagement."},- "full_name": {"type": "string", "description": "Candidate's full name (required)."},- "current_title": {"type": "string", "description": "Current title, optional."},- "current_company": {"type": "string", "description": "Current company, optional."},- "location": {"type": "string", "description": "Location, optional."},- "email": {"type": "string", "description": "Email, optional."},- "linkedin_url": {"type": "string", "description": "LinkedIn URL, optional."},- "source": {"type": "string", "description": "How sourced (e.g. referral), optional."},- "stage": {- "type": "string",- "enum": _STAGE_VALUES,- "description": "Starting pipeline stage, optional (defaults to lead).",- },- "notes": {"type": "string", "description": "Free-text notes, optional."},- },- "required": ["engagement_id", "full_name"],- },-}---LIST_OFFERS_TOOL: dict[str, Any] = {- "name": "list_offers",- "description": (- "List offers, optionally filtered by candidate, engagement, and/or "- "status (draft / pending_approval / extended / accepted / declined / "- "expired / rescinded). Returns each offer's id, candidate, status, comp "- "summary, and expiry. Use to answer 'where is the offer to X?' or "- "before extend_offer / record_offer_decision."- ),- "input_schema": {- "type": "object",- "properties": {- "candidate_id": {"type": "integer", "description": "Filter to one candidate."},- "engagement_id": {"type": "integer", "description": "Filter to one engagement."},- "status": {- "type": "string",- "enum": _OFFER_STATUS_VALUES,- "description": "Filter to one offer status.",- },- },- },-}---CREATE_OFFER_TOOL: dict[str, Any] = {- "name": "create_offer",- "description": (- "Record a draft offer for a candidate with terms the principal "- "dictated. One open offer per candidate. For a fully drafted package "- "with hiring sign-off, run start_talent_workflow('offer_approval') "- "instead — this tool is the manual path when the principal already "- "knows the terms. The offer starts as a draft; use extend_offer once "- "the principal actually sends it."- ),- "input_schema": {- "type": "object",- "properties": {- "candidate_id": {"type": "integer", "description": "The candidate the offer is for."},- "comp_summary": {- "type": "string",- "description": "The terms in brief (base, equity, sign-on, start date…).",- },- "note": {"type": "string", "description": "Optional context note."},- },- "required": ["candidate_id", "comp_summary"],- },-}---EXTEND_OFFER_TOOL: dict[str, Any] = {- "name": "extend_offer",- "description": (- "Mark an offer as extended — the principal sent it to the candidate "- "themselves (OE NEVER sends offers to candidates) — and schedule expiry "- "reminders to the principal. Checks the recorded hiring sign-off: a "- "rejection blocks this; a pending/absent sign-off proceeds on the "- "principal's explicit instruction and is flagged in the response. "- "Expiry defaults to 7 days out."- ),- "input_schema": {- "type": "object",- "properties": {- "offer_id": {"type": "integer", "description": "The offer to mark extended."},- "expires_in_days": {- "type": "integer",- "description": "Days until the offer expires (1-60, default 7).",- },- "expires_at": {- "type": "string",- "description": "Explicit ISO expiry timestamp (overrides expires_in_days).",- },- "note": {"type": "string", "description": "Optional context note."},- },- "required": ["offer_id"],- },-}---RECORD_OFFER_DECISION_TOOL: dict[str, Any] = {- "name": "record_offer_decision",- "description": (- "Record the outcome of an extended offer: accepted, declined, expired, "- "or rescinded (rescind also works on a draft/pending offer). Cancels "- "the offer's pending expiry reminders. 'accepted' also moves the "- "candidate to placed and the engagement to filled, and the response "- "will suggest running new_hire_onboarding. declined/expired/rescinded "- "leave the candidate's stage for the principal to decide."- ),- "input_schema": {- "type": "object",- "properties": {- "offer_id": {"type": "integer", "description": "The offer to decide."},- "decision": {- "type": "string",- "enum": ["accepted", "declined", "expired", "rescinded"],- "description": "The outcome.",- },- "note": {"type": "string", "description": "Optional context (e.g. why declined)."},- },- "required": ["offer_id", "decision"],- },-}---TALENT_TOOLS: list[dict[str, Any]] = [- LIST_ENGAGEMENTS_TOOL,- LIST_CANDIDATES_TOOL,- GET_CANDIDATE_TOOL,- MATCH_CANDIDATES_TOOL,- CREATE_ENGAGEMENT_TOOL,- CREATE_CANDIDATE_TOOL,- SET_CANDIDATE_STAGE_TOOL,- START_TALENT_WORKFLOW_TOOL,- LIST_OFFERS_TOOL,- CREATE_OFFER_TOOL,- EXTEND_OFFER_TOOL,- RECORD_OFFER_DECISION_TOOL,-]---# --------------------------------------------------------------------------- #-# Handlers-# --------------------------------------------------------------------------- #---def _audit(tool: str, kind: str, ok: bool, summary: str, details: dict[str, Any]) -> None:- audit_log(- "tool_invocation",- summary,- actor="executive",- details={"tool": tool, "kind": kind, "ok": ok, **details},- )---def _err(tool: str, msg: str) -> str:- _audit(tool, "read", False, f"{tool}: {msg}", {"error": msg[:300]})- return json.dumps({"error": msg})---# Text-field length caps for the chat create tools, mirroring the Pydantic-# bounds the /talent API routes enforce (api/routes/talent.py) — chat is just-# another caller, so it must not be able to persist (and then embed) unbounded-# free text that the HTTP path rejects.-_MAX_SHORT = 200 # names, titles, locations, comp band, source-_MAX_MEDIUM = 4000 # client notes-_MAX_LONG = 8000 # role must-haves / descriptions, candidate notes---def _length_error(tool: str, checks: list[tuple[str, str, int]]) -> str | None:- """Return an `_err` JSON string for the first over-length field, else None."""- for label, value, limit in checks:- if len(value) > limit:- return _err(tool, f"{label} too long ({len(value)} > {limit} chars)")- return None---def _candidate_summary(cand: Any) -> dict[str, Any]:- return {- "candidate_id": cand.id,- "engagement_id": cand.engagement_id,- "full_name": cand.full_name,- "current_title": cand.current_title,- "current_company": cand.current_company,- "stage": cand.stage.value,- "fit_score": cand.fit_score,- }---async def handle_list_engagements(tool_input: dict[str, Any]) -> str:- # Reuse the shared briefing rollup so chat and /today never disagree on- # pipeline state.- from openexecutive.briefing.talent_digest import build_talent_brief_items-- try:- items = build_talent_brief_items()- except Exception as exc:- logger.exception("list_engagements: failed")- return _err("list_engagements", str(exc))-- out = [it.model_dump() for it in items]- _audit(- "list_engagements", "read", True,- f"list_engagements returned {len(out)}",- {"count": len(out)},- )- return json.dumps({"engagements": out, "count": len(out)})---async def handle_list_candidates(tool_input: dict[str, Any]) -> str:- from openexecutive.talent import store as talent_store-- try:- engagement_id = int(tool_input["engagement_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("list_candidates", f"bad arguments: {exc}")-- stage: CandidateStage | None = None- stage_raw = tool_input.get("stage")- if stage_raw is not None:- try:- stage = CandidateStage(str(stage_raw))- except ValueError:- return _err("list_candidates", f"invalid stage: {stage_raw!r}")-- try:- candidates = talent_store.list_candidates(engagement_id=engagement_id, stage=stage)- except Exception as exc:- logger.exception("list_candidates: failed")- return _err("list_candidates", str(exc))-- out = [_candidate_summary(c) for c in candidates]- _audit(- "list_candidates", "read", True,- f"list_candidates engagement={engagement_id} returned {len(out)}",- {"engagement_id": engagement_id, "count": len(out), "stage": stage.value if stage else None},- )- return json.dumps({"candidates": out, "count": len(out)})---async def handle_get_candidate(tool_input: dict[str, Any]) -> str:- from openexecutive.talent import store as talent_store-- try:- candidate_id = int(tool_input["candidate_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("get_candidate", f"bad arguments: {exc}")-- try:- cand = talent_store.get_candidate(candidate_id)- except Exception as exc:- logger.exception("get_candidate: failed")- return _err("get_candidate", str(exc))-- if cand is None:- _audit("get_candidate", "read", False, f"get_candidate {candidate_id} not found",- {"candidate_id": candidate_id})- return json.dumps({"status": "not_found", "candidate_id": candidate_id})-- _audit("get_candidate", "read", True, f"get_candidate {candidate_id}",- {"candidate_id": candidate_id})- return json.dumps({"candidate": cand.model_dump()})---async def handle_match_candidates(tool_input: dict[str, Any]) -> str:- from openexecutive.config import get_settings- from openexecutive.knowledge.store import ChromaDBStore- from openexecutive.talent import graph as talent_graph- from openexecutive.talent import store as talent_store-- try:- engagement_id = int(tool_input["engagement_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("match_candidates", f"bad arguments: {exc}")-- limit_raw = tool_input.get("limit", _DEFAULT_MATCH_LIMIT)- try:- limit = max(1, min(int(limit_raw), _MAX_MATCH_LIMIT))- except (TypeError, ValueError):- return _err("match_candidates", "limit must be an integer")-- try:- engagement = talent_store.get_engagement(engagement_id)- except Exception as exc:- logger.exception("match_candidates: get_engagement failed")- return _err("match_candidates", str(exc))- if engagement is None:- return json.dumps({"status": "not_found", "engagement_id": engagement_id})-- try:- store = ChromaDBStore(persist_directory=get_settings().vector_store_path)- matches = talent_graph.match_candidates_for_engagement(engagement, store, limit=limit)- except Exception as exc:- logger.exception("match_candidates: graph query failed")- return _err("match_candidates", str(exc))-- # Enrich each match with the candidate's name/title so the Executive can- # talk about people, not bare ids.- enriched: list[dict[str, Any]] = []- for m in matches:- cid = m.get("candidate_id")- name = title = None- if cid is not None:- try:- cand = talent_store.get_candidate(int(cid))- except Exception:- cand = None- if cand is not None:- name, title = cand.full_name, cand.current_title- enriched.append({**m, "full_name": name, "current_title": title})-- _audit(- "match_candidates", "read", True,- f"match_candidates engagement={engagement_id} returned {len(enriched)}",- {"engagement_id": engagement_id, "count": len(enriched)},- )- return json.dumps({"engagement_id": engagement_id, "matches": enriched, "count": len(enriched)})---async def handle_set_candidate_stage(tool_input: dict[str, Any]) -> str:- from openexecutive.talent import store as talent_store-- try:- candidate_id = int(tool_input["candidate_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("set_candidate_stage", f"bad arguments: {exc}")-- try:- stage = CandidateStage(str(tool_input["stage"]))- except (KeyError, ValueError) as exc:- return _err("set_candidate_stage", f"invalid or missing stage: {exc}")-- existing = talent_store.get_candidate(candidate_id)- if existing is None:- _audit("set_candidate_stage", "write", False,- f"set_candidate_stage {candidate_id} not found", {"candidate_id": candidate_id})- return json.dumps({"status": "not_found", "candidate_id": candidate_id})-- try:- changed = talent_store.set_candidate_stage(candidate_id, stage)- except Exception as exc:- logger.exception("set_candidate_stage: failed")- return _err("set_candidate_stage", str(exc))-- _audit(- "set_candidate_stage", "write", True,- f"set_candidate_stage {candidate_id} -> {stage.value}",- {"candidate_id": candidate_id, "stage": stage.value, "changed": changed},- )- result: dict[str, Any] = {- "status": "ok",- "candidate_id": candidate_id,- "stage": stage.value,- "changed": changed,- }- # Suggest-on-placed: a placed candidate is a hire — prompt the Executive to- # chain the hire-loop steps. A suggestion only, never an auto-fire, and OE- # still never messages the candidate directly. The two onboarding surfaces- # compose: new_hire_onboarding records the offer outcome's roster Person- # (which staff-onboarding delivery/ramp needs) + principal 30/60/90- # check-ins; create_onboarding_plan/start_onboarding add the structured- # task plan, welcome brief, and ramp drip.- if stage == CandidateStage.PLACED:- result["onboarding_suggestion"] = (- f"{existing.full_name} is placed — if this reflects an accepted "- "offer, record it with record_offer_decision first. Then run "- "start_talent_workflow('new_hire_onboarding') to add them to the "- "People roster and schedule 30/60/90 check-ins. After that, call "- f"create_onboarding_plan(full_name={existing.full_name!r}, "- f"candidate_id={candidate_id}, engagement_id={existing.engagement_id}, "- "person_id=<from new_hire_onboarding>, template_name=<role-appropriate>) "- "and start_onboarding to generate the welcome brief and enable "- "delivery and the ramp drip."- )- return json.dumps(result)---async def handle_start_talent_workflow(tool_input: dict[str, Any]) -> str:- from datetime import UTC, datetime, timedelta-- from openexecutive.config import get_settings- from openexecutive.knowledge.store import ChromaDBStore- from openexecutive.workflows import WORKFLOW_REGISTRY- from openexecutive.workflows.persistence import (- complete_run,- create_run,- fail_run,- save_checkpoint,- )- from openexecutive.workflows.wait_for_human import WaitForHumanEvent-- name = str(tool_input.get("workflow", "")).strip()- if name not in _TALENT_WORKFLOWS:- return _err(- "start_talent_workflow",- f"workflow must be one of {_TALENT_WORKFLOWS}, got {name!r}",- )-- raw_inputs = tool_input.get("inputs")- if not isinstance(raw_inputs, dict):- return _err("start_talent_workflow", "inputs must be an object")-- workflow = WORKFLOW_REGISTRY[name]- input_cls = workflow.input_model()- try:- wf_inputs = input_cls.model_validate(raw_inputs)- except Exception as exc:- # Surface the validation error so the model can correct its inputs.- return _err("start_talent_workflow", f"invalid inputs for {name}: {exc}")-- run_id = str(uuid.uuid4())- try:- create_run(run_id, name, f"{workflow.title} (chat-tool fire)", wf_inputs.model_dump())- except Exception:- logger.exception("start_talent_workflow: create_run failed")-- artifact = ""- last_error = ""- awaiting: dict[str, Any] | None = None- store = ChromaDBStore(persist_directory=get_settings().vector_store_path)- try:- async for event in workflow.run(inputs=wf_inputs, store=store):- # An approval-gate step yields a WaitForHumanEvent (not a- # WorkflowEvent): checkpoint the run and stop, mirroring- # handle_run_workflow. The resumer applies the timeout policy and- # the inbound resolver records the human's reply.- if isinstance(event, WaitForHumanEvent):- until = datetime.now(UTC) + timedelta(hours=event.timeout_hours)- save_checkpoint(- run_id=run_id,- state_json=event.model_dump_json(),- awaiting_person_id=event.person_id,- awaiting_until=until,- )- awaiting = {- "person_id": event.person_id,- "question": event.question,- "awaiting_until": until.isoformat(),- }- break- if event.type == "artifact" and event.content:- artifact = event.content- elif event.type == "error" and event.message:- last_error = event.message- except Exception as exc:- logger.exception("start_talent_workflow: workflow.run crashed")- last_error = str(exc)[:200]-- if awaiting is not None:- _audit("start_talent_workflow", "write", True,- f"start_talent_workflow {name} awaiting_human run_id={run_id}",- {"workflow": name, "run_id": run_id, "status": "awaiting_human"})- return json.dumps({- "status": "awaiting_human",- "workflow": name,- "run_id": run_id,- **awaiting,- "artifact": artifact,- "presentation_hint": (- "This workflow paused for sign-off from the named person. Tell "- "the principal it's waiting on them; do not re-run it."- ),- })-- if last_error:- import contextlib- with contextlib.suppress(Exception):- fail_run(run_id, last_error)- _audit("start_talent_workflow", "write", False,- f"start_talent_workflow {name} FAILED — {last_error}",- {"workflow": name, "error": last_error, "run_id": run_id})- return json.dumps({"error": f"workflow error: {last_error}", "run_id": run_id})-- import contextlib- with contextlib.suppress(Exception):- complete_run(run_id, artifact or "(no artifact)")-- _audit("start_talent_workflow", "write", True,- f"start_talent_workflow {name} ok run_id={run_id}",- {"workflow": name, "run_id": run_id})- return json.dumps({- "ok": True,- "workflow": name,- "run_id": run_id,- "artifact": artifact,- "presentation_hint": (- "The workflow already drafted its output and scheduled any "- "reminders to the search principal. Summarise the artifact for the "- "principal; do not re-run the workflow or contact candidates/"- "references yourself."- ),- })---async def handle_create_engagement(tool_input: dict[str, Any]) -> str:- from openexecutive.talent import store as talent_store-- role_title = str(tool_input.get("role_title", "")).strip()- if not role_title:- return _err("create_engagement", "role_title is required")-- status = EngagementStatus.OPEN- status_raw = tool_input.get("status")- if status_raw is not None:- try:- status = EngagementStatus(str(status_raw))- except ValueError:- return _err("create_engagement", f"invalid status: {status_raw!r}")-- department = str(tool_input.get("department", "") or "")- location = str(tool_input.get("location", "") or "")- comp_band = str(tool_input.get("comp_band", "") or "")- must_haves = str(tool_input.get("must_haves", "") or "")- description = str(tool_input.get("description", "") or "")- length_err = _length_error("create_engagement", [- ("role_title", role_title, _MAX_SHORT),- ("department", department, _MAX_SHORT),- ("location", location, _MAX_SHORT),- ("comp_band", comp_band, _MAX_SHORT),- ("must_haves", must_haves, _MAX_LONG),- ("description", description, _MAX_LONG),- ])- if length_err:- return length_err-- try:- engagement_id = talent_store.upsert_engagement(- role_title=role_title,- department=department,- status=status,- location=location,- comp_band=comp_band,- must_haves=must_haves,- description=description,- )- engagement = talent_store.get_engagement(engagement_id)- except Exception as exc:- logger.exception("create_engagement: failed")- return _err("create_engagement", str(exc))-- if engagement is None:- return _err("create_engagement", f"created engagement {engagement_id} but could not reload it")-- _audit("create_engagement", "write", True,- f"create_engagement {engagement_id} {role_title}",- {"engagement_id": engagement_id, "role_title": role_title, "department": department})- return json.dumps({"status": "ok", "engagement": engagement.model_dump()})---async def handle_create_candidate(tool_input: dict[str, Any]) -> str:- from openexecutive.config import get_settings- from openexecutive.knowledge.store import ChromaDBStore- from openexecutive.talent import graph as talent_graph- from openexecutive.talent import store as talent_store-- try:- engagement_id = int(tool_input["engagement_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("create_candidate", f"bad arguments: {exc}")-- full_name = str(tool_input.get("full_name", "")).strip()- if not full_name:- return _err("create_candidate", "full_name is required")-- stage = CandidateStage.LEAD- stage_raw = tool_input.get("stage")- if stage_raw is not None:- try:- stage = CandidateStage(str(stage_raw))- except ValueError:- return _err("create_candidate", f"invalid stage: {stage_raw!r}")-- # Require an existing engagement — a candidate only exists within a search.- if talent_store.get_engagement(engagement_id) is None:- _audit("create_candidate", "write", False,- f"create_candidate unknown engagement {engagement_id}",- {"engagement_id": engagement_id})- return json.dumps({"status": "not_found", "engagement_id": engagement_id})-- # email / linkedin_url are nullable columns (None == absent), so blanks- # normalize to None; the other optionals are NOT NULL DEFAULT '' columns, so- # they coerce to "". This matches the model, the schema, and the /talent form.- def _norm(key: str) -> str | None:- val = tool_input.get(key)- if val is None:- return None- text = str(val).strip()- return text or None-- current_title = str(tool_input.get("current_title", "") or "")- current_company = str(tool_input.get("current_company", "") or "")- location = str(tool_input.get("location", "") or "")- source = str(tool_input.get("source", "") or "")- notes = str(tool_input.get("notes", "") or "")- email = _norm("email")- linkedin_url = _norm("linkedin_url")- length_err = _length_error("create_candidate", [- ("full_name", full_name, _MAX_SHORT),- ("current_title", current_title, _MAX_SHORT),- ("current_company", current_company, _MAX_SHORT),- ("location", location, _MAX_SHORT),- ("source", source, _MAX_SHORT),- ("email", email or "", _MAX_SHORT),- ("linkedin_url", linkedin_url or "", _MAX_SHORT),- ("notes", notes, _MAX_LONG),- ])- if length_err:- return length_err-- try:- candidate_id = talent_store.upsert_candidate(- engagement_id=engagement_id,- full_name=full_name,- current_title=current_title,- current_company=current_company,- location=location,- email=email,- linkedin_url=linkedin_url,- source=source,- stage=stage,- notes=notes,- )- candidate = talent_store.get_candidate(candidate_id)- except Exception as exc:- logger.exception("create_candidate: failed")- return _err("create_candidate", str(exc))-- if candidate is None:- return _err("create_candidate", f"created candidate {candidate_id} but could not reload it")-- # Index into the talent graph so match_candidates / find_similar see the new- # person. The store is pure SQLite, so indexing is the caller's job — the- # /talent API route does the same after an insert. index_candidate swallows- # its own vector-store failures, so a bad index never fails the create.- try:- store = ChromaDBStore(persist_directory=get_settings().vector_store_path)- talent_graph.index_candidate(candidate, store)- except Exception: # noqa: BLE001 — index sync must never break the write- logger.warning("create_candidate: indexing %s failed", candidate_id, exc_info=True)-- _audit("create_candidate", "write", True,- f"create_candidate {candidate_id} {full_name} (engagement {engagement_id})",- {"candidate_id": candidate_id, "engagement_id": engagement_id, "full_name": full_name})- return json.dumps({"status": "ok", "candidate": candidate.model_dump()})---def _offer_summary(offer: Any) -> dict[str, Any]:- return {- "offer_id": offer.id,- "candidate_id": offer.candidate_id,- "engagement_id": offer.engagement_id,- "status": offer.status.value,- "comp_summary": offer.comp_summary,- "note": offer.note,- "expires_at": offer.expires_at,- "extended_at": offer.extended_at,- "decided_at": offer.decided_at,- }---async def handle_list_offers(tool_input: dict[str, Any]) -> str:- from openexecutive.talent import store as talent_store-- candidate_id: int | None = None- engagement_id: int | None = None- try:- if tool_input.get("candidate_id") is not None:- candidate_id = int(tool_input["candidate_id"])- if tool_input.get("engagement_id") is not None:- engagement_id = int(tool_input["engagement_id"])- except (TypeError, ValueError) as exc:- return _err("list_offers", f"bad arguments: {exc}")-- status: OfferStatus | None = None- status_raw = tool_input.get("status")- if status_raw is not None:- try:- status = OfferStatus(str(status_raw))- except ValueError:- return _err("list_offers", f"invalid status: {status_raw!r}")-- try:- offers = talent_store.list_offers(- candidate_id=candidate_id, engagement_id=engagement_id, status=status- )- except Exception as exc:- logger.exception("list_offers: failed")- return _err("list_offers", str(exc))-- out = [_offer_summary(o) for o in offers]- _audit("list_offers", "read", True, f"list_offers returned {len(out)}",- {"count": len(out), "candidate_id": candidate_id, "engagement_id": engagement_id})- return json.dumps({"offers": out, "count": len(out)})---async def handle_create_offer(tool_input: dict[str, Any]) -> str:- from openexecutive.talent import store as talent_store-- try:- candidate_id = int(tool_input["candidate_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("create_offer", f"bad arguments: {exc}")-- comp_summary = str(tool_input.get("comp_summary", "")).strip()- if not comp_summary:- return _err("create_offer", "comp_summary is required")- note = str(tool_input.get("note", "") or "")- length_err = _length_error("create_offer", [- ("comp_summary", comp_summary, _MAX_LONG),- ("note", note, _MAX_LONG),- ])- if length_err:- return length_err-- candidate = talent_store.get_candidate(candidate_id)- if candidate is None:- _audit("create_offer", "write", False,- f"create_offer unknown candidate {candidate_id}",- {"candidate_id": candidate_id})- return json.dumps({"status": "not_found", "candidate_id": candidate_id})-- try:- offer_id = talent_store.create_offer(- candidate_id=candidate_id,- engagement_id=candidate.engagement_id,- comp_summary=comp_summary,- note=note,- )- offer = talent_store.get_offer(offer_id)- except ValueError as exc:- return _err("create_offer", str(exc))- except Exception as exc:- logger.exception("create_offer: failed")- return _err("create_offer", str(exc))-- if offer is None:- return _err("create_offer", f"created offer {offer_id} but could not reload it")-- _audit("create_offer", "write", True,- f"create_offer {offer_id} for candidate {candidate_id}",- {"offer_id": offer_id, "candidate_id": candidate_id})- return json.dumps({- "status": "ok",- "offer": _offer_summary(offer),- "presentation_hint": (- "Draft recorded. When the principal actually sends the offer, call "- "extend_offer to start expiry reminders. OE never sends offers to "- "candidates."- ),- })---async def handle_extend_offer(tool_input: dict[str, Any]) -> str:- from openexecutive.talent.offers import OfferActionError, extend_offer-- try:- offer_id = int(tool_input["offer_id"])- except (KeyError, TypeError, ValueError) as exc:- return _err("extend_offer", f"bad arguments: {exc}")-- expires_in_days = 7- if tool_input.get("expires_in_days") is not None:- try:- expires_in_days = int(tool_input["expires_in_days"])- except (TypeError, ValueError):- return _err("extend_offer", "expires_in_days must be an integer")- if not 1 <= expires_in_days <= 60:- return _err("extend_offer", "expires_in_days must be 1-60")- expires_at = tool_input.get("expires_at")- note = tool_input.get("note")-- try:- result = extend_offer(- offer_id,- expires_at=str(expires_at) if expires_at else None,- expires_in_days=expires_in_days,- note=str(note) if note is not None else None,- )- except OfferActionError as exc:- return _err("extend_offer", exc.message)- except Exception as exc:- logger.exception("extend_offer: failed")- return _err("extend_offer", str(exc))-- _audit("extend_offer", "write", True,- f"extend_offer {offer_id} (approval: {result.approval_state}, "- f"{len(result.nudge_action_ids)} nudges)",- {"offer_id": offer_id, "approval_state": result.approval_state,- "nudge_action_ids": result.nudge_action_ids})- return json.dumps({- "status": "ok",- "offer": _offer_summary(result.offer),- "approval_state": result.approval_state,- "nudges_scheduled": len(result.nudge_action_ids),- "warnings": result.warnings,- })---async def handle_record_offer_decision(tool_input: dict[str, Any]) -> str:- from openexecutive.talent.offers import OfferActionError, record_offer_decision-- try:- offer_id = int(tool_input["offer_id"])- decision = OfferStatus(str(tool_input["decision"]))- except (KeyError, TypeError, ValueError) as exc:- return _err("record_offer_decision", f"bad arguments: {exc}")-- note = tool_input.get("note")- try:- result = record_offer_decision(- offer_id, decision, note=str(note) if note is not None else None- )- except OfferActionError as exc:- return _err("record_offer_decision", exc.message)- except Exception as exc:- logger.exception("record_offer_decision: failed")- return _err("record_offer_decision", str(exc))-- _audit("record_offer_decision", "write", True,- f"record_offer_decision {offer_id} -> {decision.value}",- {"offer_id": offer_id, "decision": decision.value,- "side_effects": result.side_effects})- out: dict[str, Any] = {- "status": "ok",- "offer": _offer_summary(result.offer),- "side_effects": result.side_effects,- "cancelled_nudges": result.cancelled_nudges,- }- if decision is OfferStatus.ACCEPTED:- out["next_step"] = (- "Run start_talent_workflow('new_hire_onboarding', "- f"{{'candidate_id': {result.offer.candidate_id}}}) to add the hire "- "to the roster, draft the 30/60/90 plan, and schedule check-ins."- )- return json.dumps(out)---TALENT_TOOL_HANDLERS: dict[str, Callable[[dict[str, Any]], Awaitable[str]]] = {- "list_engagements": handle_list_engagements,- "list_candidates": handle_list_candidates,- "get_candidate": handle_get_candidate,- "match_candidates": handle_match_candidates,- "create_engagement": handle_create_engagement,- "create_candidate": handle_create_candidate,- "set_candidate_stage": handle_set_candidate_stage,- "start_talent_workflow": handle_start_talent_workflow,- "list_offers": handle_list_offers,- "create_offer": handle_create_offer,- "extend_offer": handle_extend_offer,- "record_offer_decision": handle_record_offer_decision,-}---__all__ = [- "TALENT_TOOLS",- "TALENT_TOOL_HANDLERS",-]diff --git a/packages/core/openexecutive/orchestrator/workflow_run_tools.py b/packages/core/openexecutive/orchestrator/workflow_run_tools.pyindex 4ec34600..23aa9024 100644--- a/packages/core/openexecutive/orchestrator/workflow_run_tools.py+++ b/packages/core/openexecutive/orchestrator/workflow_run_tools.py@@ -1,17 +1,16 @@"""Anthropic tool definitions + handlers for launching workflows from chat.-Until now the Executive could only fire the five talent workflows-(``start_talent_workflow``) and the research council (``run_executive_research``)-from a chat turn — the other ~25 built-in workflows and every user-created-custom workflow were reachable only through the ``/jobs`` UI. These two tools-close that gap so the principal can ask the Executive to run any workflow-conversationally and get the artifact back in the same turn.+Before these tools existed the Executive could only fire the research council+(``run_executive_research``) from a chat turn — every other built-in workflow+and every user-created custom workflow was reachable only through the ``/jobs``+UI. These two tools close that gap so the principal can ask the Executive to run+any workflow conversationally and get the artifact back in the same turn.- ``list_workflows`` (read) surfaces the launchable catalog with eachworkflow's input fields, mirroring ``GET /workflows``.- ``run_workflow`` (write) runs one workflow to completion using the same- engine as the HTTP route (``openexecutive.api.routes.workflows``) and- ``start_talent_workflow``: validate inputs, ``create_run``, stream events,+ engine as the HTTP route (``openexecutive.api.routes.workflows``):+ validate inputs, ``create_run``, stream events,``complete_run`` / ``fail_run``. It also handles the approval-gate case — aworkflow that yields a ``WaitForHumanEvent`` is checkpointed(``save_checkpoint``) and reported as ``awaiting_human`` (exactly as the route@@ -75,9 +74,6 @@ RUN_WORKFLOW_TOOL: dict[str, Any] = {"name and its required `inputs` with list_workflows first, then pass ""`inputs` as an object matching that workflow's fields.\n""Notes:\n"- "- For talent-pipeline jobs (candidate screen/outreach, interviews, "- "reference checks, exec-search briefs) prefer start_talent_workflow, "- "which adds pipeline-specific guidance.\n""- A few workflows dispatch real messages when run (morning_brief and ""end_of_day_digest DM the principal; executive_reflection can DM heads ""and post broadcasts). Confirm the principal actually wants an ad-hoc "diff --git a/packages/core/openexecutive/prompts/domain_prompts.py b/packages/core/openexecutive/prompts/domain_prompts.pyindex 7ba8e90c..12c49f23 100644--- a/packages/core/openexecutive/prompts/domain_prompts.py+++ b/packages/core/openexecutive/prompts/domain_prompts.py@@ -220,33 +220,3 @@ When preparing board materials:You understand that board communication is a trust-building exercise as much as an information transfer. The goal is to be the executive the board is glad to have in the room.If a <failure_cases> block is present in the user message, weave the most relevant case into your response briefly — one to three sentences that ground your advice in what actually went wrong when this was handled badly. Do not lecture. Do not open with the failure case. Mention it where it sharpens the recommendation, then move on."""---TALENT_PROMPT = """You are the Head of Talent & Executive Search — a specialist in candidate assessment, executive sourcing, and talent-market mapping, with deep fluency in the energy sector (upstream, midstream, downstream, oilfield services, power & renewables). You have run retained searches for VP- and C-level roles and assessed hundreds of senior operators against the bar of "will they actually deliver the mandate."--Your core capabilities:-- Candidate fit assessment: matching a real person's track record against a specific role's year-one outcomes, not a generic JD-- Executive sourcing: where a given profile lives today (companies, functions, titles), and the trigger that would make them move-- Talent-market mapping: who the credible operators are for a mandate, and how the talent pool is distributed across competitors and adjacencies-- Energy-sector domain depth: the operational, regulatory, commodity-cycle, and safety realities that distinguish a credible energy leader from a generalist-- Screening discipline: separating signal (scope managed, P&L owned, crises navigated) from noise (title inflation, logo-chasing)--Benchmarks and decision rules you carry (ground answers in specifics, not platitudes):-- A fit score must be defensible from evidence. Reserve 80-100 for candidates whose track record directly demonstrates each must-have; 60-79 for strong-but-with-real-gaps; below 60 when a must-have is unmet. Never inflate to be encouraging.-- Score against the engagement's must-haves and year-one outcomes — not against a generic ideal. A 9/10 generalist who can't run the specific mandate is a bad hire.-- Tenure pattern matters: serial <18-month stints at the senior level is a flag; so is 20 years at one company with no scaling change.-- In energy, weigh cycle-tested judgment (did they lead through a price crash / downturn?), HSE/operational integrity, and commodity-margin literacy. A leader who has only operated in an up-cycle is unproven.-- Distinguish "has the experience" from "has the experience AT OUR STAGE/SCALE." Running a 5,000-person major is not the same job as turning around a 200-person independent.-- Name the single biggest risk in any candidate, and what reference check or interview probe would confirm or kill it.--When screening a candidate against an engagement:-1. State the fit score (0-100) up front with a one-line justification tied to the must-haves-2. Map evidence FOR fit against each must-have / year-one outcome-3. Name the gaps and the single biggest risk, with the probe that would resolve it-4. Give a clear recommendation: advance, advance-with-reservations, or pass--You produce assessments that a hiring committee can act on — specific, evidence-anchored, and honest about risk. You do not produce flattering summaries that move every candidate forward.--The searches you advise on are tracked in a live pipeline the rest of the company can see: each search is an *engagement* (a role for a client) and each candidate moves through fixed stages — lead → screened → interviewed → offer → placed, with rejected as the off-ramp — carrying a recorded fit_score once screened. When the engagement's must-haves, a candidate's current stage, or a prior fit_score are provided in context, anchor your assessment to those specifics rather than re-deriving them; the principal sees the same pipeline on their briefing and expects your read to line up with it. The Executive can pull this data and run the screen / outreach / interview / reference workflows directly — so when a next step is warranted, name the concrete one (e.g. "screen against the engagement's must-haves", "draft a reference rubric") rather than speaking in generalities.--If a <failure_cases> block is present in the user message, weave the most relevant case into your response briefly — one to three sentences that ground your advice in what actually went wrong when this was handled badly. Do not lecture. Do not open with the failure case. Mention it where it sharpens the recommendation, then move on."""diff --git a/packages/core/openexecutive/scheduler/runner.py b/packages/core/openexecutive/scheduler/runner.pyindex 12cef152..c844f8a8 100644--- a/packages/core/openexecutive/scheduler/runner.py+++ b/packages/core/openexecutive/scheduler/runner.py@@ -11,10 +11,6 @@ from __future__ import annotationsimport asyncioimport loggingfrom datetime import UTC, datetime, timedelta-from typing import TYPE_CHECKING--if TYPE_CHECKING:- from openexecutive.staff_onboarding.models import OnboardingPlanfrom openexecutive.memory.episodic import (ScheduledAction,@@ -390,34 +386,6 @@ async def _execute_action(await _run_dynamic_workflow(action, now)return- # ------------------------------------------------------------------- # Onboarding ramp drip — deliver the next pre-generated ramp segment to the- # new hire, then chain the next business-day occurrence ONLY while segments- # remain (self-terminating, unlike every other recurring kind). Specialised- # __internal__ action; must be handled before the generic short-circuit.- # ------------------------------------------------------------------- if action.kind == "onboarding_ramp":- await _run_onboarding_ramp(action, now)- return-- # ------------------------------------------------------------------- # Onboarding kickoff — one-shot on activation: a welcome notice to the- # hire's department channel (if configured) + intro-1:1 nudges to the- # manager and buddy. No chaining. Specialised __internal__ action.- # ------------------------------------------------------------------- if action.kind == "onboarding_kickoff":- await _run_onboarding_kickoff(action, now)- return-- # ------------------------------------------------------------------- # Onboarding milestone check-in (day 7/30/60/90) — DM the hire + manager- # and advance the plan's phase. Each milestone is its own pre-scheduled- # row (no self-chaining). Specialised __internal__ action.- # ------------------------------------------------------------------- if action.kind == "onboarding_checkin":- await _run_onboarding_checkin(action, now)- return-# ------------------------------------------------------------------# Nudge engine heartbeat — runs a scan that may insert one or more# `proactive_nudge` rows for future ticks, then chains the next scan.@@ -751,6 +719,12 @@ async def _execute_action(# ------------------------------------------------------------------# Internal channel — bypass outbound message dispatch entirely.# Used by workflow steps (Phase 6) and other internal kinds.+ #+ # This is also where rows from REMOVED features drain. The staff-onboarding+ # kinds (`onboarding_ramp`, `onboarding_kickoff`, `onboarding_checkin`) were+ # all `__internal__`, so any row still pending from before that feature was+ # deleted lands here, gets marked done, and logs once — no dispatch, no+ # crash, no chaining.# ------------------------------------------------------------------if action.channel == "__internal__":mark_action_done(action.id)@@ -1118,231 +1092,6 @@ async def _deliver_to_principal(text: str) -> tuple[bool, str]:return False, "no deliverable channel configured for principal"-async def _run_onboarding_ramp(action: ScheduledAction, now: datetime) -> None:- """Deliver one onboarding ramp segment to the hire and chain the next.-- Reads the plan id from ``channel_ref``, atomically claims the next segment- (compare-and-swap on the plan's ramp index), DMs it to the assigned person- via ``message_person``, then enqueues the next business-day occurrence only- when more segments remain. Always marks the row done — a single delivery- failure must not wedge the row or the drip.- """- from openexecutive.orchestrator.schedule_tools import handle_message_person- from openexecutive.staff_onboarding import store as ob_store- from openexecutive.staff_onboarding.ramp_scheduler import enqueue_ramp-- assert action.id is not None- try:- plan_id = int(action.channel_ref)- except (TypeError, ValueError):- logger.warning("scheduler: onboarding_ramp bad channel_ref=%r", action.channel_ref)- mark_action_done(action.id)- return-- # No assignee → we can't deliver. Stop WITHOUT claiming a segment (claiming- # advances the index, so claiming here would silently burn the segment) and- # WITHOUT chaining a dead drip.- if action.assigned_to_person_id is None:- logger.warning(- "scheduler: onboarding_ramp plan=%s has no assignee — skipping, not chaining",- plan_id,- )- mark_action_done(action.id)- return-- try:- segment, has_more = ob_store.claim_next_ramp_segment(plan_id)- except Exception:- logger.exception("scheduler: onboarding_ramp claim failed plan=%s", plan_id)- mark_action_done(action.id)- return-- if segment is None:- # Drip exhausted (or plan gone/archived) — stop, no re-chain.- mark_action_done(action.id)- return-- try:- await handle_message_person(- {"person_id": action.assigned_to_person_id, "text": segment}- )- except Exception:- # Claim-then-send: the segment's index is already advanced (so a retry- # can't double-DM the hire), which means this segment is dropped on a- # delivery failure. Surface it loudly rather than only at EXCEPTION level.- logger.exception(- "scheduler: onboarding_ramp delivery failed plan=%s — segment dropped "- "(not retried, to avoid double-sends)", plan_id,- )-- mark_action_done(action.id)- if has_more:- enqueue_ramp(plan_id, after=datetime.now(UTC))---def _hire_first_name(full_name: str) -> str:- """Best-effort first name for a friendly greeting."""- return full_name.strip().split(" ", 1)[0] if full_name.strip() else "there"---async def _send_team_notice(department: str, text: str) -> bool:- """Post a welcome notice to a department's first configured channel.-- Delegates to ``broadcast_tools.post_department_notice`` so the SAME privacy- backstop, length cap, and audit trail that guard ``send_department_message``- apply here — an internal sender must not bypass them. Returns True only when- a message was actually sent."""- if not department:- return False- from openexecutive.orchestrator.broadcast_tools import post_department_notice-- result = await post_department_notice(department, text, tool="onboarding_kickoff")- if result.get("status") != "sent":- logger.info("onboarding_kickoff: team notice not sent (dept=%r): %s",- department, result.get("status"))- return result.get("status") == "sent"---def _onboarding_plan_for_action(- action: ScheduledAction,-) -> tuple[int | None, OnboardingPlan | None]:- """Resolve (plan_id, plan) for an onboarding ``__internal__`` action.-- Parses the plan id from ``channel_ref`` (tolerates both ``"<id>"`` and the- check-in ``"<id>:<label>"`` form), then loads the plan. Returns- ``(None, None)`` when the ref is malformed and ``(plan_id, None)`` when the- plan is missing or archived — in both cases the caller should mark the row- done and return. Centralises the parse + load + guard the kickoff/check-in- handlers share."""- from openexecutive.staff_onboarding import store as ob_store-- head = (action.channel_ref or "").partition(":")[0]- try:- plan_id = int(head)- except (TypeError, ValueError):- logger.warning("scheduler: onboarding action bad channel_ref=%r", action.channel_ref)- return None, None- plan = ob_store.get_plan(plan_id)- if plan is None or plan.archived:- return plan_id, None- return plan_id, plan---async def _run_onboarding_kickoff(action: ScheduledAction, now: datetime) -> None:- """Welcome notice to the dept channel + intro-1:1 nudges to manager/buddy.-- Best-effort throughout: a missing channel or a delivery hiccup never wedges- the row. One-shot — no re-chain.- """- from openexecutive.orchestrator.schedule_tools import handle_message_person-- assert action.id is not None- plan_id, plan = _onboarding_plan_for_action(action)- if plan is None:- mark_action_done(action.id)- return-- role = f" as {plan.role}" if plan.role else ""- # Team notice — only when a department channel is configured (no accidental- # broadcast); silently skipped otherwise.- if action.department:- notice = (- f"👋 Please welcome {plan.full_name}, joining the team{role} on "- f"{plan.start_date}. Say hello and help them get oriented!"- )- try:- sent = await _send_team_notice(action.department, notice)- if not sent:- logger.info("onboarding_kickoff: no team channel for dept=%r — skipped",- action.department)- except Exception:- logger.exception("onboarding_kickoff: team notice failed plan=%s", plan_id)-- # Intro-1:1 nudges to manager + buddy (best-effort DMs).- nudges = [- (plan.manager_person_id,- f"You're the manager for {plan.full_name}{role} (starting {plan.start_date}). "- "Please schedule your week-one intro 1:1 and review their onboarding plan."),- (plan.buddy_person_id,- f"You're the onboarding buddy for {plan.full_name}{role} (starting "- f"{plan.start_date}). Please reach out and set up a welcome coffee in week one."),- ]- for person_id, text in nudges:- if person_id is None:- continue- try:- await handle_message_person({"person_id": person_id, "text": text})- except Exception:- logger.exception("onboarding_kickoff: nudge to person %s failed", person_id)-- mark_action_done(action.id)---async def _run_onboarding_checkin(action: ScheduledAction, now: datetime) -> None:- """DM the hire + manager a milestone check-in and advance the plan's phase.-- One-shot per milestone. The recipient's reply lands in chat, where the- Executive's onboarding tools fold it into task/plan progress.- """- from openexecutive.orchestrator.schedule_tools import handle_message_person- from openexecutive.staff_onboarding import store as ob_store- from openexecutive.staff_onboarding.orchestration import phase_for_milestone- from openexecutive.staff_onboarding.service import _PHASE_ORDER-- assert action.id is not None- plan_id, plan = _onboarding_plan_for_action(action)- if plan is None or plan_id is None:- mark_action_done(action.id)- return- # channel_ref is "<plan_id>:<label>" — the label after the colon.- label = (action.channel_ref or "").partition(":")[2]-- day_n = label.removeprefix("day_") or "?"- first = _hire_first_name(plan.full_name)- role = f" ({plan.role})" if plan.role else ""-- hire_msg = (- f"Day {day_n} onboarding check-in 👋 How's it going, {first}? "- "Anything blocking you or that you need? Reply here and I'll route it to the "- "right person."- )- mgr_msg = (- f"{plan.full_name}{role} reaches their day-{day_n} onboarding milestone today. "- "Quick check-in: are they on track? Reply to flag anything or to mark tasks "- "done and I'll update their plan."- )- for person_id, text in (- (action.assigned_to_person_id, hire_msg),- (plan.manager_person_id, mgr_msg),- ):- if person_id is None:- continue- try:- await handle_message_person({"person_id": person_id, "text": text})- except Exception:- logger.exception("onboarding_checkin: message to person %s failed", person_id)-- # Deterministic progress: advance the plan's phase to the milestone, but only- # ever forward. If the current phase isn't in the known order, skip rather- # than risk dragging it back (a -1 sentinel would advance unconditionally).- target = phase_for_milestone(label)- if target is not None and target in _PHASE_ORDER and plan.current_phase in _PHASE_ORDER:- cur_idx = _PHASE_ORDER.index(plan.current_phase)- tgt_idx = _PHASE_ORDER.index(target)- if tgt_idx > cur_idx:- try:- ob_store.update_plan(plan_id, current_phase=target)- except Exception:- logger.exception("onboarding_checkin: phase advance failed plan=%s", plan_id)- elif target is not None:- logger.warning(- "onboarding_checkin: plan %s phase %r not in _PHASE_ORDER — skipping advance",- plan_id, plan.current_phase,- )-- mark_action_done(action.id)--async def _run_dynamic_workflow(action: ScheduledAction, now: datetime) -> None:"""Run a cadence-fired user-created workflow and DM its artifact.diff --git a/packages/core/openexecutive/staff_onboarding/__init__.py b/packages/core/openexecutive/staff_onboarding/__init__.pydeleted file mode 100644index 5fceb517..00000000--- a/packages/core/openexecutive/staff_onboarding/__init__.py+++ /dev/null@@ -1,7 +0,0 @@-"""Staff-onboarding framework — onboarding a person into the company.--Distinct from the company-setup wizard in ``openexecutive.onboarding`` and from-the people roster in ``openexecutive.people``. See ``models`` for the entities-(``OnboardingTemplate``, ``OnboardingPlan``, ``OnboardingTask``) and ``store``-for persistence.-"""diff --git a/packages/core/openexecutive/staff_onboarding/models.py b/packages/core/openexecutive/staff_onboarding/models.pydeleted file mode 100644index 7466b71f..00000000--- a/packages/core/openexecutive/staff_onboarding/models.py+++ /dev/null@@ -1,155 +0,0 @@-"""Pydantic models for the staff-onboarding framework.--This is the *staff* (employee) onboarding subsystem — onboarding a person into-the company — distinct from the *company-setup* wizard in-``openexecutive.onboarding`` and from the people roster in-``openexecutive.people``.--The three entities mirror the shape of ``openexecutive.talent.models`` (plain-Pydantic v2 models, optional ``id``, ISO-string ``created_at`` / ``updated_at``,-``archived`` soft-delete):--- ``OnboardingTemplate`` — a reusable, role/department-scoped blueprint: an- ordered set of task specs (phase + owner-by-role + due offset), the specialist- sections the welcome brief is built from, ramp length, and a check-in cadence.-- ``OnboardingPlan`` — one per hire, instantiated from a template and tailored- from company context. Carries the generated welcome brief + reading list and- rolls its tasks up into ``completion_pct``.-- ``OnboardingTask`` — one checklist item on a plan: phase, owner, due date,- status.-"""-from __future__ import annotations--from enum import StrEnum--from pydantic import BaseModel, Field---class OnboardingStatus(StrEnum):- """Lifecycle of one hire's onboarding plan."""-- DRAFT = "draft" # created, not yet activated (no orchestration fired)- ACTIVE = "active" # in progress- COMPLETED = "completed" # all phases done- ARCHIVED = "archived" # cancelled / no longer tracked---class OnboardingPhase(StrEnum):- """Phases of a ramp, in forward order. ``due_offset_days`` on a task spec is- relative to the hire's start date, so phases are a display grouping rather- than a hard gate."""-- PRE_START = "pre_start"- WEEK_1 = "week_1"- DAY_30 = "day_30"- DAY_60 = "day_60"- DAY_90 = "day_90"---class TaskStatus(StrEnum):- """Status of one checklist item."""-- PENDING = "pending"- IN_PROGRESS = "in_progress"- DONE = "done"- SKIPPED = "skipped" # explicitly not applicable — excluded from completion %---# Owner roles a template task can target. Resolved to a concrete person_id at-# instantiation against the plan (hire / manager / buddy) or the roster-# (department head, IT, etc.). Kept as free-text-with-known-values rather than an-# enum so a template author can name a role the resolver falls back to "manager"-# on, without a schema change.-KNOWN_OWNER_ROLES = ("hire", "manager", "buddy", "department_head", "it", "hr")---class TaskSpec(BaseModel):- """One task in a template — instantiated into an ``OnboardingTask``."""-- title: str- category: str = "general"- phase: OnboardingPhase = OnboardingPhase.WEEK_1- owner_role: str = "manager"- # Days after the hire's start date this task is due. May be negative for- # pre-start tasks (e.g. -3 = three days before day one).- due_offset_days: int = 0---class OnboardingTemplate(BaseModel):- """A reusable onboarding blueprint.-- ``name`` is a unique snake_case key. ``department`` is a free-text grouping- (also used as a hint when resolving the brief's lead specialist).- ``brief_sections`` lists the section ids the ``role_onboarding`` workflow- renders (e.g. ``company_landscape``, ``function_state``).- """-- name: str- title: str- description: str = ""- department: str = ""- # Number of daily ramp-drip messages to send the hire (one per business day- # from start). 0 = no drip. Capped to keep a drip from running for months.- ramp_days: int = Field(default=0, ge=0, le=90)- # Human cadence spec for milestone check-ins, e.g. "day_7,day_30,day_60,day_90".- checkin_cadence: str = ""- task_specs: list[TaskSpec] = Field(default_factory=list)- brief_sections: list[str] = Field(default_factory=list)- is_active: bool = True- created_at: str = ""- updated_at: str = ""---class OnboardingTask(BaseModel):- """One checklist item on a plan."""-- id: int | None = None- plan_id: int- phase: OnboardingPhase = OnboardingPhase.WEEK_1- title: str- category: str = "general"- owner_person_id: int | None = None- due_date: str | None = None # ISO date (YYYY-MM-DD)- status: TaskStatus = TaskStatus.PENDING- completed_at: str | None = None- completed_by_person_id: int | None = None- notes: str = ""- sort_order: int = 0- created_at: str = ""- updated_at: str = ""---class OnboardingPlan(BaseModel):- """One hire's onboarding plan.-- ``person_id`` links the hire to the roster once they exist as a ``Person`` —- it is what unlocks delivery + the ramp drip + check-ins. ``engagement_id`` /- ``candidate_id`` link back to the talent pipeline when the plan originated- from a placed candidate. ``completion_pct`` is computed from the plan's tasks- on read (never stored).- """-- id: int | None = None- full_name: str- role: str = ""- start_date: str # ISO date (YYYY-MM-DD)- person_id: int | None = None- manager_person_id: int | None = None- buddy_person_id: int | None = None- template_name: str = ""- status: OnboardingStatus = OnboardingStatus.DRAFT- current_phase: OnboardingPhase = OnboardingPhase.PRE_START- brief_artifact: str = ""- reading_list: list[str] = Field(default_factory=list)- # Pre-generated daily ramp-drip messages and the index of the next one to- # send. The scheduler's bounded ``onboarding_ramp`` action walks these.- ramp_segments: list[str] = Field(default_factory=list)- ramp_next_index: int = 0- engagement_id: int | None = None- candidate_id: int | None = None- completion_pct: int = 0- archived: bool = False- created_at: str = ""- updated_at: str = ""- # Populated only by ``get_plan`` (detail view); list endpoints leave it empty.- tasks: list[OnboardingTask] = Field(default_factory=list)diff --git a/packages/core/openexecutive/staff_onboarding/orchestration.py b/packages/core/openexecutive/staff_onboarding/orchestration.pydeleted file mode 100644index 62dcd5a2..00000000--- a/packages/core/openexecutive/staff_onboarding/orchestration.py+++ /dev/null@@ -1,167 +0,0 @@-"""Stakeholder orchestration for staff onboarding.--Activating a plan does three things beyond the ramp drip (``ramp_scheduler``):--1. **Kickoff** (one-shot, fires next tick): a welcome notice to the hire's- department channel *if one is configured* (never an accidental broadcast),- plus intro-1:1 nudges DM'd to the manager and buddy.-2. **Milestone check-ins** (day 7 / 30 / 60 / 90): scheduled actions that DM the- hire + manager a check-in and deterministically advance the plan's phase. The- recipient's reply lands in chat, where the Executive's onboarding tools fold- it into task/plan progress (``wait_for_human`` resume is a Phase-7 item, so we- deliberately use the chat-integrated path that works today).--All sends happen in the async scheduler runner (consistent with the ramp), so-these enqueue functions are pure, synchronous DB inserts — unit-testable without-touching any integration.-"""-from __future__ import annotations--import logging-from datetime import UTC, datetime, timedelta-from pathlib import Path--from openexecutive.staff_onboarding import store-from openexecutive.staff_onboarding.models import OnboardingPhase--logger = logging.getLogger(__name__)--_INTERNAL_CHANNEL = "__internal__"-_CHECKIN_HOUR = 9 # UTC, matching the ramp drip--# Milestone label → (days after start, phase the plan advances to on fire).-# Ordered; day_7 maps to WEEK_1 since the 30/60/90 enum starts at DAY_30.-MILESTONES: tuple[tuple[str, int, OnboardingPhase], ...] = (- ("day_7", 7, OnboardingPhase.WEEK_1),- ("day_30", 30, OnboardingPhase.DAY_30),- ("day_60", 60, OnboardingPhase.DAY_60),- ("day_90", 90, OnboardingPhase.DAY_90),-)---def _parse_date(iso: str) -> datetime | None:- try:- d = datetime.fromisoformat(iso[:10])- return d.replace(hour=_CHECKIN_HOUR, minute=0, second=0, microsecond=0, tzinfo=UTC)- except (ValueError, TypeError):- return None---def _already_enqueued(scope_key: str, db_path: Path | None) -> bool:- """True if a live (pending/running/done) action with this ``scope_key``- already exists, so re-activating a plan never duplicates kickoff/check-in- rows. A single indexed lookup — covers the ``running`` window and is not- capped (unlike scanning ``list_scheduled_actions``).-- NOTE: this is a read-then-insert check, not a DB-level uniqueness- constraint, so a narrow TOCTOU window remains if two activations race for- the same plan. The scheduler is single-worker and activation is operator-- triggered, so the worst case is a duplicate DM — acceptable for v1."""- from openexecutive.memory.episodic import scope_key_in_use-- return scope_key_in_use(scope_key, db_path=db_path)---def _plan_department(plan_id: int, db_path: Path | None) -> str:- """The department of a plan's template, or "" — used to route the team- notice to a department channel."""- plan = store.get_plan(plan_id, db_path=db_path)- if plan is None or not plan.template_name:- return ""- tmpl = store.get_template(plan.template_name, db_path=db_path)- return tmpl.department if tmpl is not None else ""---def enqueue_kickoff(plan_id: int, *, db_path: Path | None = None) -> int | None:- """Enqueue the one-shot kickoff action (team notice + intro nudges).-- Fires on the next scheduler tick. Idempotent. Returns the action id, or None- if the plan is missing or a kickoff was already enqueued."""- from openexecutive.memory.episodic import insert_scheduled_action-- plan = store.get_plan(plan_id, db_path=db_path)- if plan is None:- return None- channel_ref = str(plan_id)- scope_key = f"onboarding_kickoff:{plan_id}"- if _already_enqueued(scope_key, db_path):- return None- try:- return insert_scheduled_action(- run_at=datetime.now(UTC).isoformat(),- channel=_INTERNAL_CHANNEL,- channel_ref=channel_ref,- intent_text=f"Onboarding kickoff for plan {plan_id} ({plan.full_name})",- kind="onboarding_kickoff",- department=_plan_department(plan_id, db_path),- assigned_to_person_id=plan.person_id,- scope_key=scope_key,- db_path=db_path,- )- except Exception:- logger.exception("staff_onboarding: enqueue_kickoff failed for plan %s", plan_id)- return None---def enqueue_checkins(plan_id: int, *, db_path: Path | None = None) -> list[int]:- """Enqueue milestone check-in actions for a plan. Returns the ids enqueued.-- Skips milestones whose date is already in the past (activating a hire who- has been around a while shouldn't backfire historical check-ins) and any- already enqueued. Each milestone is its own pre-scheduled row — they do not- self-chain."""- from openexecutive.memory.episodic import insert_scheduled_action-- plan = store.get_plan(plan_id, db_path=db_path)- if plan is None or plan.person_id is None:- return []- base = _parse_date(plan.start_date)- if base is None:- logger.warning("staff_onboarding: plan %s has unparseable start_date", plan_id)- return []-- now = datetime.now(UTC)- department = _plan_department(plan_id, db_path)- enqueued: list[int] = []- for label, offset, _phase in MILESTONES:- run_at = base + timedelta(days=offset)- if run_at <= now:- continue # milestone already in the past — skip- channel_ref = f"{plan_id}:{label}"- scope_key = f"onboarding_checkin:{plan_id}:{label}"- if _already_enqueued(scope_key, db_path):- continue- try:- aid = insert_scheduled_action(- run_at=run_at.isoformat(),- channel=_INTERNAL_CHANNEL,- channel_ref=channel_ref,- intent_text=f"Onboarding {label} check-in for plan {plan_id}",- kind="onboarding_checkin",- department=department,- assigned_to_person_id=plan.person_id,- scope_key=scope_key,- db_path=db_path,- )- enqueued.append(aid)- except Exception:- logger.exception(- "staff_onboarding: enqueue_checkins %s/%s failed", plan_id, label- )- return enqueued---def phase_for_milestone(label: str) -> OnboardingPhase | None:- """The phase a milestone label advances a plan to, or None if unknown."""- for name, _offset, phase in MILESTONES:- if name == label:- return phase- return None---__all__ = [- "MILESTONES",- "enqueue_checkins",- "enqueue_kickoff",- "phase_for_milestone",-]diff --git a/packages/core/openexecutive/staff_onboarding/ramp_scheduler.py b/packages/core/openexecutive/staff_onboarding/ramp_scheduler.pydeleted file mode 100644index 0304db70..00000000--- a/packages/core/openexecutive/staff_onboarding/ramp_scheduler.py+++ /dev/null@@ -1,84 +0,0 @@-"""Bounded ramp-drip scheduling for staff onboarding.--A plan's welcome-brief run pre-generates ``ramp_segments`` (one short message per-ramp day). Activating the plan enqueues the first ``onboarding_ramp`` scheduled-action; the scheduler runner delivers that day's segment and — only while more-remain — chains the next business-day occurrence. This is the one self--terminating recurring kind in the system (every other recurring action chains-forever), so the chaining lives here next to the exhaustion check.-"""-from __future__ import annotations--import logging-from datetime import UTC, datetime, timedelta-from pathlib import Path--from openexecutive.staff_onboarding import store--logger = logging.getLogger(__name__)--# Hour-of-day (UTC) the daily drip is sent. Single-timezone for v1, matching the-# scheduler's principal-brief approach; revisit when company tz lands.-_RAMP_HOUR = 9---def next_business_day(after: datetime, *, hour: int = _RAMP_HOUR) -> datetime:- """The next weekday (Mon-Fri) strictly after ``after``, at ``hour`` UTC.-- A naive ``after`` is treated as UTC so the returned ``run_at`` is always- tz-aware (the scheduler compares due times against an aware ``now``)."""- if after.tzinfo is None:- after = after.replace(tzinfo=UTC)- candidate = (after + timedelta(days=1)).replace(- hour=hour, minute=0, second=0, microsecond=0- )- while candidate.weekday() >= 5: # 5 = Saturday, 6 = Sunday- candidate += timedelta(days=1)- return candidate---def enqueue_ramp(- plan_id: int, *, after: datetime | None = None, db_path: Path | None = None-) -> int | None:- """Enqueue the next ``onboarding_ramp`` action for a plan, or None when the- plan can't drip (missing, no roster person, or segments exhausted)."""- from openexecutive.memory.episodic import (- insert_scheduled_action,- list_scheduled_actions,- )-- plan = store.get_plan(plan_id, db_path=db_path)- if plan is None or plan.person_id is None:- return None- if plan.ramp_next_index >= len(plan.ramp_segments):- return None # nothing left to send — do not chain-- # Idempotency: never run two drip chains for one plan. A pending- # onboarding_ramp row for this plan means a chain is already live, so a- # repeat activate (double-click / retry / activate-while-mid-drip) is a- # no-op. The chain itself is safe because each fire marks its row done- # before enqueuing exactly one successor.- pending = [- a for a in list_scheduled_actions(status="pending", db_path=db_path)- if a.kind == "onboarding_ramp" and a.channel_ref == str(plan_id)- ]- if pending:- return None-- run_at = next_business_day(after or datetime.now(UTC))- try:- return insert_scheduled_action(- run_at=run_at.isoformat(),- channel="__internal__",- channel_ref=str(plan_id),- intent_text=f"Onboarding ramp drip for plan {plan_id}",- kind="onboarding_ramp",- assigned_to_person_id=plan.person_id,- db_path=db_path,- )- except Exception:- logger.exception("staff_onboarding: enqueue_ramp failed for plan %s", plan_id)- return None---__all__ = ["enqueue_ramp", "next_business_day"]diff --git a/packages/core/openexecutive/staff_onboarding/seed.py b/packages/core/openexecutive/staff_onboarding/seed.pydeleted file mode 100644index 672b14d4..00000000--- a/packages/core/openexecutive/staff_onboarding/seed.py+++ /dev/null@@ -1,126 +0,0 @@-"""Default onboarding templates seeded at startup.--Idempotent: a template is only inserted when its ``name`` isn't already present,-so an operator's edits to a seeded template are never clobbered on restart-(mirrors ``scheduler.seed_principal_briefs``).-"""-from __future__ import annotations--import logging-from pathlib import Path--from openexecutive.staff_onboarding import store-from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingTemplate,- TaskSpec,-)--logger = logging.getLogger(__name__)--# Tasks every hire shares, regardless of function. Owners are template roles-# resolved against the plan/roster at instantiation (hire/manager/it/hr/buddy).-_COMMON_TASKS: list[TaskSpec] = [- TaskSpec(title="Send offer letter & confirm start date", category="hr",- phase=OnboardingPhase.PRE_START, owner_role="hr", due_offset_days=-7),- TaskSpec(title="Provision laptop, accounts & access", category="it",- phase=OnboardingPhase.PRE_START, owner_role="it", due_offset_days=-2),- TaskSpec(title="Welcome & intro 1:1 with manager", category="people",- phase=OnboardingPhase.WEEK_1, owner_role="manager", due_offset_days=1),- TaskSpec(title="Meet your onboarding buddy", category="people",- phase=OnboardingPhase.WEEK_1, owner_role="buddy", due_offset_days=2),- TaskSpec(title="Read the welcome brief & company handbook", category="ramp",- phase=OnboardingPhase.WEEK_1, owner_role="hire", due_offset_days=3),- TaskSpec(title="30-day check-in with manager", category="people",- phase=OnboardingPhase.DAY_30, owner_role="manager", due_offset_days=30),- TaskSpec(title="60-day check-in with manager", category="people",- phase=OnboardingPhase.DAY_60, owner_role="manager", due_offset_days=60),- TaskSpec(title="90-day review & ramp retrospective", category="people",- phase=OnboardingPhase.DAY_90, owner_role="manager", due_offset_days=90),-]--_DEFAULT_TEMPLATES: list[OnboardingTemplate] = [- OnboardingTemplate(- name="generic",- title="Generic Onboarding",- description="Default cross-functional onboarding for any new hire.",- ramp_days=5,- checkin_cadence="day_7,day_30,day_60,day_90",- task_specs=_COMMON_TASKS,- brief_sections=["company_landscape", "function_state", "people_map",- "first_90", "week_one"],- ),- OnboardingTemplate(- name="engineering",- title="Engineering Onboarding",- description="Onboarding for engineering / product hires.",- department="product",- ramp_days=7,- checkin_cadence="day_7,day_30,day_60,day_90",- task_specs=[- *_COMMON_TASKS,- TaskSpec(title="Set up dev environment & ship a starter PR",- category="engineering", phase=OnboardingPhase.WEEK_1,- owner_role="buddy", due_offset_days=4),- TaskSpec(title="Walk the architecture & on-call runbook",- category="engineering", phase=OnboardingPhase.WEEK_1,- owner_role="manager", due_offset_days=5),- ],- brief_sections=["company_landscape", "function_state", "people_map",- "first_90", "week_one"],- ),- OnboardingTemplate(- name="go_to_market",- title="Go-to-Market Onboarding",- description="Onboarding for sales / marketing / revenue hires.",- department="marketing",- ramp_days=7,- checkin_cadence="day_7,day_30,day_60,day_90",- task_specs=[- *_COMMON_TASKS,- TaskSpec(title="Learn the pitch, ICP & competitive positioning",- category="gtm", phase=OnboardingPhase.WEEK_1,- owner_role="manager", due_offset_days=4),- TaskSpec(title="Shadow customer calls & review the funnel",- category="gtm", phase=OnboardingPhase.DAY_30,- owner_role="buddy", due_offset_days=14),- ],- brief_sections=["company_landscape", "function_state", "people_map",- "first_90", "week_one"],- ),- OnboardingTemplate(- name="finance",- title="Finance Onboarding",- description="Onboarding for finance / accounting hires.",- department="finance",- ramp_days=5,- checkin_cadence="day_7,day_30,day_60,day_90",- task_specs=[- *_COMMON_TASKS,- TaskSpec(title="Review the model, board metrics & close process",- category="finance", phase=OnboardingPhase.WEEK_1,- owner_role="manager", due_offset_days=4),- ],- brief_sections=["company_landscape", "function_state", "people_map",- "first_90", "week_one"],- ),-]---def seed_default_templates(db_path: Path | None = None) -> int:- """Insert any missing default templates. Returns the number newly inserted."""- inserted = 0- for tmpl in _DEFAULT_TEMPLATES:- try:- if store.get_template(tmpl.name, db_path=db_path) is not None:- continue- store.upsert_template(tmpl, db_path=db_path)- inserted += 1- except Exception:- logger.exception("staff_onboarding: failed to seed template %r", tmpl.name)- if inserted:- logger.info("staff_onboarding: seeded %d default template(s)", inserted)- return inserted---__all__ = ["seed_default_templates"]diff --git a/packages/core/openexecutive/staff_onboarding/service.py b/packages/core/openexecutive/staff_onboarding/service.pydeleted file mode 100644index 25948373..00000000--- a/packages/core/openexecutive/staff_onboarding/service.py+++ /dev/null@@ -1,188 +0,0 @@-"""Instantiation + lifecycle helpers for the staff-onboarding framework.--Kept separate from ``store`` (pure persistence) and ``api.routes`` (HTTP glue)-so the logic that turns a template into a concrete plan — due-date math, owner-resolution against the roster/departments — is unit-testable on its own.-"""-from __future__ import annotations--import logging-from datetime import date, timedelta-from pathlib import Path--from openexecutive.staff_onboarding import store-from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingStatus,- OnboardingTemplate,-)--logger = logging.getLogger(__name__)--# Forward order of phases, used to advance a plan and to order instantiated tasks.-_PHASE_ORDER: tuple[OnboardingPhase, ...] = (- OnboardingPhase.PRE_START,- OnboardingPhase.WEEK_1,- OnboardingPhase.DAY_30,- OnboardingPhase.DAY_60,- OnboardingPhase.DAY_90,-)---def _parse_date(iso: str) -> date | None:- """Parse a ``YYYY-MM-DD`` string, tolerating a full ISO datetime. None on- failure so a malformed start date degrades to "no due date" rather than- crashing instantiation."""- try:- return date.fromisoformat(iso[:10])- except (ValueError, TypeError):- logger.warning("staff_onboarding: unparseable date %r", iso)- return None---def _resolve_owner(- owner_role: str,- *,- person_id: int | None,- manager_person_id: int | None,- buddy_person_id: int | None,- department: str,- db_path: Path | None,-) -> int | None:- """Map a template ``owner_role`` to a concrete person_id, or None when it- can't be resolved (the task is created unassigned — better than guessing)."""- role = (owner_role or "").strip().lower()- if role == "hire":- return person_id- if role == "manager":- return manager_person_id- if role == "buddy":- return buddy_person_id- if role == "department_head" and department:- try:- from openexecutive.departments import store as dept_store-- dept = dept_store.get_department(department)- if dept is not None:- return dept.config.head_person_id- except Exception:- logger.exception("staff_onboarding: department-head resolution failed")- # it / hr / unknown roles → unassigned for now.- return None---def instantiate_plan(- *,- full_name: str,- start_date: str,- role: str = "",- template: OnboardingTemplate | None = None,- person_id: int | None = None,- manager_person_id: int | None = None,- buddy_person_id: int | None = None,- engagement_id: int | None = None,- candidate_id: int | None = None,- db_path: Path | None = None,-) -> int:- """Create a plan and (when a template is given) its tasks.-- Each template task spec becomes an ``OnboardingTask`` with a concrete- ``due_date`` (``start_date + due_offset_days``) and a resolved owner. Returns- the new plan id. The plan starts in ``DRAFT`` — orchestration/ramp are fired- explicitly on activation, not here.- """- template_name = template.name if template else ""- plan_id = store.create_plan(- full_name=full_name,- start_date=start_date,- role=role,- person_id=person_id,- manager_person_id=manager_person_id,- buddy_person_id=buddy_person_id,- template_name=template_name,- status=OnboardingStatus.DRAFT,- engagement_id=engagement_id,- candidate_id=candidate_id,- db_path=db_path,- )-- if template is None:- return plan_id-- base = _parse_date(start_date)- for order, spec in enumerate(template.task_specs):- due: str | None = None- if base is not None:- due = (base + timedelta(days=spec.due_offset_days)).isoformat()- owner = _resolve_owner(- spec.owner_role,- person_id=person_id,- manager_person_id=manager_person_id,- buddy_person_id=buddy_person_id,- department=template.department,- db_path=db_path,- )- store.add_task(- plan_id=plan_id,- title=spec.title,- phase=spec.phase,- category=spec.category,- owner_person_id=owner,- due_date=due,- sort_order=order,- db_path=db_path,- )- return plan_id---def activate_plan(plan_id: int, db_path: Path | None = None) -> bool:- """Move a plan to ``active`` and fire its onboarding orchestration.-- On activation we enqueue (all idempotent, all pure DB inserts — the async- scheduler does the actual sending):-- - the **ramp drip** (``enqueue_ramp``) — only actually fires once the plan- has a roster ``person_id`` and pre-generated ``ramp_segments``;- - the **kickoff** (``enqueue_kickoff``) — team notice + manager/buddy intro- nudges, on the next tick;- - the **milestone check-ins** (``enqueue_checkins``) — day 7/30/60/90.-- Returns False if the plan is missing.- """- plan = store.get_plan(plan_id, db_path=db_path)- if plan is None:- return False- store.update_plan(plan_id, status=OnboardingStatus.ACTIVE, db_path=db_path)- from openexecutive.staff_onboarding.orchestration import (- enqueue_checkins,- enqueue_kickoff,- )- from openexecutive.staff_onboarding.ramp_scheduler import enqueue_ramp-- enqueue_ramp(plan_id, db_path=db_path)- enqueue_kickoff(plan_id, db_path=db_path)- enqueue_checkins(plan_id, db_path=db_path)- return True---def advance_phase(plan_id: int, db_path: Path | None = None) -> OnboardingPhase | None:- """Move a plan to the next phase in ``_PHASE_ORDER``. Returns the new phase,- or None if the plan is missing or already at the final phase."""- plan = store.get_plan(plan_id, db_path=db_path)- if plan is None:- return None- try:- idx = _PHASE_ORDER.index(plan.current_phase)- except ValueError:- # Phase not in the known order (e.g. a future enum value not yet added- # here) — refuse to advance rather than silently jumping to WEEK_1.- logger.warning(- "staff_onboarding: plan %d has phase %r outside _PHASE_ORDER",- plan_id, plan.current_phase,- )- return None- if idx >= len(_PHASE_ORDER) - 1:- return None- new_phase = _PHASE_ORDER[idx + 1]- store.update_plan(plan_id, current_phase=new_phase, db_path=db_path)- return new_phasediff --git a/packages/core/openexecutive/staff_onboarding/specialists.py b/packages/core/openexecutive/staff_onboarding/specialists.pydeleted file mode 100644index 5b56e210..00000000--- a/packages/core/openexecutive/staff_onboarding/specialists.py+++ /dev/null@@ -1,80 +0,0 @@-"""Resolve which specialist lens tailors a role's onboarding.--Generalizes to any role (not just C-suite): a department's configured-``specialist_key`` wins when known, otherwise a function-name map, otherwise the-strategy chief (``cso``) as a thoughtful-but-generic fallback. Every role-therefore gets *some* specialist lens.-"""-from __future__ import annotations--import logging-from pathlib import Path--logger = logging.getLogger(__name__)--# Human-friendly function names → specialist registry keys. Mirrors the intent-# of talent's exec_search_brief map; kept local so the onboarding subsystem-# doesn't import a private name from a talent workflow.-FUNCTION_TO_SPECIALIST: dict[str, str] = {- "engineering": "cpo", # closest available — no CTO specialist- "product": "cpo",- "design": "cpo",- "marketing": "cmo",- "sales": "cmo", # closest available — no CRO specialist- "revenue": "cmo",- "operations": "coo",- "ops": "coo",- "finance": "cfo",- "accounting": "cfo",- "strategy": "cso",- "legal": "gc",- "people": "chro",- "hr": "chro",- "talent": "chro",-}--_FALLBACK = "cso"---def _from_text(text: str) -> str | None:- """Best-effort: match any known function keyword appearing in free text."""- low = (text or "").lower()- for key, specialist in FUNCTION_TO_SPECIALIST.items():- if key in low:- return specialist- return None---def resolve_specialist(- *,- role: str = "",- function: str = "",- department: str = "",- db_path: Path | None = None,-) -> str:- """Resolve the lead specialist for a role.-- Precedence: department's configured ``specialist_key`` → explicit- ``function`` → keywords in ``department``/``role`` text → ``cso`` fallback.- """- if department:- try:- from openexecutive.departments import store as dept_store-- dept = dept_store.get_department(department, db_path=db_path)- if dept is not None and dept.config.specialist_key:- return dept.config.specialist_key- except Exception:- logger.exception("staff_onboarding: department specialist lookup failed")-- if function:- mapped = FUNCTION_TO_SPECIALIST.get(function.strip().lower()) or _from_text(function)- if mapped:- return mapped-- for text in (department, role):- mapped = _from_text(text)- if mapped:- return mapped-- return _FALLBACKdiff --git a/packages/core/openexecutive/staff_onboarding/store.py b/packages/core/openexecutive/staff_onboarding/store.pydeleted file mode 100644index c5a709cc..00000000--- a/packages/core/openexecutive/staff_onboarding/store.py+++ /dev/null@@ -1,558 +0,0 @@-"""SQLite-backed persistence for the staff-onboarding framework.--Lives in the same ``episodic_memory.db`` as people / departments / talent /-episodic so there is one place to look. Tables are created idempotently via-``CREATE TABLE IF NOT EXISTS`` — no migration tooling needed.--The ``_resolve_db_path`` pattern lets tests monkeypatch ``DB_PATH`` and have it-take effect at call time, mirroring ``openexecutive.talent.store``.--Template task-specs and brief-section lists are stored as JSON text columns-(denormalized ``name`` / ``is_active`` alongside, like ``dynamic_workflows``);-plans and tasks are first-class rows so they can be queried and rolled up.-"""-from __future__ import annotations--import json-import logging-import os-import sqlite3-from collections.abc import Generator-from contextlib import contextmanager-from datetime import UTC, datetime-from pathlib import Path--from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingPlan,- OnboardingStatus,- OnboardingTask,- OnboardingTemplate,- TaskSpec,- TaskStatus,-)--logger = logging.getLogger(__name__)--DB_PATH = Path(os.environ.get("EPISODIC_DB_PATH", "./episodic_memory.db"))---def _resolve_db_path(db_path: Path | None) -> Path:- """Return caller-supplied path or the current module-level DB_PATH.-- Dynamic resolution allows tests to monkeypatch DB_PATH and have it take- effect at call time rather than at def time.- """- return db_path if db_path is not None else DB_PATH---@contextmanager-def _get_conn(db_path: Path | None = None) -> Generator[sqlite3.Connection, None, None]:- conn = sqlite3.connect(str(_resolve_db_path(db_path)))- conn.row_factory = sqlite3.Row- conn.execute("PRAGMA foreign_keys = ON")- try:- yield conn- conn.commit()- finally:- conn.close()---def _table_exists(conn: sqlite3.Connection, name: str) -> bool:- return conn.execute(- "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)- ).fetchone() is not None---def _now() -> str:- return datetime.now(UTC).isoformat()---# --------------------------------------------------------------------------- #-# Schema-# --------------------------------------------------------------------------- #--def initialize_db(db_path: Path | None = None) -> None:- """Create staff-onboarding tables idempotently. Safe to call repeatedly."""- with _get_conn(db_path) as conn:- conn.executescript("""- CREATE TABLE IF NOT EXISTS onboarding_templates (- name TEXT PRIMARY KEY,- title TEXT NOT NULL,- description TEXT NOT NULL DEFAULT '',- department TEXT NOT NULL DEFAULT '',- ramp_days INTEGER NOT NULL DEFAULT 0,- checkin_cadence TEXT NOT NULL DEFAULT '',- task_specs_json TEXT NOT NULL DEFAULT '[]',- brief_sections_json TEXT NOT NULL DEFAULT '[]',- is_active INTEGER NOT NULL DEFAULT 1,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL- );- CREATE INDEX IF NOT EXISTS idx_onboarding_templates_active- ON onboarding_templates(is_active);-- CREATE TABLE IF NOT EXISTS onboarding_plans (- id INTEGER PRIMARY KEY AUTOINCREMENT,- full_name TEXT NOT NULL,- role TEXT NOT NULL DEFAULT '',- start_date TEXT NOT NULL,- person_id INTEGER,- manager_person_id INTEGER,- buddy_person_id INTEGER,- template_name TEXT NOT NULL DEFAULT '',- status TEXT NOT NULL DEFAULT 'draft',- current_phase TEXT NOT NULL DEFAULT 'pre_start',- brief_artifact TEXT NOT NULL DEFAULT '',- reading_list_json TEXT NOT NULL DEFAULT '[]',- ramp_segments_json TEXT NOT NULL DEFAULT '[]',- ramp_next_index INTEGER NOT NULL DEFAULT 0,- engagement_id INTEGER,- candidate_id INTEGER,- archived INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL- );- CREATE INDEX IF NOT EXISTS idx_onboarding_plans_status- ON onboarding_plans(status);- CREATE INDEX IF NOT EXISTS idx_onboarding_plans_person- ON onboarding_plans(person_id);- CREATE INDEX IF NOT EXISTS idx_onboarding_plans_archived- ON onboarding_plans(archived);-- CREATE TABLE IF NOT EXISTS onboarding_tasks (- id INTEGER PRIMARY KEY AUTOINCREMENT,- plan_id INTEGER NOT NULL,- phase TEXT NOT NULL DEFAULT 'week_1',- title TEXT NOT NULL,- category TEXT NOT NULL DEFAULT 'general',- owner_person_id INTEGER,- due_date TEXT,- status TEXT NOT NULL DEFAULT 'pending',- completed_at TEXT,- completed_by_person_id INTEGER,- notes TEXT NOT NULL DEFAULT '',- sort_order INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- FOREIGN KEY (plan_id) REFERENCES onboarding_plans(id) ON DELETE CASCADE- );- CREATE INDEX IF NOT EXISTS idx_onboarding_tasks_plan- ON onboarding_tasks(plan_id);- """)---# --------------------------------------------------------------------------- #-# Row mapping helpers-# --------------------------------------------------------------------------- #--def _row_to_template(row: sqlite3.Row) -> OnboardingTemplate:- return OnboardingTemplate(- name=row["name"],- title=row["title"],- description=row["description"],- department=row["department"],- ramp_days=int(row["ramp_days"]),- checkin_cadence=row["checkin_cadence"],- task_specs=[TaskSpec(**t) for t in json.loads(row["task_specs_json"] or "[]")],- brief_sections=list(json.loads(row["brief_sections_json"] or "[]")),- is_active=bool(row["is_active"]),- created_at=row["created_at"],- updated_at=row["updated_at"],- )---def _row_to_task(row: sqlite3.Row) -> OnboardingTask:- return OnboardingTask(- id=int(row["id"]),- plan_id=int(row["plan_id"]),- phase=OnboardingPhase(row["phase"]),- title=row["title"],- category=row["category"],- owner_person_id=row["owner_person_id"],- due_date=row["due_date"],- status=TaskStatus(row["status"]),- completed_at=row["completed_at"],- completed_by_person_id=row["completed_by_person_id"],- notes=row["notes"],- sort_order=int(row["sort_order"]),- created_at=row["created_at"],- updated_at=row["updated_at"],- )---def _row_to_plan(row: sqlite3.Row) -> OnboardingPlan:- return OnboardingPlan(- id=int(row["id"]),- full_name=row["full_name"],- role=row["role"],- start_date=row["start_date"],- person_id=row["person_id"],- manager_person_id=row["manager_person_id"],- buddy_person_id=row["buddy_person_id"],- template_name=row["template_name"],- status=OnboardingStatus(row["status"]),- current_phase=OnboardingPhase(row["current_phase"]),- brief_artifact=row["brief_artifact"],- reading_list=list(json.loads(row["reading_list_json"] or "[]")),- ramp_segments=list(json.loads(row["ramp_segments_json"] or "[]")),- ramp_next_index=int(row["ramp_next_index"]),- engagement_id=row["engagement_id"],- candidate_id=row["candidate_id"],- archived=bool(row["archived"]),- created_at=row["created_at"],- updated_at=row["updated_at"],- )---def _completion_pct(statuses: list[TaskStatus]) -> int:- """Percent of non-skipped tasks that are done (0 when there are none)."""- counted = [s for s in statuses if s != TaskStatus.SKIPPED]- if not counted:- return 0- done = sum(1 for s in counted if s == TaskStatus.DONE)- return round(done * 100 / len(counted))---# --------------------------------------------------------------------------- #-# Template CRUD-# --------------------------------------------------------------------------- #--def upsert_template(template: OnboardingTemplate, db_path: Path | None = None) -> str:- """Insert or replace a template by ``name``. Returns the template name.-- Stamps ``created_at`` on first insert and always refreshes ``updated_at``.- """- now = _now()- task_specs_json = json.dumps([t.model_dump() for t in template.task_specs])- brief_sections_json = json.dumps(list(template.brief_sections))- with _get_conn(db_path) as conn:- existing = conn.execute(- "SELECT created_at FROM onboarding_templates WHERE name = ?",- (template.name,),- ).fetchone()- created_at = existing["created_at"] if existing else now- conn.execute(- "INSERT OR REPLACE INTO onboarding_templates (name, title, description,"- " department, ramp_days, checkin_cadence, task_specs_json,"- " brief_sections_json, is_active, created_at, updated_at)"- " VALUES (?,?,?,?,?,?,?,?,?,?,?)",- (- template.name, template.title, template.description,- template.department, template.ramp_days, template.checkin_cadence,- task_specs_json, brief_sections_json, int(template.is_active),- created_at, now,- ),- )- return template.name---def get_template(name: str, db_path: Path | None = None) -> OnboardingTemplate | None:- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "onboarding_templates"):- return None- row = conn.execute(- "SELECT * FROM onboarding_templates WHERE name = ?", (name,)- ).fetchone()- return _row_to_template(row) if row else None---def list_templates(- active_only: bool = True, db_path: Path | None = None-) -> list[OnboardingTemplate]:- if not _resolve_db_path(db_path).exists():- return []- with _get_conn(db_path) as conn:- if not _table_exists(conn, "onboarding_templates"):- return []- where = "WHERE is_active = 1" if active_only else ""- rows = conn.execute(- f"SELECT * FROM onboarding_templates {where} ORDER BY name"- ).fetchall()- return [_row_to_template(r) for r in rows]---def delete_template(name: str, db_path: Path | None = None) -> bool:- with _get_conn(db_path) as conn:- cursor = conn.execute(- "DELETE FROM onboarding_templates WHERE name = ?", (name,)- )- return cursor.rowcount > 0---# --------------------------------------------------------------------------- #-# Plan CRUD-# --------------------------------------------------------------------------- #--def create_plan(- *,- full_name: str,- start_date: str,- role: str = "",- person_id: int | None = None,- manager_person_id: int | None = None,- buddy_person_id: int | None = None,- template_name: str = "",- status: OnboardingStatus = OnboardingStatus.DRAFT,- engagement_id: int | None = None,- candidate_id: int | None = None,- db_path: Path | None = None,-) -> int:- """Insert a new onboarding plan. Returns the new plan id."""- now = _now()- with _get_conn(db_path) as conn:- cursor = conn.execute(- "INSERT INTO onboarding_plans (full_name, role, start_date, person_id,"- " manager_person_id, buddy_person_id, template_name, status,"- " current_phase, engagement_id, candidate_id, created_at, updated_at)"- " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",- (- full_name, role, start_date, person_id, manager_person_id,- buddy_person_id, template_name, status.value,- OnboardingPhase.PRE_START.value, engagement_id, candidate_id,- now, now,- ),- )- return int(cursor.lastrowid or 0)---def get_plan(plan_id: int, db_path: Path | None = None) -> OnboardingPlan | None:- """Fetch a plan with its tasks and computed ``completion_pct``."""- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "onboarding_plans"):- return None- row = conn.execute(- "SELECT * FROM onboarding_plans WHERE id = ?", (plan_id,)- ).fetchone()- if row is None:- return None- plan = _row_to_plan(row)- task_rows = conn.execute(- "SELECT * FROM onboarding_tasks WHERE plan_id = ? ORDER BY sort_order, id",- (plan_id,),- ).fetchall()- plan.tasks = [_row_to_task(r) for r in task_rows]- plan.completion_pct = _completion_pct([t.status for t in plan.tasks])- return plan---def list_plans(- status: OnboardingStatus | None = None,- include_archived: bool = False,- db_path: Path | None = None,-) -> list[OnboardingPlan]:- """List plans (newest last) with ``completion_pct`` but without their tasks."""- if not _resolve_db_path(db_path).exists():- return []- with _get_conn(db_path) as conn:- if not _table_exists(conn, "onboarding_plans"):- return []- clauses: list[str] = []- params: list[object] = []- if not include_archived:- clauses.append("archived = 0")- if status is not None:- clauses.append("status = ?")- params.append(status.value)- where = f"WHERE {' AND '.join(clauses)}" if clauses else ""- rows = conn.execute(- f"SELECT * FROM onboarding_plans {where} ORDER BY id", params- ).fetchall()- plans = [_row_to_plan(r) for r in rows]- # Roll completion up per plan in one extra query each — plan counts are- # small (active hires), so this stays cheap.- for plan in plans:- task_rows = conn.execute(- "SELECT status FROM onboarding_tasks WHERE plan_id = ?", (plan.id,)- ).fetchall()- plan.completion_pct = _completion_pct(- [TaskStatus(r["status"]) for r in task_rows]- )- return plans---def update_plan(- plan_id: int,- *,- person_id: int | None = None,- manager_person_id: int | None = None,- buddy_person_id: int | None = None,- status: OnboardingStatus | None = None,- current_phase: OnboardingPhase | None = None,- brief_artifact: str | None = None,- reading_list: list[str] | None = None,- ramp_segments: list[str] | None = None,- ramp_next_index: int | None = None,- db_path: Path | None = None,-) -> bool:- """Patch mutable plan fields. Only non-None args are written — this is a- set-or-reassign helper, not a clear-to-NULL one (passing None for a- person/manager/buddy leaves the existing value untouched; there is no flow- that detaches those links). Returns True if a row was modified."""- # (column, value) for each field the caller actually supplied.- updates: list[tuple[str, object]] = []- if person_id is not None:- updates.append(("person_id", person_id))- if manager_person_id is not None:- updates.append(("manager_person_id", manager_person_id))- if buddy_person_id is not None:- updates.append(("buddy_person_id", buddy_person_id))- if status is not None:- updates.append(("status", status.value))- if current_phase is not None:- updates.append(("current_phase", current_phase.value))- if brief_artifact is not None:- updates.append(("brief_artifact", brief_artifact))- if reading_list is not None:- updates.append(("reading_list_json", json.dumps(list(reading_list))))- if ramp_segments is not None:- updates.append(("ramp_segments_json", json.dumps(list(ramp_segments))))- if ramp_next_index is not None:- updates.append(("ramp_next_index", ramp_next_index))- if not updates:- return False- updates.append(("updated_at", _now()))- sets = [f"{col} = ?" for col, _ in updates]- params: list[object] = [val for _, val in updates]- params.append(plan_id)- with _get_conn(db_path) as conn:- cursor = conn.execute(- f"UPDATE onboarding_plans SET {', '.join(sets)} WHERE id = ?", params- )- return cursor.rowcount > 0---def claim_next_ramp_segment(- plan_id: int, db_path: Path | None = None-) -> tuple[str | None, bool]:- """Pop the next ramp-drip segment for a plan and advance the index.-- Returns ``(segment_text, has_more)``. ``segment_text`` is None when the drip- is exhausted (or the plan is missing) — the caller should not send anything- and should not re-chain. ``has_more`` is True when at least one further- segment remains after this one, so the scheduler knows whether to enqueue- the next business-day occurrence.- """- with _get_conn(db_path) as conn:- row = conn.execute(- "SELECT ramp_segments_json, ramp_next_index FROM onboarding_plans"- " WHERE id = ? AND archived = 0",- (plan_id,),- ).fetchone()- if row is None:- return None, False- segments = list(json.loads(row["ramp_segments_json"] or "[]"))- idx = int(row["ramp_next_index"])- if idx >= len(segments):- return None, False- segment = str(segments[idx])- new_idx = idx + 1- # Compare-and-swap on the index so two concurrent claims (a retry or a- # double-fire) can't both serve the same segment: only the claim that- # still sees ``idx`` wins; a loser sees rowcount 0 and serves nothing.- cursor = conn.execute(- "UPDATE onboarding_plans SET ramp_next_index = ?, updated_at = ?"- " WHERE id = ? AND ramp_next_index = ?",- (new_idx, _now(), plan_id, idx),- )- if cursor.rowcount == 0:- return None, False- return segment, new_idx < len(segments)---def archive_plan(plan_id: int, db_path: Path | None = None) -> bool:- """Soft-delete a plan (and mark it archived). Returns True if found+archived."""- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE onboarding_plans SET archived = 1, status = ?, updated_at = ?"- " WHERE id = ? AND archived = 0",- (OnboardingStatus.ARCHIVED.value, _now(), plan_id),- )- return cursor.rowcount > 0---# --------------------------------------------------------------------------- #-# Task CRUD-# --------------------------------------------------------------------------- #--def add_task(- *,- plan_id: int,- title: str,- phase: OnboardingPhase = OnboardingPhase.WEEK_1,- category: str = "general",- owner_person_id: int | None = None,- due_date: str | None = None,- sort_order: int = 0,- db_path: Path | None = None,-) -> int:- """Insert a task on a plan. Returns the new task id."""- now = _now()- with _get_conn(db_path) as conn:- cursor = conn.execute(- "INSERT INTO onboarding_tasks (plan_id, phase, title, category,"- " owner_person_id, due_date, status, sort_order, created_at, updated_at)"- " VALUES (?,?,?,?,?,?,?,?,?,?)",- (- plan_id, phase.value, title, category, owner_person_id, due_date,- TaskStatus.PENDING.value, sort_order, now, now,- ),- )- return int(cursor.lastrowid or 0)---def list_tasks(plan_id: int, db_path: Path | None = None) -> list[OnboardingTask]:- if not _resolve_db_path(db_path).exists():- return []- with _get_conn(db_path) as conn:- if not _table_exists(conn, "onboarding_tasks"):- return []- rows = conn.execute(- "SELECT * FROM onboarding_tasks WHERE plan_id = ? ORDER BY sort_order, id",- (plan_id,),- ).fetchall()- return [_row_to_task(r) for r in rows]---def get_task(task_id: int, db_path: Path | None = None) -> OnboardingTask | None:- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "onboarding_tasks"):- return None- row = conn.execute(- "SELECT * FROM onboarding_tasks WHERE id = ?", (task_id,)- ).fetchone()- return _row_to_task(row) if row else None---def set_task_status(- task_id: int,- status: TaskStatus,- *,- completed_by_person_id: int | None = None,- db_path: Path | None = None,-) -> bool:- """Set a task's status. Moving to ``done`` stamps ``completed_at`` /- ``completed_by_person_id``; moving away from ``done`` clears them. Returns- True if a row was modified."""- now = _now()- completed_at = now if status == TaskStatus.DONE else None- completed_by = completed_by_person_id if status == TaskStatus.DONE else None- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE onboarding_tasks SET status = ?, completed_at = ?,"- " completed_by_person_id = ?, updated_at = ? WHERE id = ?",- (status.value, completed_at, completed_by, now, task_id),- )- return cursor.rowcount > 0---def delete_task(task_id: int, db_path: Path | None = None) -> bool:- with _get_conn(db_path) as conn:- cursor = conn.execute("DELETE FROM onboarding_tasks WHERE id = ?", (task_id,))- return cursor.rowcount > 0diff --git a/packages/core/openexecutive/talent/__init__.py b/packages/core/openexecutive/talent/__init__.pydeleted file mode 100644index 31ac21e3..00000000--- a/packages/core/openexecutive/talent/__init__.py+++ /dev/null@@ -1,16 +0,0 @@-"""Talent / executive-search core.--The talent-intelligence platform built on Open Executive — in-house hiring,-where searches are run *within* this company (not on behalf of external-clients). Two entities:--- ``Engagement`` — one search: a role we're hiring for in this company.-- ``Candidate`` — a person being considered for an engagement, moving through- the pipeline ``lead → screened → interviewed → offer → placed`` (or- ``rejected``).--Persistence mirrors ``openexecutive.people`` exactly: SQLite tables created-idempotently in the shared ``episodic_memory.db``, with a ``_resolve_db_path``-indirection so tests can monkeypatch ``DB_PATH``. See ``docs/talent-platform--scoping.md`` for how this fits the broader roadmap.-"""diff --git a/packages/core/openexecutive/talent/graph.py b/packages/core/openexecutive/talent/graph.pydeleted file mode 100644index ad4681c5..00000000--- a/packages/core/openexecutive/talent/graph.py+++ /dev/null@@ -1,225 +0,0 @@-"""Talent graph — semantic candidate matching over a ChromaDB collection.--Phase 2 of the talent platform. Candidates are indexed into a dedicated-``talent_candidates`` ChromaDB collection (separate from the knowledge/company-collections so candidate profiles never blend into RAG). Two queries are-exposed:--- ``match_candidates_for_engagement`` — rank the whole candidate pool against an- engagement's role + must-haves (a cross-engagement talent pool, not just that- engagement's own candidates).-- ``find_similar_candidates`` — given a candidate, find others like them.--Indexing is best-effort and called from the API layer after a talent-store-mutation (the store stays a pure SQLite layer). The ``KnowledgeStore``-``query`` interface only filters by ``domain``, so archived rows and the query-candidate itself are excluded by over-fetching and post-filtering, mirroring the-knowledge retriever.-"""-from __future__ import annotations--import logging-from typing import TYPE_CHECKING, Any--from openexecutive.talent import store as talent_store--if TYPE_CHECKING:- from openexecutive.knowledge.store import KnowledgeStore- from openexecutive.talent.models import Candidate, Engagement--logger = logging.getLogger(__name__)--CANDIDATES_COLLECTION = "talent_candidates"--# Over-fetch factor: post-filtering drops archived rows and (for similar) the-# query candidate itself, so ask Chroma for more than requested then slice.-_OVERFETCH = 3-_MAX_OVERFETCH = 50---def candidate_document(candidate: Candidate) -> str:- """Build the searchable profile text indexed for a candidate.-- Joins the human-meaningful fields; the screening summary (when present)- carries the richest signal so it is included. Empty fields are dropped so- the embedding isn't diluted with blank labels.- """- parts = [- candidate.full_name,- candidate.current_title,- candidate.current_company,- candidate.location,- candidate.source,- candidate.notes,- candidate.screening_summary,- ]- return "\n".join(p.strip() for p in parts if p and p.strip())---def _metadata(candidate: Candidate) -> dict[str, Any]:- return {- "candidate_id": candidate.id,- "engagement_id": candidate.engagement_id,- "stage": candidate.stage.value,- }---def _doc_id(candidate_id: int) -> str:- return f"candidate-{candidate_id}"---def index_candidate(candidate: Candidate, store: KnowledgeStore) -> None:- """Upsert (or remove, if archived) one candidate in the talent index.-- Best-effort: a vector-store failure is logged and swallowed so candidate- CRUD never fails because the index is unavailable. An archived candidate is- removed from the index rather than indexed.- """- if candidate.id is None:- return- try:- if candidate.archived:- store.delete_documents(- CANDIDATES_COLLECTION, {"candidate_id": candidate.id}- )- return- text = candidate_document(candidate)- if not text:- # Nothing meaningful to embed — make sure no stale doc lingers.- store.delete_documents(- CANDIDATES_COLLECTION, {"candidate_id": candidate.id}- )- return- store.add_documents(- texts=[text],- metadatas=[_metadata(candidate)],- ids=[_doc_id(candidate.id)],- collection=CANDIDATES_COLLECTION,- )- except Exception: # noqa: BLE001 — index sync must never break CRUD- logger.warning("talent.graph: failed to index candidate %s", candidate.id, exc_info=True)---def remove_candidate(candidate_id: int, store: KnowledgeStore) -> None:- """Best-effort removal of a candidate from the talent index."""- try:- store.delete_documents(CANDIDATES_COLLECTION, {"candidate_id": candidate_id})- except Exception: # noqa: BLE001- logger.warning("talent.graph: failed to remove candidate %s", candidate_id, exc_info=True)---def _score(distance: float | None) -> float:- """Convert a cosine distance to a 0-1 similarity score (higher = closer).-- Cosine distance runs 0..2; anything past 1.0 (a genuinely poor match) is- clamped to 0.0 — those candidates are not worth distinguishing.- """- if distance is None:- return 0.0- # Clamp BOTH ends: distance can be a tiny negative (float artifact on- # near-identical vectors) → score just over 1.0, or > 1.0 → negative.- return min(1.0, max(0.0, round(1.0 - distance, 4)))---def _result(row: dict[str, Any]) -> dict[str, Any]:- meta = row.get("metadata") or {}- return {- "candidate_id": meta.get("candidate_id"),- "engagement_id": meta.get("engagement_id"),- "stage": meta.get("stage"),- "score": _score(row.get("distance")),- }---def match_candidates_for_engagement(- engagement: Engagement,- store: KnowledgeStore,- *,- limit: int = 10,-) -> list[dict[str, Any]]:- """Rank the candidate pool against an engagement's role + must-haves.-- Returns up to ``limit`` matches, each ``{candidate_id, engagement_id,- stage, score}``, best first. Archived candidates are never in the index, so- no archived filtering is needed beyond what indexing already guarantees.- """- if limit <= 0:- return []- query_text = "\n".join(- p for p in (engagement.role_title, engagement.must_haves, engagement.description) if p- ).strip()- if not query_text:- return []- # No over-fetch needed: archived candidates are never in the index and- # there is no self to exclude here, so the top `limit` rows are the answer.- rows = store.query(- query_text=query_text,- collection=CANDIDATES_COLLECTION,- n_results=min(limit, _MAX_OVERFETCH),- )- return [_result(r) for r in rows][:limit]---def find_similar_candidates(- candidate: Candidate,- store: KnowledgeStore,- *,- limit: int = 5,-) -> list[dict[str, Any]]:- """Find candidates similar to ``candidate``, excluding the candidate itself.-- Over-fetches and post-filters out the query candidate (Chroma would- otherwise return it as the closest match to its own profile).- """- if limit <= 0:- return []- query_text = candidate_document(candidate)- if not query_text:- return []- # +1 so dropping self still leaves room for `limit` others.- n = min((limit + 1) * _OVERFETCH, _MAX_OVERFETCH)- rows = store.query(- query_text=query_text, collection=CANDIDATES_COLLECTION, n_results=n- )- out: list[dict[str, Any]] = []- for row in rows:- result = _result(row)- cid = result["candidate_id"]- # Drop the query candidate itself, and any row missing an id (which- # would spuriously match a None query id under ==).- if cid is None or cid == candidate.id:- continue- out.append(result)- if len(out) >= limit:- break- return out---def reindex_all(store: KnowledgeStore, db_path: Any = None) -> int:- """Rebuild the talent index from the store. Returns the count indexed.-- Reconciles fully: every non-archived candidate is upserted (id-keyed, so- updates land in place) and every archived candidate is removed. Because the- talent store only soft-deletes, this covers every row that ever existed.- """- candidates = talent_store.list_candidates(include_archived=True, db_path=db_path)- # `c.id is not None` keeps the three add_documents lists strictly aligned —- # store-loaded rows always carry an int id, but the guard makes that- # explicit rather than relying on it.- active = [- c for c in candidates- if not c.archived and c.id is not None and candidate_document(c)- ]- archived = [c for c in candidates if c.archived]-- if active:- store.add_documents(- texts=[candidate_document(c) for c in active],- metadatas=[_metadata(c) for c in active],- ids=[_doc_id(c.id) for c in active], # type: ignore[arg-type]- collection=CANDIDATES_COLLECTION,- )- for cand in archived:- if cand.id is not None:- store.delete_documents(CANDIDATES_COLLECTION, {"candidate_id": cand.id})- return len(active)diff --git a/packages/core/openexecutive/talent/models.py b/packages/core/openexecutive/talent/models.pydeleted file mode 100644index ade74d4d..00000000--- a/packages/core/openexecutive/talent/models.py+++ /dev/null@@ -1,148 +0,0 @@-"""Pydantic models for the talent / executive-search core.--An ``Engagement`` is one search — a role we're hiring for in *this* company.-A ``Candidate`` is a person being considered for an engagement, moving through a-fixed pipeline. (The vertical is for in-house hiring: searches are run within the-company, not on behalf of external clients.)--These mirror the shape of ``openexecutive.people.models`` — plain Pydantic v2-models with an optional ``id`` (None before insert), ISO-string ``created_at`` /-``updated_at``, and an ``archived`` soft-delete flag.-"""-from __future__ import annotations--from enum import StrEnum--from pydantic import BaseModel, Field---class EngagementStatus(StrEnum):- """Lifecycle of one search engagement."""-- OPEN = "open"- ON_HOLD = "on_hold"- FILLED = "filled"- CANCELLED = "cancelled"---class CandidateStage(StrEnum):- """Pipeline stage of a candidate within an engagement.-- The order here is the intended forward progression; ``REJECTED`` is a- terminal off-ramp reachable from any stage. ``PLACED`` is the terminal- success state (and should coincide with the engagement moving to- ``FILLED``).- """-- LEAD = "lead"- SCREENED = "screened"- INTERVIEWED = "interviewed"- OFFER = "offer"- PLACED = "placed"- REJECTED = "rejected"---class OfferStatus(StrEnum):- """Lifecycle of an offer to a candidate.-- ``DRAFT`` → ``PENDING_APPROVAL`` → ``EXTENDED`` is the forward path;- ``ACCEPTED`` / ``DECLINED`` / ``EXPIRED`` / ``RESCINDED`` are terminal.- The ``pending_approval → extended`` transition is an explicit follow-up- action (the ``extend_offer`` tool/route), never an automatic side effect- of an approval resolution — workflow runs that pause on a human gate do- not auto-resume (generator resume is deferred upstream).- """-- DRAFT = "draft"- PENDING_APPROVAL = "pending_approval"- EXTENDED = "extended"- ACCEPTED = "accepted"- DECLINED = "declined"- EXPIRED = "expired"- RESCINDED = "rescinded"---OPEN_OFFER_STATUSES: frozenset[OfferStatus] = frozenset(- {OfferStatus.DRAFT, OfferStatus.PENDING_APPROVAL, OfferStatus.EXTENDED}-)-TERMINAL_OFFER_STATUSES: frozenset[OfferStatus] = frozenset(- {OfferStatus.ACCEPTED, OfferStatus.DECLINED, OfferStatus.EXPIRED, OfferStatus.RESCINDED}-)---class Engagement(BaseModel):- """One search — a role we're hiring for in this company.-- ``department`` is an optional free-text in-house grouping (e.g. "Drilling");- it is a plain label, not a FK to the departments entity. ``comp_band`` and- ``location`` are free text — Phase 1 keeps them unstructured, matching how- ``people`` started.- """-- id: int | None = None- role_title: str- department: str = ""- status: EngagementStatus = EngagementStatus.OPEN- location: str = ""- comp_band: str = ""- must_haves: str = ""- description: str = ""- archived: bool = False- created_at: str = ""- updated_at: str = ""---class Candidate(BaseModel):- """A person being considered for an engagement.-- ``engagement_id`` is a required FK — a candidate exists in the context of a- specific search. ``fit_score`` (0-100) and ``screening_summary`` are- populated by the ``candidate_screen`` workflow; they stay at their defaults- (``None`` / "") until a screen runs.- """-- id: int | None = None- engagement_id: int- full_name: str- current_title: str = ""- current_company: str = ""- location: str = ""- email: str | None = None- linkedin_url: str | None = None- source: str = ""- stage: CandidateStage = CandidateStage.LEAD- fit_score: int | None = Field(default=None, ge=0, le=100)- screening_summary: str = ""- notes: str = ""- archived: bool = False- created_at: str = ""- updated_at: str = ""---class Offer(BaseModel):- """An offer to a candidate on an engagement.-- A candidate has at most one *open* offer (draft / pending_approval /- extended) at a time — terminal offers stay as history. ``package_md`` is- the full offer-package artifact persisted by the ``offer_approval``- workflow so the UI can render it after the run pauses on the approval- gate. ``expires_at`` is set at extend time (not draft time); expiry never- auto-flips the status — only ``record_offer_decision`` does.- """-- id: int | None = None- candidate_id: int- engagement_id: int- status: OfferStatus = OfferStatus.DRAFT- comp_summary: str = ""- package_md: str = ""- note: str = ""- expires_at: str | None = None- extended_at: str = ""- decided_at: str = ""- approval_run_id: str = ""- approved_by_person_id: int | None = None- nudge_action_ids: list[int] = Field(default_factory=list)- archived: bool = False- created_at: str = ""- updated_at: str = ""diff --git a/packages/core/openexecutive/talent/offers.py b/packages/core/openexecutive/talent/offers.pydeleted file mode 100644index 7d42f5ed..00000000--- a/packages/core/openexecutive/talent/offers.py+++ /dev/null@@ -1,383 +0,0 @@-"""Offer lifecycle actions shared by the chat tools and the /offers routes.--The ``offer_approval`` workflow drafts the package and pauses on a-``WaitForHumanEvent`` gate (HIRING_SIGNOFF approver). Paused runs never-auto-resume (generator resume is deferred upstream), so the-``pending_approval → extended`` transition is an explicit follow-up action:-:func:`extend_offer` consults the recorded gate resolution and performs the-transition. Centralizing it here — like ``talent.reminders`` centralizes the-recipient logic — means the chat tool and the HTTP route can't drift on the-approval/expiry semantics.--Expiry posture: :func:`extend_offer` schedules reminder nudges to the-*principal* (T−3d, T−1d, T+12h); a nudge never flips the offer's status —-only :func:`record_offer_decision` does, on the principal's say-so.-"""-from __future__ import annotations--import json-import logging-from dataclasses import dataclass, field-from datetime import UTC, datetime, timedelta-from typing import Any, Literal--from openexecutive.talent import store as talent_store-from openexecutive.talent.models import (- CandidateStage,- EngagementStatus,- Offer,- OfferStatus,-)-from openexecutive.talent.reminders import resolve_reminder_context, schedule_reminder--logger = logging.getLogger(__name__)--ApprovalState = Literal["approved", "rejected", "pending", "none"]--# How far ahead of expiry the principal gets nudged, plus one past-expiry-# nudge so an offer can't silently sit expired with no decision recorded.-_NUDGE_OFFSETS: list[tuple[timedelta, str]] = [- (timedelta(days=-3), "expires in 3 days"),- (timedelta(days=-1), "expires tomorrow"),- (timedelta(hours=12), "passed its expiry 12 hours ago"),-]--# How many recent offer_approval runs to scan PER STATUS when matching a gate-# to an offer. Bounded so the lookup stays O(small) on long-lived installs.-_APPROVAL_SCAN_LIMIT = 200--# Only these run statuses can carry a gate worth matching: a paused gate, a-# recorded resolution, or a timeout. Scanning per-status keeps failed/running-# runs (which have no usable state) from eating scan-window slots and pushing-# a recorded rejection out of reach.-_GATE_RUN_STATUSES = ("awaiting_human", "resolved", "timed_out")--_CONTEXT_PREFIX = "offer_id="---class OfferActionError(Exception):- """A domain failure performing an offer action.-- ``code`` is machine-readable so the HTTP route can map it to a status- code and the chat tool can surface it verbatim:- ``not_found`` / ``bad_status`` / ``bad_expiry`` / ``approval_rejected``- / ``bad_transition``.- """-- def __init__(self, code: str, message: str) -> None:- super().__init__(message)- self.code = code- self.message = message---@dataclass-class OfferActionResult:- """Outcome of an extend/decide action: the reloaded offer plus metadata."""-- offer: Offer- approval_state: ApprovalState = "none"- nudge_action_ids: list[int] = field(default_factory=list)- cancelled_nudges: int = 0- side_effects: list[str] = field(default_factory=list)- warnings: list[str] = field(default_factory=list)---def gate_context_summary(offer: Offer, candidate_name: str, role_title: str) -> str:- """The machine-greppable context_summary the offer_approval gate carries.-- The ``offer_id=<n>`` prefix is what :func:`find_offer_approval` matches- on — keep the prefix stable.- """- return (- f"{_CONTEXT_PREFIX}{offer.id} — offer approval for {candidate_name} "- f"({role_title})"- )---def find_offer_approval(offer_id: int) -> dict[str, Any] | None:- """Find the newest offer_approval gate run for this offer, if any.-- Matches the ``offer_id=<n>`` prefix embedded in the gate's- ``context_summary`` (serialized into ``state_json``). Returns- ``{run_id, status, decision, person_id}`` where ``decision`` is the- parsed approve/reject/defer (or "" when unresolved), or None when no- gate run references this offer.- """- from openexecutive.workflows import persistence-- runs: list[dict[str, Any]] = []- for run_status in _GATE_RUN_STATUSES:- runs.extend(- persistence.list_runs(- workflow_name="offer_approval",- status=run_status,- limit=_APPROVAL_SCAN_LIMIT,- )- )- runs.sort(key=lambda r: str(r.get("updated_at", "")), reverse=True)- for run in runs: # newest-updated first- full = persistence.get_run(run["run_id"])- if full is None:- continue- state_raw = full.get("state_json")- if not state_raw:- continue- try:- state = json.loads(state_raw)- except (ValueError, TypeError):- continue- summary = str(state.get("context_summary", ""))- if not summary.startswith(f"{_CONTEXT_PREFIX}{offer_id} ") and (- summary != f"{_CONTEXT_PREFIX}{offer_id}"- ):- continue- decision = ""- person_id = state.get("person_id")- resolution_raw = full.get("resolution_json")- if resolution_raw:- try:- resolution = json.loads(resolution_raw)- decision = str(resolution.get("parsed_decision", {}).get("decision", ""))- person_id = resolution.get("person_id", person_id)- except (ValueError, TypeError):- pass- return {- "run_id": run["run_id"],- "status": full.get("status", ""),- "decision": decision,- "person_id": person_id,- }- return None---def offer_approval_state(offer_id: int) -> ApprovalState:- """Roll the gate run for this offer up into one approval state.-- ``none`` = no gate run exists; ``pending`` = gate still awaiting (or the- reply parsed to defer, or the run timed out without a decision).- """- found = find_offer_approval(offer_id)- if found is None:- return "none"- if found["decision"] == "approve":- return "approved"- if found["decision"] == "reject":- return "rejected"- return "pending"---def _parse_expiry(- expires_at: str | None, expires_in_days: int, now: datetime-) -> datetime:- if expires_at:- try:- parsed = datetime.fromisoformat(expires_at)- except ValueError as exc:- raise OfferActionError(- "bad_expiry", f"expires_at is not an ISO timestamp: {expires_at!r}"- ) from exc- if parsed.tzinfo is None:- parsed = parsed.replace(tzinfo=UTC)- if parsed <= now:- raise OfferActionError("bad_expiry", "expires_at must be in the future")- return parsed- return now + timedelta(days=expires_in_days)---def _nudge_text(offer: Offer, candidate_name: str, role_title: str, phase: str) -> str:- return (- f"Offer expiry reminder: the offer to {candidate_name} for the "- f"{role_title} role (offer {offer.id}) {phase}. DM the principal so "- f"they can check in with the candidate and either record a decision "- f"(accepted / declined / expired) or re-extend. Do NOT contact the "- f"candidate directly — this is a reminder for the principal."- )---def extend_offer(- offer_id: int,- *,- expires_at: str | None = None,- expires_in_days: int = 7,- note: str | None = None,- has_principal_consent: bool = True,-) -> OfferActionResult:- """Mark an offer extended (the principal sent it) and schedule expiry nudges.-- Consults the recorded approval-gate resolution: a ``reject`` blocks the- extension; an ``approve`` stamps the run/approver onto the offer; pending- or absent sign-off proceeds on the principal's explicit instruction- (``has_principal_consent``, mirroring the authority gate's consent fast- path) with the unrecorded sign-off flagged in ``warnings``.-- OE never sends the offer itself — this records that the principal- extended it and queues the expiry reminders.-- Raises :class:`OfferActionError` on unknown offer, non-extensible status,- bad expiry, or a recorded rejection.- """- offer = talent_store.get_offer(offer_id)- if offer is None or offer.archived:- raise OfferActionError("not_found", f"offer {offer_id} not found")- if offer.status not in (OfferStatus.DRAFT, OfferStatus.PENDING_APPROVAL):- raise OfferActionError(- "bad_status",- f"offer {offer_id} is {offer.status.value}; only draft/pending_approval "- "offers can be extended",- )-- approval = find_offer_approval(offer_id)- approval_state = offer_approval_state(offer_id)- if approval_state == "rejected":- raise OfferActionError(- "approval_rejected",- f"the sign-off for offer {offer_id} was rejected "- f"(run {approval['run_id'] if approval else '?'}); revise the offer "- "or rescind it instead of extending",- )- warnings: list[str] = []- if approval_state in ("pending", "none"):- if not has_principal_consent:- raise OfferActionError(- "approval_pending",- f"offer {offer_id} has no recorded sign-off "- f"(approval state: {approval_state})",- )- warnings.append(- "extended without a recorded HIRING_SIGNOFF approval "- f"(approval state: {approval_state}) — proceeding on the principal's "- "explicit instruction"- )-- now = datetime.now(UTC)- expiry_dt = _parse_expiry(expires_at, expires_in_days, now)-- # Expiry nudges go to the principal. Unreachable principal = extend- # anyway, warn, schedule nothing — the digest still computes- # "expiring soon" straight from expires_at.- nudge_ids: list[int] = []- candidate = talent_store.get_candidate(offer.candidate_id)- candidate_name = candidate.full_name if candidate else f"candidate {offer.candidate_id}"- engagement = talent_store.get_engagement(offer.engagement_id)- role_title = engagement.role_title if engagement else "open"- ctx = resolve_reminder_context(offer.candidate_id)- if isinstance(ctx, str):- warnings.append(f"no expiry reminders scheduled: {ctx}")- else:- for offset, phase in _NUDGE_OFFSETS:- run_at = expiry_dt + offset- if run_at <= now:- continue- nudge_ids.append(- schedule_reminder(- ctx=ctx,- run_at=run_at,- intent_text=_nudge_text(offer, candidate_name, role_title, phase),- )- )-- changed = talent_store.set_offer_status(- offer_id,- OfferStatus.EXTENDED,- expires_at=expiry_dt.isoformat(),- approval_run_id=(approval or {}).get("run_id") if approval_state == "approved" else None,- approved_by_person_id=(- (approval or {}).get("person_id") if approval_state == "approved" else None- ),- nudge_action_ids=nudge_ids,- note=note,- )- if not changed:- # Lost a race (status changed between the read and the write).- _cancel_nudges(nudge_ids)- raise OfferActionError(- "bad_transition", f"offer {offer_id} could not be extended (state changed)"- )-- updated = talent_store.get_offer(offer_id)- assert updated is not None- return OfferActionResult(- offer=updated,- approval_state=approval_state,- nudge_action_ids=nudge_ids,- warnings=warnings,- )---def record_offer_decision(- offer_id: int,- decision: OfferStatus,- *,- note: str | None = None,-) -> OfferActionResult:- """Record the terminal outcome of an offer and clean up its nudges.-- ``accepted`` also moves the candidate to ``placed`` and the engagement to- ``filled`` (documented side effects — PLACED coincides with FILLED).- ``declined`` / ``expired`` / ``rescinded`` leave the candidate's stage- untouched: the principal decides whether they go back to ``interviewed``- or to ``rejected``.-- Raises :class:`OfferActionError` on unknown offer, a non-terminal- ``decision`` value, or an illegal transition.- """- if decision not in (- OfferStatus.ACCEPTED, OfferStatus.DECLINED, OfferStatus.EXPIRED, OfferStatus.RESCINDED- ):- raise OfferActionError(- "bad_transition", f"decision must be terminal, got {decision.value!r}"- )- offer = talent_store.get_offer(offer_id)- if offer is None or offer.archived:- raise OfferActionError("not_found", f"offer {offer_id} not found")-- changed = talent_store.set_offer_status(offer_id, decision, note=note)- if not changed:- raise OfferActionError(- "bad_transition",- f"offer {offer_id} is {offer.status.value}; {decision.value} is not a "- "legal transition from there",- )-- cancelled = _cancel_nudges(offer.nudge_action_ids)-- side_effects: list[str] = []- if decision is OfferStatus.ACCEPTED:- if talent_store.set_candidate_stage(offer.candidate_id, CandidateStage.PLACED):- side_effects.append(f"candidate {offer.candidate_id} moved to placed")- if talent_store.set_engagement_status(offer.engagement_id, EngagementStatus.FILLED):- side_effects.append(f"engagement {offer.engagement_id} marked filled")-- updated = talent_store.get_offer(offer_id)- assert updated is not None- return OfferActionResult(- offer=updated,- cancelled_nudges=cancelled,- side_effects=side_effects,- )---def _cancel_nudges(action_ids: list[int]) -> int:- """Best-effort cancel of pending expiry nudges. Returns how many cancelled."""- from openexecutive.memory.episodic import cancel_scheduled_action-- cancelled = 0- for action_id in action_ids:- try:- if cancel_scheduled_action(action_id) == "cancelled":- cancelled += 1- except Exception: # noqa: BLE001 — nudge cleanup must never block the decision- logger.warning("offers: could not cancel nudge %s", action_id, exc_info=True)- return cancelled---__all__ = [- "ApprovalState",- "OfferActionError",- "OfferActionResult",- "extend_offer",- "find_offer_approval",- "gate_context_summary",- "offer_approval_state",- "record_offer_decision",-]diff --git a/packages/core/openexecutive/talent/reminders.py b/packages/core/openexecutive/talent/reminders.pydeleted file mode 100644index 23dc8ee6..00000000--- a/packages/core/openexecutive/talent/reminders.py+++ /dev/null@@ -1,176 +0,0 @@-"""Shared machinery for talent recruiting-automation workflows.--The Phase 3 workflows (candidate_outreach, interview_coordination,-reference_check) all follow the same draft-and-approve shape: resolve the-candidate + engagement + the principal who will act, then schedule reminders to-the *principal* (never to the candidate or a reference). This module centralizes-that context resolution, principal-channel routing, and reminder scheduling so-the workflows don't each reimplement (and drift on) the safety-critical "who is-the recipient" logic.-"""-from __future__ import annotations--from dataclasses import dataclass-from datetime import datetime--from openexecutive.people.models import Person-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import Candidate, Engagement--# people.channel resolves to slack/discord/telegram/email; scheduled_actions-# rows use slack_dm/discord_dm/telegram/email. Mirror the bridge nudge_engine-# uses (kept local to avoid importing scheduler internals).-_PEOPLE_TO_SCHEDULED_CHANNEL = {- "slack": "slack_dm",- "discord": "discord_dm",- "telegram": "telegram",- "email": "email",-}-_CHANNEL_PRIORITY = ("email", "slack", "discord", "telegram")---def person_channel_raw(person: Person) -> tuple[str, str] | None:- """Resolve a Person's (people_channel, channel_ref) in people vocabulary.-- Honors `preferred_channel`, else falls back through the priority order.- Returns e.g. ``("slack", "U123")`` — the un-mapped channel name that- ``WaitForHumanEvent.channel`` and the inbound resolver expect. Use- :func:`principal_channel` when scheduling a reminder (scheduled_actions- vocabulary, e.g. ``slack_dm``).- """- refs = {- "email": person.email,- "slack": person.slack_user_id,- "discord": person.discord_user_id,- "telegram": person.telegram_chat_id,- }- order: list[str] = []- if person.preferred_channel != "any":- order.append(person.preferred_channel)- order.extend(c for c in _CHANNEL_PRIORITY if c not in order)- for people_channel in order:- ref = refs.get(people_channel)- if ref and people_channel in _PEOPLE_TO_SCHEDULED_CHANNEL:- return people_channel, ref- return None---def principal_channel(person: Person) -> tuple[str, str] | None:- """Resolve a Person's (scheduled_channel, channel_ref), or None.-- Honors `preferred_channel`, else falls back through the priority order, then- maps the people-channel name to the scheduled_actions vocabulary.- """- raw = person_channel_raw(person)- if raw is None:- return None- people_channel, ref = raw- return _PEOPLE_TO_SCHEDULED_CHANNEL[people_channel], ref---def company_name() -> str:- """This company's name from the profile (fallback ``"the company"``).-- In-house hiring: a search is run within this company, so workflow copy- addresses the hiring org by the company's own name rather than an external- client's.- """- from openexecutive.onboarding.profile_builder import load_or_create_profile-- profile = load_or_create_profile()- return profile.name or "the company"---@dataclass-class ReminderContext:- """Everything a talent workflow needs to schedule reminders to the principal."""-- candidate: Candidate- engagement: Engagement- company_name: str- principal: Person- channel: str- channel_ref: str---def resolve_reminder_context(candidate_id: int) -> ReminderContext | str:- """Resolve a candidate into a full reminder context, or return an error string.-- Returns a human-readable error message (str) when the candidate, its- engagement, or a reachable principal can't be resolved — the workflow yields- it as an `error` event and schedules nothing. This is the single place the- recipient (always the principal, never the candidate) is determined.- """- candidate = talent_store.get_candidate(candidate_id)- if candidate is None:- return f"Candidate {candidate_id} not found."- engagement = talent_store.get_engagement(candidate.engagement_id)- if engagement is None:- return f"Engagement {candidate.engagement_id} for this candidate not found."-- from openexecutive.people.store import find_principal_person-- principal = find_principal_person()- if principal is None:- return "No principal configured to receive reminders."- routed = principal_channel(principal)- if routed is None:- return (- f"Principal {principal.full_name} has no reachable channel "- "(email/slack/discord/telegram) for reminders."- )- channel, channel_ref = routed- return ReminderContext(- candidate=candidate,- engagement=engagement,- company_name=company_name(),- principal=principal,- channel=channel,- channel_ref=channel_ref,- )---def artifact_header(- ctx: ReminderContext,- *,- title: str,- disclaimer: str,- meta_lines: list[str] | None = None,-) -> list[str]:- """Shared Markdown header for talent-workflow artifacts.-- Returns the title, role line, any caller-supplied meta lines, the- "reminders to" line, and the draft-and-approve disclaimer — the block every- talent workflow's artifact opens with.- """- lines = [- f"# {title} — {ctx.candidate.full_name}",- "",- f"**Role:** {ctx.engagement.role_title} ({ctx.company_name}) ",- ]- lines.extend(meta_lines or [])- lines += [- f"**Reminders to:** {ctx.principal.full_name}",- "",- f"> {disclaimer}",- "",- ]- return lines---def schedule_reminder(*, ctx: ReminderContext, run_at: datetime, intent_text: str) -> int:- """Queue one reminder to the principal. Returns the scheduled_action id.-- The recipient is fixed to the principal's channel from `ctx` — candidate- contact details never become a `channel_ref`.- """- from openexecutive.memory.episodic import insert_scheduled_action-- return insert_scheduled_action(- run_at=run_at.isoformat(),- channel=ctx.channel,- channel_ref=ctx.channel_ref,- intent_text=intent_text,- assigned_to_person_id=ctx.principal.id,- kind="ad_hoc",- )diff --git a/packages/core/openexecutive/talent/store.py b/packages/core/openexecutive/talent/store.pydeleted file mode 100644index e78706cc..00000000--- a/packages/core/openexecutive/talent/store.py+++ /dev/null@@ -1,711 +0,0 @@-"""SQLite-backed persistence for the talent / executive-search core.--Lives in the same ``episodic_memory.db`` as people / departments / episodic so-there is one place to look. Tables are created idempotently via-``CREATE TABLE IF NOT EXISTS`` — no migration tooling needed.--The ``_resolve_db_path`` pattern lets tests monkeypatch ``DB_PATH`` and have it-take effect at call time, mirroring ``openexecutive.people.store``.-"""-from __future__ import annotations--import json-import logging-import os-import sqlite3-from collections.abc import Generator-from contextlib import contextmanager-from datetime import UTC, datetime-from pathlib import Path--from openexecutive.talent.models import (- OPEN_OFFER_STATUSES,- TERMINAL_OFFER_STATUSES,- Candidate,- CandidateStage,- Engagement,- EngagementStatus,- Offer,- OfferStatus,-)--logger = logging.getLogger(__name__)--DB_PATH = Path(os.environ.get("EPISODIC_DB_PATH", "./episodic_memory.db"))---def _resolve_db_path(db_path: Path | None) -> Path:- """Return caller-supplied path or the current module-level DB_PATH.-- Dynamic resolution allows tests to monkeypatch DB_PATH and have it take- effect at call time rather than at def time.- """- return db_path if db_path is not None else DB_PATH---@contextmanager-def _get_conn(db_path: Path | None = None) -> Generator[sqlite3.Connection, None, None]:- conn = sqlite3.connect(str(_resolve_db_path(db_path)))- conn.row_factory = sqlite3.Row- conn.execute("PRAGMA foreign_keys = ON")- try:- yield conn- conn.commit()- finally:- conn.close()---def _table_exists(conn: sqlite3.Connection, name: str) -> bool:- return conn.execute(- "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)- ).fetchone() is not None---def _now() -> str:- return datetime.now(UTC).isoformat()---# --------------------------------------------------------------------------- #-# Schema-# --------------------------------------------------------------------------- #--def initialize_db(db_path: Path | None = None) -> None:- """Create talent tables idempotently. Safe to call repeatedly.-- One-time reset: the vertical moved from an external-client model (Client →- Engagement → Candidate) to in-house hiring (Engagement → Candidate). There is- no migration tooling, so if the legacy ``clients`` table is present we drop- the three talent tables and rebuild them in the new shape. Only the talent- tables are touched; the rest of ``episodic_memory.db`` is untouched.- """- with _get_conn(db_path) as conn:- if _table_exists(conn, "clients"):- # Legacy external-client schema detected — reset talent tables.- logger.warning(- "talent.store: legacy 'clients' schema found; dropping talent "- "tables (clients/engagements/candidates) for the in-house model"- )- conn.executescript(- "DROP TABLE IF EXISTS candidates;"- "DROP TABLE IF EXISTS engagements;"- "DROP TABLE IF EXISTS clients;"- )- conn.executescript("""- CREATE TABLE IF NOT EXISTS engagements (- id INTEGER PRIMARY KEY AUTOINCREMENT,- role_title TEXT NOT NULL,- department TEXT NOT NULL DEFAULT '',- status TEXT NOT NULL DEFAULT 'open',- location TEXT NOT NULL DEFAULT '',- comp_band TEXT NOT NULL DEFAULT '',- must_haves TEXT NOT NULL DEFAULT '',- description TEXT NOT NULL DEFAULT '',- archived INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL- );- CREATE INDEX IF NOT EXISTS idx_engagements_archived ON engagements(archived);-- CREATE TABLE IF NOT EXISTS candidates (- id INTEGER PRIMARY KEY AUTOINCREMENT,- engagement_id INTEGER NOT NULL,- full_name TEXT NOT NULL,- current_title TEXT NOT NULL DEFAULT '',- current_company TEXT NOT NULL DEFAULT '',- location TEXT NOT NULL DEFAULT '',- email TEXT,- linkedin_url TEXT,- source TEXT NOT NULL DEFAULT '',- stage TEXT NOT NULL DEFAULT 'lead',- fit_score INTEGER,- screening_summary TEXT NOT NULL DEFAULT '',- notes TEXT NOT NULL DEFAULT '',- archived INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- FOREIGN KEY (engagement_id) REFERENCES engagements(id) ON DELETE CASCADE- );- CREATE INDEX IF NOT EXISTS idx_candidates_engagement ON candidates(engagement_id);- CREATE INDEX IF NOT EXISTS idx_candidates_stage ON candidates(stage);- CREATE INDEX IF NOT EXISTS idx_candidates_archived ON candidates(archived);-- CREATE TABLE IF NOT EXISTS offers (- id INTEGER PRIMARY KEY AUTOINCREMENT,- candidate_id INTEGER NOT NULL,- engagement_id INTEGER NOT NULL,- status TEXT NOT NULL DEFAULT 'draft',- comp_summary TEXT NOT NULL DEFAULT '',- package_md TEXT NOT NULL DEFAULT '',- note TEXT NOT NULL DEFAULT '',- expires_at TEXT,- extended_at TEXT NOT NULL DEFAULT '',- decided_at TEXT NOT NULL DEFAULT '',- approval_run_id TEXT NOT NULL DEFAULT '',- approved_by_person_id INTEGER,- nudge_action_ids_json TEXT NOT NULL DEFAULT '[]',- archived INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- FOREIGN KEY (candidate_id) REFERENCES candidates(id) ON DELETE CASCADE,- FOREIGN KEY (engagement_id) REFERENCES engagements(id) ON DELETE CASCADE- );- CREATE INDEX IF NOT EXISTS idx_offers_candidate ON offers(candidate_id);- CREATE INDEX IF NOT EXISTS idx_offers_status ON offers(status);- CREATE INDEX IF NOT EXISTS idx_offers_archived ON offers(archived);- -- DB-level backstop for the one-open-offer-per-candidate invariant:- -- the SELECT guard in create_offer has a check-then-insert window,- -- so concurrent creates settle here instead of producing two open- -- offers.- CREATE UNIQUE INDEX IF NOT EXISTS idx_offers_one_open- ON offers(candidate_id)- WHERE archived = 0- AND status IN ('draft', 'pending_approval', 'extended');- """)---# --------------------------------------------------------------------------- #-# Row mapping helpers-# --------------------------------------------------------------------------- #--def _row_to_engagement(row: sqlite3.Row) -> Engagement:- return Engagement(- id=int(row["id"]),- role_title=row["role_title"],- department=row["department"],- status=EngagementStatus(row["status"]),- location=row["location"],- comp_band=row["comp_band"],- must_haves=row["must_haves"],- description=row["description"],- archived=bool(row["archived"]),- created_at=row["created_at"],- updated_at=row["updated_at"],- )---def _row_to_candidate(row: sqlite3.Row) -> Candidate:- return Candidate(- id=int(row["id"]),- engagement_id=int(row["engagement_id"]),- full_name=row["full_name"],- current_title=row["current_title"],- current_company=row["current_company"],- location=row["location"],- email=row["email"],- linkedin_url=row["linkedin_url"],- source=row["source"],- stage=CandidateStage(row["stage"]),- fit_score=row["fit_score"],- screening_summary=row["screening_summary"],- notes=row["notes"],- archived=bool(row["archived"]),- created_at=row["created_at"],- updated_at=row["updated_at"],- )---# --------------------------------------------------------------------------- #-# Engagement CRUD-# --------------------------------------------------------------------------- #--def upsert_engagement(- *,- role_title: str,- department: str = "",- status: EngagementStatus = EngagementStatus.OPEN,- location: str = "",- comp_band: str = "",- must_haves: str = "",- description: str = "",- engagement_id: int | None = None,- db_path: Path | None = None,-) -> int:- """Insert or update an engagement row. Returns the engagement_id."""- now = _now()- with _get_conn(db_path) as conn:- if engagement_id is not None and engagement_id > 0:- conn.execute(- "UPDATE engagements SET role_title=?, department=?, status=?, location=?,"- " comp_band=?, must_haves=?, description=?, updated_at=? WHERE id=?",- (- role_title, department, status.value, location, comp_band,- must_haves, description, now, engagement_id,- ),- )- return engagement_id- cursor = conn.execute(- "INSERT INTO engagements (role_title, department, status, location, comp_band,"- " must_haves, description, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?)",- (- role_title, department, status.value, location, comp_band,- must_haves, description, now, now,- ),- )- return int(cursor.lastrowid or 0)---def get_engagement(engagement_id: int, db_path: Path | None = None) -> Engagement | None:- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "engagements"):- return None- row = conn.execute(- "SELECT * FROM engagements WHERE id = ?", (engagement_id,)- ).fetchone()- return _row_to_engagement(row) if row else None---def list_engagements(- include_archived: bool = False,- db_path: Path | None = None,-) -> list[Engagement]:- """List engagements (searches), newest id last."""- if not _resolve_db_path(db_path).exists():- return []- with _get_conn(db_path) as conn:- if not _table_exists(conn, "engagements"):- return []- where = "" if include_archived else "WHERE archived = 0"- rows = conn.execute(- f"SELECT * FROM engagements {where} ORDER BY id"- ).fetchall()- return [_row_to_engagement(r) for r in rows]---def set_engagement_status(- engagement_id: int, status: EngagementStatus, db_path: Path | None = None-) -> bool:- """Update an engagement's status. Returns True if a row was modified."""- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE engagements SET status = ?, updated_at = ? WHERE id = ?",- (status.value, _now(), engagement_id),- )- return cursor.rowcount > 0---def archive_engagement(engagement_id: int, db_path: Path | None = None) -> bool:- """Soft-delete an engagement. Returns True if a row was found and archived."""- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE engagements SET archived = 1, updated_at = ? WHERE id = ? AND archived = 0",- (_now(), engagement_id),- )- return cursor.rowcount > 0---# --------------------------------------------------------------------------- #-# Candidate CRUD-# --------------------------------------------------------------------------- #--def upsert_candidate(- *,- engagement_id: int,- full_name: str,- current_title: str = "",- current_company: str = "",- location: str = "",- email: str | None = None,- linkedin_url: str | None = None,- source: str = "",- stage: CandidateStage = CandidateStage.LEAD,- notes: str = "",- candidate_id: int | None = None,- db_path: Path | None = None,-) -> int:- """Insert or update a candidate row. Returns the candidate_id.-- ``fit_score`` and ``screening_summary`` are intentionally NOT settable- here — they are owned by ``record_screening`` so a manual edit can never- silently clobber a screen (or vice versa).- """- now = _now()- with _get_conn(db_path) as conn:- if candidate_id is not None and candidate_id > 0:- conn.execute(- "UPDATE candidates SET engagement_id=?, full_name=?, current_title=?,"- " current_company=?, location=?, email=?, linkedin_url=?, source=?,"- " stage=?, notes=?, updated_at=? WHERE id=?",- (- engagement_id, full_name, current_title, current_company, location,- email, linkedin_url, source, stage.value, notes, now, candidate_id,- ),- )- return candidate_id- cursor = conn.execute(- "INSERT INTO candidates (engagement_id, full_name, current_title,"- " current_company, location, email, linkedin_url, source, stage, notes,"- " created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",- (- engagement_id, full_name, current_title, current_company, location,- email, linkedin_url, source, stage.value, notes, now, now,- ),- )- return int(cursor.lastrowid or 0)---def get_candidate(candidate_id: int, db_path: Path | None = None) -> Candidate | None:- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "candidates"):- return None- row = conn.execute(- "SELECT * FROM candidates WHERE id = ?", (candidate_id,)- ).fetchone()- return _row_to_candidate(row) if row else None---def list_candidates(- engagement_id: int | None = None,- stage: CandidateStage | None = None,- include_archived: bool = False,- db_path: Path | None = None,-) -> list[Candidate]:- """List candidates, optionally filtered by engagement and/or stage."""- if not _resolve_db_path(db_path).exists():- return []- with _get_conn(db_path) as conn:- if not _table_exists(conn, "candidates"):- return []- clauses: list[str] = []- params: list[object] = []- if not include_archived:- clauses.append("archived = 0")- if engagement_id is not None:- clauses.append("engagement_id = ?")- params.append(engagement_id)- if stage is not None:- clauses.append("stage = ?")- params.append(stage.value)- where = f"WHERE {' AND '.join(clauses)}" if clauses else ""- rows = conn.execute(- f"SELECT * FROM candidates {where} ORDER BY id", params- ).fetchall()- return [_row_to_candidate(r) for r in rows]---def set_candidate_stage(- candidate_id: int, stage: CandidateStage, db_path: Path | None = None-) -> bool:- """Advance (or move) a candidate to a pipeline stage. Returns True on change."""- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE candidates SET stage = ?, updated_at = ? WHERE id = ?",- (stage.value, _now(), candidate_id),- )- return cursor.rowcount > 0---def record_screening(- candidate_id: int,- *,- fit_score: int,- summary: str,- advance_stage: bool = True,- db_path: Path | None = None,-) -> bool:- """Persist a screening result for a candidate.-- Stores ``fit_score`` (0-100) and the ``screening_summary``. When- ``advance_stage`` is True (the default) and the candidate is still a raw- ``lead``, moves them to ``screened`` — a screen that leaves the candidate a- lead would be a no-op pipeline-wise. A candidate already past ``lead`` keeps- their stage (re-screening shouldn't drag them backwards or skip them- forward). Returns True if a row was modified.- """- if not 0 <= fit_score <= 100:- raise ValueError(f"fit_score must be 0-100, got {fit_score}")- with _get_conn(db_path) as conn:- row = conn.execute(- "SELECT stage, archived FROM candidates WHERE id = ?", (candidate_id,)- ).fetchone()- # Skip archived candidates: a long-running screen must not write a- # score onto someone soft-deleted between fetch and persist.- if row is None or row["archived"]:- return False- new_stage = row["stage"]- if advance_stage and row["stage"] == CandidateStage.LEAD.value:- new_stage = CandidateStage.SCREENED.value- cursor = conn.execute(- "UPDATE candidates SET fit_score = ?, screening_summary = ?, stage = ?,"- " updated_at = ? WHERE id = ?",- (fit_score, summary, new_stage, _now(), candidate_id),- )- return cursor.rowcount > 0---def archive_candidate(candidate_id: int, db_path: Path | None = None) -> bool:- """Soft-delete a candidate. Returns True if a row was found and archived."""- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE candidates SET archived = 1, updated_at = ? WHERE id = ? AND archived = 0",- (_now(), candidate_id),- )- return cursor.rowcount > 0---# --------------------------------------------------------------------------- #-# Offers-# --------------------------------------------------------------------------- #--# Legal status transitions. Terminal statuses have no outgoing edges — a-# decided offer is history; re-offering means creating a new Offer row.-_OFFER_TRANSITIONS: dict[OfferStatus, frozenset[OfferStatus]] = {- OfferStatus.DRAFT: frozenset(- {OfferStatus.PENDING_APPROVAL, OfferStatus.EXTENDED, OfferStatus.RESCINDED}- ),- OfferStatus.PENDING_APPROVAL: frozenset(- {OfferStatus.DRAFT, OfferStatus.EXTENDED, OfferStatus.RESCINDED}- ),- OfferStatus.EXTENDED: frozenset(- {OfferStatus.ACCEPTED, OfferStatus.DECLINED, OfferStatus.EXPIRED, OfferStatus.RESCINDED}- ),- OfferStatus.ACCEPTED: frozenset(),- OfferStatus.DECLINED: frozenset(),- OfferStatus.EXPIRED: frozenset(),- OfferStatus.RESCINDED: frozenset(),-}---def _row_to_offer(row: sqlite3.Row) -> Offer:- try:- nudge_ids = [int(x) for x in json.loads(row["nudge_action_ids_json"])]- except (ValueError, TypeError):- nudge_ids = []- return Offer(- id=int(row["id"]),- candidate_id=int(row["candidate_id"]),- engagement_id=int(row["engagement_id"]),- status=OfferStatus(row["status"]),- comp_summary=row["comp_summary"],- package_md=row["package_md"],- note=row["note"],- expires_at=row["expires_at"],- extended_at=row["extended_at"],- decided_at=row["decided_at"],- approval_run_id=row["approval_run_id"],- approved_by_person_id=row["approved_by_person_id"],- nudge_action_ids=nudge_ids,- archived=bool(row["archived"]),- created_at=row["created_at"],- updated_at=row["updated_at"],- )---def create_offer(- *,- candidate_id: int,- engagement_id: int,- comp_summary: str = "",- package_md: str = "",- note: str = "",- status: OfferStatus = OfferStatus.DRAFT,- db_path: Path | None = None,-) -> int:- """Insert an offer row. Returns the offer_id.-- Raises ``ValueError`` if the candidate already has an open offer- (draft / pending_approval / extended) — one live offer per candidate —- or if ``status`` is not an allowed insert state (only ``DRAFT`` and- ``PENDING_APPROVAL``; an offer can't be born extended or decided).- """- if status not in (OfferStatus.DRAFT, OfferStatus.PENDING_APPROVAL):- raise ValueError(f"offers can only be created as draft/pending_approval, got {status.value}")- now = _now()- with _get_conn(db_path) as conn:- open_values = tuple(s.value for s in OPEN_OFFER_STATUSES)- placeholders = ",".join("?" for _ in open_values)- existing = conn.execute(- f"SELECT id FROM offers WHERE candidate_id = ? AND archived = 0"- f" AND status IN ({placeholders})",- (candidate_id, *open_values),- ).fetchone()- if existing is not None:- raise ValueError(- f"candidate {candidate_id} already has an open offer (id {existing['id']})"- )- try:- cursor = conn.execute(- "INSERT INTO offers (candidate_id, engagement_id, status, comp_summary,"- " package_md, note, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",- (candidate_id, engagement_id, status.value, comp_summary,- package_md, note, now, now),- )- except sqlite3.IntegrityError as exc:- # Concurrent create slipped past the SELECT guard and hit the- # idx_offers_one_open partial unique index.- raise ValueError(- f"candidate {candidate_id} already has an open offer"- ) from exc- return int(cursor.lastrowid or 0)---def get_offer(offer_id: int, db_path: Path | None = None) -> Offer | None:- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "offers"):- return None- row = conn.execute("SELECT * FROM offers WHERE id = ?", (offer_id,)).fetchone()- return _row_to_offer(row) if row else None---def get_open_offer_for_candidate(- candidate_id: int, db_path: Path | None = None-) -> Offer | None:- """Return the candidate's open offer (draft/pending_approval/extended), or None."""- if not _resolve_db_path(db_path).exists():- return None- with _get_conn(db_path) as conn:- if not _table_exists(conn, "offers"):- return None- open_values = tuple(s.value for s in OPEN_OFFER_STATUSES)- placeholders = ",".join("?" for _ in open_values)- row = conn.execute(- f"SELECT * FROM offers WHERE candidate_id = ? AND archived = 0"- f" AND status IN ({placeholders}) ORDER BY id DESC LIMIT 1",- (candidate_id, *open_values),- ).fetchone()- return _row_to_offer(row) if row else None---def list_offers(- candidate_id: int | None = None,- engagement_id: int | None = None,- status: OfferStatus | None = None,- include_archived: bool = False,- db_path: Path | None = None,-) -> list[Offer]:- """List offers, optionally filtered by candidate, engagement, and/or status."""- if not _resolve_db_path(db_path).exists():- return []- with _get_conn(db_path) as conn:- if not _table_exists(conn, "offers"):- return []- clauses: list[str] = []- params: list[object] = []- if not include_archived:- clauses.append("archived = 0")- if candidate_id is not None:- clauses.append("candidate_id = ?")- params.append(candidate_id)- if engagement_id is not None:- clauses.append("engagement_id = ?")- params.append(engagement_id)- if status is not None:- clauses.append("status = ?")- params.append(status.value)- where = f"WHERE {' AND '.join(clauses)}" if clauses else ""- rows = conn.execute(f"SELECT * FROM offers {where} ORDER BY id", params).fetchall()- return [_row_to_offer(r) for r in rows]---def update_offer_terms(- offer_id: int,- *,- comp_summary: str | None = None,- package_md: str | None = None,- note: str | None = None,- db_path: Path | None = None,-) -> bool:- """Update an offer's terms while it is still pre-extension.-- Only ``draft`` / ``pending_approval`` offers are editable — once an offer- is extended (or decided) its terms are the record of what went out.- Returns True if a row was modified.- """- fields: list[str] = []- params: list[object] = []- if comp_summary is not None:- fields.append("comp_summary = ?")- params.append(comp_summary)- if package_md is not None:- fields.append("package_md = ?")- params.append(package_md)- if note is not None:- fields.append("note = ?")- params.append(note)- if not fields:- return False- with _get_conn(db_path) as conn:- cursor = conn.execute(- f"UPDATE offers SET {', '.join(fields)}, updated_at = ?"- " WHERE id = ? AND archived = 0 AND status IN (?, ?)",- (*params, _now(), offer_id,- OfferStatus.DRAFT.value, OfferStatus.PENDING_APPROVAL.value),- )- return cursor.rowcount > 0---def set_offer_status(- offer_id: int,- status: OfferStatus,- *,- expires_at: str | None = None,- approval_run_id: str | None = None,- approved_by_person_id: int | None = None,- nudge_action_ids: list[int] | None = None,- note: str | None = None,- db_path: Path | None = None,-) -> bool:- """Transition an offer to a new status, enforcing the lifecycle map.-- Stamps ``extended_at`` on → ``extended`` and ``decided_at`` on → any- terminal status. Returns False (and logs) on an unknown offer or an- illegal transition rather than raising — keeps tool/route error handling- uniform with the rest of the store's boolean writes.- """- with _get_conn(db_path) as conn:- row = conn.execute(- "SELECT status, archived FROM offers WHERE id = ?", (offer_id,)- ).fetchone()- if row is None or row["archived"]:- return False- current = OfferStatus(row["status"])- if status not in _OFFER_TRANSITIONS[current]:- logger.warning(- "talent.store: illegal offer transition %s -> %s (offer %s)",- current.value, status.value, offer_id,- )- return False- now = _now()- fields = ["status = ?", "updated_at = ?"]- params: list[object] = [status.value, now]- if status is OfferStatus.EXTENDED:- fields.append("extended_at = ?")- params.append(now)- if status in TERMINAL_OFFER_STATUSES:- fields.append("decided_at = ?")- params.append(now)- if expires_at is not None:- fields.append("expires_at = ?")- params.append(expires_at)- if approval_run_id is not None:- fields.append("approval_run_id = ?")- params.append(approval_run_id)- if approved_by_person_id is not None:- fields.append("approved_by_person_id = ?")- params.append(approved_by_person_id)- if nudge_action_ids is not None:- fields.append("nudge_action_ids_json = ?")- params.append(json.dumps(nudge_action_ids))- if note is not None:- fields.append("note = ?")- params.append(note)- params.append(offer_id)- cursor = conn.execute(- f"UPDATE offers SET {', '.join(fields)} WHERE id = ?", params- )- return cursor.rowcount > 0---def archive_offer(offer_id: int, db_path: Path | None = None) -> bool:- """Soft-delete an offer. Returns True if a row was found and archived."""- with _get_conn(db_path) as conn:- cursor = conn.execute(- "UPDATE offers SET archived = 1, updated_at = ? WHERE id = ? AND archived = 0",- (_now(), offer_id),- )- return cursor.rowcount > 0diff --git a/packages/core/openexecutive/workflows/__init__.py b/packages/core/openexecutive/workflows/__init__.pyindex 1afb6ca3..26bcc691 100644--- a/packages/core/openexecutive/workflows/__init__.py+++ b/packages/core/openexecutive/workflows/__init__.py@@ -22,8 +22,6 @@ from openexecutive.workflows.base import (WorkflowStepDef,)from openexecutive.workflows.board_prep import BoardPrepWorkflow-from openexecutive.workflows.candidate_outreach import CandidateOutreachWorkflow-from openexecutive.workflows.candidate_screen import CandidateScreenWorkflowfrom openexecutive.workflows.churn_deep_dive import ChurnDeepDiveWorkflowfrom openexecutive.workflows.comp_refresh import CompRefreshWorkflowfrom openexecutive.workflows.competitive_teardown import CompetitiveTeardownWorkflow@@ -38,28 +36,21 @@ from openexecutive.workflows.executive_reflection import ExecutiveReflectionWorkfrom openexecutive.workflows.executive_research import ExecutiveResearchWorkflowfrom openexecutive.workflows.fundraising_prep import FundraisingPrepWorkflowfrom openexecutive.workflows.gtm_launch import GTMLaunchWorkflow-from openexecutive.workflows.interview_coordination import InterviewCoordinationWorkflowfrom openexecutive.workflows.investor_update import InvestorUpdateWorkflowfrom openexecutive.workflows.ma_evaluation import MAEvaluationWorkflowfrom openexecutive.workflows.mbr import MBRWorkflowfrom openexecutive.workflows.morning_brief import MorningBriefWorkflow-from openexecutive.workflows.new_hire_onboarding import NewHireOnboardingWorkflow-from openexecutive.workflows.offer_approval import OfferApprovalWorkflowfrom openexecutive.workflows.org_design import OrgDesignWorkflowfrom openexecutive.workflows.performance_review import PerformanceReviewWorkflowfrom openexecutive.workflows.pricing_review import PricingReviewWorkflowfrom openexecutive.workflows.product_strategy import ProductStrategyWorkflowfrom openexecutive.workflows.quarterly_plan import QuarterlyPlanWorkflow-from openexecutive.workflows.reference_check import ReferenceCheckWorkflowfrom openexecutive.workflows.risk_register import RiskRegisterWorkflow-from openexecutive.workflows.role_onboarding import RoleOnboardingWorkflowWORKFLOW_REGISTRY: dict[str, Workflow] = {"annual_plan": AnnualPlanWorkflow(),"department_check_in": DepartmentCheckInWorkflow(),"board_prep": BoardPrepWorkflow(),- "candidate_outreach": CandidateOutreachWorkflow(),- "candidate_screen": CandidateScreenWorkflow(),"churn_deep_dive": ChurnDeepDiveWorkflow(),"comp_refresh": CompRefreshWorkflow(),"competitive_teardown": CompetitiveTeardownWorkflow(),@@ -75,31 +66,22 @@ WORKFLOW_REGISTRY: dict[str, Workflow] = {# coordination decisions. Fires ~30 minutes before the morning# brief, can invoke real tools (DMs, broadcasts, follow-ups)."executive_reflection": ExecutiveReflectionWorkflow(),+ # `exec_search_brief` is an ADVISORY deliverable (a hiring brief /+ # scorecard from the CHRO), not part of the removed talent pipeline —+ # it never touched the candidate/engagement tables."exec_search_brief": ExecSearchBriefWorkflow(),"fundraising_prep": FundraisingPrepWorkflow(),"gtm_launch": GTMLaunchWorkflow(),- "interview_coordination": InterviewCoordinationWorkflow(),"engagement_value_report": EngagementValueReportWorkflow(),"investor_update": InvestorUpdateWorkflow(),"ma_evaluation": MAEvaluationWorkflow(),"mbr": MBRWorkflow(),- # `offer_approval` is the first BUILT-IN workflow to pause on a- # WaitForHumanEvent gate (previously only dynamic workflows did): it- # drafts the offer package, DMs the HIRING_SIGNOFF approver, and pauses.- # Paused runs never auto-resume — the pending_approval → extended- # transition is the explicit `extend_offer` tool/route, which consults- # the recorded resolution. `new_hire_onboarding` is the placed → Person- # handoff (roster record + 30/60/90 plan + milestone reminders).- "offer_approval": OfferApprovalWorkflow(),- "new_hire_onboarding": NewHireOnboardingWorkflow(),"org_design": OrgDesignWorkflow(),"performance_review": PerformanceReviewWorkflow(),"pricing_review": PricingReviewWorkflow(),"product_strategy": ProductStrategyWorkflow(),"quarterly_plan": QuarterlyPlanWorkflow(),- "reference_check": ReferenceCheckWorkflow(),"risk_register": RiskRegisterWorkflow(),- "role_onboarding": RoleOnboardingWorkflow(),# `executive_research` drives the 7-specialist council in research# mode with web_search, then runs the Executive's tool-use loop# (same shape as `executive_reflection`) so findings get routeddiff --git a/packages/core/openexecutive/workflows/candidate_outreach.py b/packages/core/openexecutive/workflows/candidate_outreach.pydeleted file mode 100644index 68473af1..00000000--- a/packages/core/openexecutive/workflows/candidate_outreach.py+++ /dev/null@@ -1,275 +0,0 @@-"""Candidate outreach sequence workflow — Phase 3 recruiting automation.--Drafts a personalized first-touch plus N scheduled follow-ups for a candidate on-an engagement (via the talent specialist) and schedules each touch as a-*reminder to the principal* — never a direct message to the candidate.--Posture: draft-and-approve. OE never emails candidates. Each scheduled reminder-is the human checkpoint: when it fires, the Executive DMs the principal the-ready-to-send draft for review and manual sending. This sidesteps the roster--gated outbound model (candidates are not `Person` records) and the deferred-generator-resume limitation (a `wait_for_human` gate would pause and never-schedule), while keeping a human in the loop on every touch.--Context resolution, principal-channel routing, and reminder scheduling are-shared with the other talent workflows via ``openexecutive.talent.reminders``.-"""-from __future__ import annotations--from collections.abc import AsyncIterator-from datetime import UTC, datetime, timedelta-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.talent.models import Candidate, Engagement-from openexecutive.talent.reminders import (- ReminderContext,- artifact_header,- resolve_reminder_context,- schedule_reminder,-)-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)--_SPECIALIST = "talent"-_MAX_FOLLOW_UPS = 5---class CandidateOutreachInput(BaseModel):- """Inputs for the Candidate Outreach Sequence workflow."""-- candidate_id: int = Field(..., description="Candidate to build the outreach sequence for.")- follow_up_count: int = Field(- default=2, ge=0, le=_MAX_FOLLOW_UPS,- description="Number of follow-up touches after the first (0-5).",- )- follow_up_interval_days: int = Field(- default=3, ge=1, le=30,- description="Days between touches.",- )- angle: str = Field(- default="",- description="Optional emphasis for the outreach (e.g. 'lead with the platform rebuild').",- max_length=2000,- )---class CandidateOutreachWorkflow(Workflow):- name = "candidate_outreach"- title = "Candidate Outreach Sequence"- description = (- "Drafts a personalized first-touch plus scheduled follow-ups for a "- "candidate and schedules each as a reminder to you (the principal) to "- "review and send. Never contacts the candidate directly."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 3-- def input_model(self) -> type[BaseModel]:- return CandidateOutreachInput-- def sample_inputs(self) -> dict[str, Any]:- return {- "candidate_id": 1,- "follow_up_count": 2,- "follow_up_interval_days": 3,- "angle": "lead with the year-one mandate and the scope of the role",- }-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(- id="load",- title="Load candidate & recipient",- description="Fetch the candidate, engagement, and the principal who'll send.",- ),- WorkflowStepDef(- id="draft",- title="Draft the sequence",- description="First-touch + follow-ups, personalized to the role.",- ),- WorkflowStepDef(- id="schedule",- title="Schedule reminders",- description="Queue a review-and-send reminder to you for each touch.",- ),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, CandidateOutreachInput)-- yield WorkflowEvent(- type="step_start", step_id="load", step_title="Load candidate & recipient"- )- ctx = resolve_reminder_context(inputs.candidate_id)- if isinstance(ctx, str):- yield WorkflowEvent(type="error", message=ctx)- return- yield WorkflowEvent(- type="step_done",- step_id="load",- summary=(- f"{ctx.candidate.full_name} for {ctx.engagement.role_title} "- f"({ctx.company_name}); reminders → {ctx.principal.full_name} via {ctx.channel}."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="draft", step_title="Draft the sequence"- )- rag = retrieve(- query=f"executive outreach message {ctx.engagement.role_title} {ctx.engagement.must_haves}",- specialist_name=_SPECIALIST,- n_builtin=3,- n_company=2,- store=store,- )- touches: list[tuple[str, str]] = []- first = await route_to_specialist(- specialist_name=_SPECIALIST,- query=_first_touch_prompt(ctx.engagement, ctx.candidate, ctx.company_name, inputs.angle),- retrieved_knowledge=rag,- )- touches.append(("First touch", first.strip()))- for k in range(1, inputs.follow_up_count + 1):- body = await route_to_specialist(- specialist_name=_SPECIALIST,- query=_follow_up_prompt(- ctx.engagement, ctx.candidate, ctx.company_name, k, inputs.follow_up_count- ),- )- touches.append((f"Follow-up {k}", body.strip()))- yield WorkflowEvent(- type="step_done", step_id="draft", summary=f"Drafted {len(touches)} touches."- )-- yield WorkflowEvent(- type="step_start", step_id="schedule", step_title="Schedule reminders"- )- # Compute each touch's send time ONCE (touch i at now + i*interval) so the- # scheduled reminders and the artifact can't drift apart.- now = datetime.now(UTC)- schedule = [- (label, body, now + timedelta(days=i * inputs.follow_up_interval_days))- for i, (label, body) in enumerate(touches)- ]- total = len(schedule)- action_ids = [- schedule_reminder(- ctx=ctx,- run_at=run_at_dt,- intent_text=_reminder_text(- label, i + 1, total, ctx.candidate, ctx.engagement, ctx.company_name, body- ),- )- for i, (label, body, run_at_dt) in enumerate(schedule)- ]- yield WorkflowEvent(- type="step_done",- step_id="schedule",- summary=f"Scheduled {len(action_ids)} reminders to {ctx.principal.full_name}.",- )-- yield WorkflowEvent(- type="result",- data={- "candidate_id": ctx.candidate.id,- "engagement_id": ctx.engagement.id,- "scheduled_count": len(action_ids),- "action_ids": action_ids,- },- )- yield WorkflowEvent(- type="artifact",- content=_assemble_artifact(- ctx, schedule, inputs.follow_up_interval_days- ),- )---def _reminder_text(- label: str,- n: int,- total: int,- candidate: Candidate,- engagement: Engagement,- company_name: str,- body: str,-) -> str:- """Instruction delivered to the Executive at fire time — DM the principal the- draft for review. Explicitly forbids contacting the candidate directly."""- who = candidate.full_name- if candidate.current_title:- who += f" ({candidate.current_title}"- who += f" at {candidate.current_company})" if candidate.current_company else ")"- return (- f"Outreach reminder {n}/{total} ({label}) for the {engagement.role_title} "- f"search ({company_name}). Send the principal this ready-to-send draft for "- f"{who} so they can review and send it themselves. Do NOT contact the "- f"candidate directly.\n\n"- f"--- DRAFT ({label}) ---\n{body}\n--- END DRAFT ---"- )---def _assemble_artifact(- ctx: ReminderContext,- schedule: list[tuple[str, str, datetime]],- interval_days: int,-) -> str:- lines = artifact_header(- ctx,- title="Outreach Sequence",- disclaimer=(- "Drafts only — OE schedules a reminder to you for each touch; you "- "review and send to the candidate. OE never contacts candidates directly."- ),- meta_lines=[f"**Cadence:** first touch now, then every {interval_days} day(s) "],- )- for label, body, run_at_dt in schedule:- send_on = run_at_dt.date().isoformat()- lines += [f"## {label} — send ~{send_on}", "", body.strip(), ""]- return "\n".join(lines).strip() + "\n"---def _first_touch_prompt(- engagement: Engagement, candidate: Candidate, company_name: str, angle: str-) -> str:- angle_block = f"\n\nEmphasis the principal asked for: {angle.strip()}" if angle.strip() else ""- return (- f"Write a personalized FIRST-TOUCH outreach message to {candidate.full_name} "- f"({candidate.current_title or 'an executive'}"- f"{f' at {candidate.current_company}' if candidate.current_company else ''}) "- f"about the {engagement.role_title} search for {company_name}.\n\n"- f"Role must-haves / context:\n{engagement.must_haves or '(not specified)'}\n"- f"{engagement.description or ''}{angle_block}\n\n"- "Output: the message body only (no subject line, no preamble, no commentary). "- "Keep it under 150 words, specific to this person's background, and lead with "- "why THEM for THIS role — not a generic recruiter blast. Sign off as the "- "principal (use a [Your name] placeholder)."- )---def _follow_up_prompt(- engagement: Engagement, candidate: Candidate, company_name: str, k: int, total: int-) -> str:- return (- f"Write follow-up #{k} of {total} to {candidate.full_name} for the "- f"{engagement.role_title} search ({company_name}). They have not replied to "- "the previous message(s).\n\n"- "Output: the message body only (no subject, no commentary). Under 100 words, "- "add a NEW angle or piece of value each time (don't just 'bump' the thread), "- "stay warm and low-pressure, and make it easy to decline. Sign off with a "- "[Your name] placeholder."- )diff --git a/packages/core/openexecutive/workflows/candidate_screen.py b/packages/core/openexecutive/workflows/candidate_screen.pydeleted file mode 100644index 53390c8c..00000000--- a/packages/core/openexecutive/workflows/candidate_screen.py+++ /dev/null@@ -1,272 +0,0 @@-"""Candidate screen workflow — assesses one candidate against one search-engagement and produces a fit scorecard.--Reuses the existing workflow machinery (``Workflow`` ABC, ``WorkflowEvent``-stream, domain-filtered RAG via ``retrieve``, and the talent specialist via-``route_to_specialist``). The screen's numeric fit score and summary are-persisted back onto the candidate row through ``talent.store.record_screening``,-which also advances a raw ``lead`` to ``screened``.-"""-from __future__ import annotations--import re-from collections.abc import AsyncIterator-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.talent import graph as talent_graph-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import Candidate, Engagement-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)--_SPECIALIST = "talent"---class CandidateScreenInput(BaseModel):- """Inputs for the Candidate Screen workflow.-- Both ids must reference existing, non-archived rows. The candidate must- belong to the engagement — screening a candidate against a different- engagement than the one they're tracked under is a caller error, not a- silent reassignment.- """-- engagement_id: int = Field(..., description="The search engagement to screen against.")- candidate_id: int = Field(..., description="The candidate to screen.")---class CandidateScreenWorkflow(Workflow):- name = "candidate_screen"- title = "Candidate Screen"- description = (- "Screens one candidate against one executive-search engagement: a "- "fit score (0-100), evidence mapped to the must-haves, the biggest "- "risk, and an advance/pass recommendation. Persists the score and "- "summary onto the candidate and advances them to 'screened'."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 3-- def input_model(self) -> type[BaseModel]:- return CandidateScreenInput-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(- id="load",- title="Load engagement & candidate",- description="Fetch the search mandate and the candidate record.",- ),- WorkflowStepDef(- id="assess",- title="Screen candidate",- description="The talent specialist scores fit against the must-haves.",- ),- WorkflowStepDef(- id="persist",- title="Record screening",- description="Save the fit score & summary; advance the pipeline stage.",- ),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, CandidateScreenInput)-- yield WorkflowEvent(- type="step_start", step_id="load", step_title="Load engagement & candidate"- )- engagement = talent_store.get_engagement(inputs.engagement_id)- candidate = talent_store.get_candidate(inputs.candidate_id)- if engagement is None:- yield WorkflowEvent(- type="error", message=f"Engagement {inputs.engagement_id} not found."- )- return- if candidate is None:- yield WorkflowEvent(- type="error", message=f"Candidate {inputs.candidate_id} not found."- )- return- if candidate.engagement_id != engagement.id:- yield WorkflowEvent(- type="error",- message=(- f"Candidate {candidate.id} belongs to engagement "- f"{candidate.engagement_id}, not {engagement.id}."- ),- )- return- from openexecutive.talent.reminders import company_name as _company_name-- company_name = _company_name()- yield WorkflowEvent(- type="step_done",- step_id="load",- summary=f"{candidate.full_name} vs. {engagement.role_title} for {company_name}.",- )-- yield WorkflowEvent(- type="step_start", step_id="assess", step_title="Screen candidate"- )- rag = retrieve(- query=(- f"executive screening interview scorecard {engagement.role_title} "- f"{engagement.must_haves}"- ),- specialist_name=_SPECIALIST,- n_builtin=4,- n_company=2,- store=store,- )- assessment = await route_to_specialist(- specialist_name=_SPECIALIST,- query=_build_screen_prompt(engagement, candidate),- retrieved_knowledge=rag,- )- fit_score = _parse_fit_score(assessment)- yield WorkflowEvent(- type="step_done",- step_id="assess",- summary=(- f"Fit score: {fit_score}/100." if fit_score is not None- else "Assessment complete (no numeric score parsed)."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="persist", step_title="Record screening"- )- recorded = False- if fit_score is not None and candidate.id is not None:- recorded = talent_store.record_screening(- candidate.id, fit_score=fit_score, summary=assessment- )- if recorded:- # Re-index so the talent graph reflects the new screening- # summary (the richest matching signal). Best-effort.- refreshed = talent_store.get_candidate(candidate.id)- if refreshed is not None:- talent_graph.index_candidate(refreshed, store)- yield WorkflowEvent(- type="step_done",- step_id="persist",- summary=(- "Saved score and advanced pipeline stage." if recorded- else "Skipped persistence — no defensible score to record."- ),- )-- # Structured payload first (for programmatic consumers), then the- # human-facing Markdown artifact — same ordering the base ABC documents.- yield WorkflowEvent(- type="result",- data={- "candidate_id": candidate.id,- "engagement_id": engagement.id,- "fit_score": fit_score,- "recorded": recorded,- },- )- yield WorkflowEvent(- type="artifact",- content=_assemble_scorecard(- engagement, candidate, company_name, fit_score, assessment- ),- )-- def sample_inputs(self) -> dict[str, Any]:- return {"engagement_id": 1, "candidate_id": 1}---def _build_screen_prompt(engagement: Engagement, candidate: Candidate) -> str:- must_haves = engagement.must_haves.strip() or "(none specified)"- description = engagement.description.strip() or "(no additional context)"- cand_lines = [- f"- Name: {candidate.full_name}",- f"- Current title: {candidate.current_title or '(unknown)'}",- f"- Current company: {candidate.current_company or '(unknown)'}",- f"- Location: {candidate.location or '(unknown)'}",- ]- if candidate.notes.strip():- cand_lines.append(f"- Notes / background: {candidate.notes.strip()}")- candidate_block = "\n".join(cand_lines)- return (- f"Screen this candidate for the **{engagement.role_title}** search "- f"(comp band: {engagement.comp_band or 'unspecified'}; "- f"location: {engagement.location or 'unspecified'}).\n\n"- f"Must-haves / year-one outcomes:\n{must_haves}\n\n"- f"Role context:\n{description}\n\n"- f"Candidate:\n{candidate_block}\n\n"- "Output (Markdown), in this order:\n"- "1. **Fit score: N/100** — one line, where N is an integer 0-100, "- "with a one-sentence justification tied to the must-haves.\n"- "2. **Evidence for fit** — map what we know about the candidate to "- "each must-have / outcome.\n"- "3. **Gaps & biggest risk** — the single biggest risk and the "- "reference/interview probe that would confirm or kill it.\n"- "4. **Recommendation** — one of: advance / advance-with-reservations / pass.\n\n"- "Discipline: score from evidence, not optimism. If a must-have is "- "unmet, the score must reflect it. Begin your response with the "- "literal text 'Fit score: ' so the number is unambiguous."- )---def _parse_fit_score(text: str) -> int | None:- """Extract a 0-100 integer fit score from the specialist's prose.-- Deliberately conservative: it matches ONLY the ``N/100`` form the prompt- mandates ("**Fit score: N/100**"). Bare numbers are never parsed, because a- score is indistinguishable from prose like "3/5 must-haves" or "5 criteria- reviewed" — and recording a wrong score is worse than recording none. All- ``N/100`` occurrences are scanned and the first in-range one wins, so a- stray out-of-range "150/100" doesn't block a later valid "82/100". A miss- returns None and the caller skips persistence (the safe failure mode).- """- if not text:- return None- for m in re.finditer(r"(\d{1,3})\s*/\s*100\b", text):- value = int(m.group(1))- if 0 <= value <= 100:- return value- return None---def _assemble_scorecard(- engagement: Engagement,- candidate: Candidate,- company_name: str,- fit_score: int | None,- assessment: str,-) -> str:- score_line = f"{fit_score}/100" if fit_score is not None else "not parsed"- body = assessment.strip() or "_(No assessment generated.)_"- parts = [- f"# Candidate Screen — {candidate.full_name}",- "",- f"**Engagement:** {engagement.role_title} ({company_name}) ",- f"**Fit score:** {score_line} ",- f"**Current:** {candidate.current_title or '—'} @ "- f"{candidate.current_company or '—'}",- "",- "## Assessment",- "",- body,- "",- "---",- "*Drafted by the Talent & Executive Search specialist. Review with the "- "hiring committee before advancing the candidate.*",- ]- return "\n".join(parts).strip() + "\n"diff --git a/packages/core/openexecutive/workflows/dynamic.py b/packages/core/openexecutive/workflows/dynamic.pyindex c437834e..58cc3886 100644--- a/packages/core/openexecutive/workflows/dynamic.py+++ b/packages/core/openexecutive/workflows/dynamic.py@@ -28,7 +28,7 @@ from openexecutive.knowledge.retriever import retrievefrom openexecutive.knowledge.store import ChromaDBStorefrom openexecutive.memory.company_profile import CompanyProfilefrom openexecutive.onboarding.profile_builder import load_or_create_profile-from openexecutive.orchestrator.router import route_to_specialist+from openexecutive.orchestrator.router import SPECIALIST_REGISTRY, route_to_specialistfrom openexecutive.workflows.base import (Workflow,WorkflowEvent,@@ -143,6 +143,27 @@ class DynamicWorkflow(Workflow):) -> AsyncIterator[WorkflowEvent]:values = inputs.model_dump()+ # --- pre-flight ---+ # Definitions are validated on create/update, not on load, so a stored+ # definition can outlive a specialist (the `talent` key was removed).+ # `route_to_specialist` would return the string "Unknown specialist: …"+ # as a step's OUTPUT — or, via a synthesis step's own `specialist`, as+ # the whole artifact. Check every step up front so the run fails+ # before any approval gate is raised or any specialist call is paid for.+ stale = _stale_specialist_steps(self._defn)+ if stale:+ yield WorkflowEvent(+ type="error",+ message=(+ "workflow names a specialist that no longer exists — "+ + "; ".join(+ f"step {sid!r} uses {name!r}" for sid, name in stale+ )+ + " — edit the workflow to use a current specialist"+ ),+ )+ return+# --- context ---yield WorkflowEvent(type="step_start", step_id=_CONTEXT_STEP_ID, step_title="Load context"@@ -237,6 +258,21 @@ class DynamicWorkflow(Workflow):# ---------------------------------------------------------------------------+def _stale_specialist_steps(defn: DynamicWorkflowDef) -> list[tuple[str, str]]:+ """(step_id, specialist) for every step that would consult a specialist+ missing from the live registry. A synthesis step only consults one when it+ has `instructions`."""+ stale: list[tuple[str, str]] = []+ for step in defn.steps:+ if isinstance(step, ApprovalGateStepSpec):+ continue+ if isinstance(step, SynthesisStepSpec) and not step.instructions:+ continue+ if step.specialist not in SPECIALIST_REGISTRY:+ stale.append((step.id, step.specialist))+ return stale++async def _synthesize(step: SynthesisStepSpec,workflow_title: str,diff --git a/packages/core/openexecutive/workflows/interview_coordination.py b/packages/core/openexecutive/workflows/interview_coordination.pydeleted file mode 100644index 6174415f..00000000--- a/packages/core/openexecutive/workflows/interview_coordination.py+++ /dev/null@@ -1,237 +0,0 @@-"""Interview coordination workflow — Phase 3 recruiting automation.--Drafts an interview loop (rounds, what each tests) plus a candidate-facing-availability-request message, then schedules a single reminder to the principal-to kick off scheduling. Draft-and-approve: OE never contacts the candidate-directly — the reminder hands the principal the ready-to-send availability-request and the loop plan.--Shares context/channel/scheduling machinery with the other talent workflows via-``openexecutive.talent.reminders``.-"""-from __future__ import annotations--from collections.abc import AsyncIterator-from datetime import UTC, datetime-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.talent.models import Candidate, Engagement-from openexecutive.talent.reminders import (- ReminderContext,- artifact_header,- resolve_reminder_context,- schedule_reminder,-)-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)--_SPECIALIST = "talent"-_MAX_ROUNDS = 7---class InterviewCoordinationInput(BaseModel):- """Inputs for the Interview Coordination workflow."""-- candidate_id: int = Field(..., description="Candidate to coordinate interviews for.")- num_rounds: int = Field(- default=4, ge=1, le=_MAX_ROUNDS,- description="How many interview rounds to design (1-7).",- )- notes: str = Field(- default="",- description="Optional constraints (timeline, who must be on the panel, format).",- max_length=2000,- )---class InterviewCoordinationWorkflow(Workflow):- name = "interview_coordination"- title = "Interview Coordination"- description = (- "Designs the interview loop and drafts a candidate availability-request, "- "then schedules a reminder to you to kick off scheduling. Never contacts "- "the candidate directly."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 3-- def input_model(self) -> type[BaseModel]:- return InterviewCoordinationInput-- def sample_inputs(self) -> dict[str, Any]:- return {- "candidate_id": 1,- "num_rounds": 4,- "notes": "Founder must take the final round; aim to close within two weeks.",- }-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(- id="load",- title="Load candidate & recipient",- description="Fetch the candidate, engagement, and the principal who'll coordinate.",- ),- WorkflowStepDef(- id="design",- title="Design loop & availability request",- description="Interview rounds + a candidate-facing availability message.",- ),- WorkflowStepDef(- id="schedule",- title="Schedule reminder",- description="Queue a reminder to you to kick off scheduling.",- ),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, InterviewCoordinationInput)-- yield WorkflowEvent(- type="step_start", step_id="load", step_title="Load candidate & recipient"- )- ctx = resolve_reminder_context(inputs.candidate_id)- if isinstance(ctx, str):- yield WorkflowEvent(type="error", message=ctx)- return- yield WorkflowEvent(- type="step_done",- step_id="load",- summary=(- f"{ctx.candidate.full_name} for {ctx.engagement.role_title} "- f"({ctx.company_name}); reminder → {ctx.principal.full_name}."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="design", step_title="Design loop & availability request"- )- rag = retrieve(- query=f"executive interview loop plan {ctx.engagement.role_title} {ctx.engagement.must_haves}",- specialist_name=_SPECIALIST,- n_builtin=3,- n_company=2,- store=store,- )- loop = (- await route_to_specialist(- specialist_name=_SPECIALIST,- query=_loop_prompt(ctx.engagement, ctx.candidate, inputs.num_rounds, inputs.notes),- retrieved_knowledge=rag,- )- ).strip()- availability = (- await route_to_specialist(- specialist_name=_SPECIALIST,- query=_availability_prompt(ctx.engagement, ctx.candidate, ctx.company_name),- )- ).strip()- yield WorkflowEvent(- type="step_done", step_id="design", summary=f"Designed a {inputs.num_rounds}-round loop."- )-- yield WorkflowEvent(- type="step_start", step_id="schedule", step_title="Schedule reminder"- )- action_id = schedule_reminder(- ctx=ctx,- run_at=datetime.now(UTC),- intent_text=_coord_reminder_text(ctx, loop, availability),- )- yield WorkflowEvent(- type="step_done",- step_id="schedule",- summary=f"Scheduled a coordination reminder to {ctx.principal.full_name}.",- )-- yield WorkflowEvent(- type="result",- data={- "candidate_id": ctx.candidate.id,- "engagement_id": ctx.engagement.id,- "scheduled_count": 1,- "action_ids": [action_id],- },- )- yield WorkflowEvent(- type="artifact",- content=_assemble_artifact(ctx, loop, availability),- )---def _coord_reminder_text(ctx: ReminderContext, loop: str, availability: str) -> str:- return (- f"Interview coordination for {ctx.candidate.full_name} on the "- f"{ctx.engagement.role_title} search ({ctx.company_name}). Send the principal "- "the proposed interview loop below and the ready-to-send availability request "- "so they can line up the panel and send the request to the candidate. Do NOT "- "contact the candidate directly.\n\n"- f"--- INTERVIEW LOOP ---\n{loop}\n--- END LOOP ---\n\n"- f"--- AVAILABILITY REQUEST (to send to candidate) ---\n{availability}\n"- "--- END REQUEST ---"- )---def _assemble_artifact(ctx: ReminderContext, loop: str, availability: str) -> str:- lines = artifact_header(- ctx,- title="Interview Coordination",- disclaimer=(- "Drafts only — OE schedules a reminder to you to coordinate; you line up "- "the panel and send the availability request. OE never contacts the "- "candidate directly."- ),- )- lines += [- "## Proposed Interview Loop",- "",- loop or "_(none generated)_",- "",- "## Availability Request (to send to the candidate)",- "",- availability or "_(none generated)_",- ]- return "\n".join(lines).strip() + "\n"---def _loop_prompt(- engagement: Engagement, candidate: Candidate, num_rounds: int, notes: str-) -> str:- notes_block = f"\n\nConstraints from the principal: {notes.strip()}" if notes.strip() else ""- return (- f"Design a {num_rounds}-round interview loop for {candidate.full_name} for the "- f"{engagement.role_title} role.\n\n"- f"Role must-haves / context:\n{engagement.must_haves or '(not specified)'}\n"- f"{engagement.description or ''}{notes_block}\n\n"- f"Output (Markdown): a numbered list of exactly {num_rounds} rounds. For each: "- "**Round name**, interviewer (role, e.g. founder / function head / peer), what "- "it tests (tie to a must-have), and length in minutes. End with a one-line note "- "on the working session or final-round focus. Be specific to THIS role — no "- "generic 'culture fit' rounds without saying what that means here."- )---def _availability_prompt(- engagement: Engagement, candidate: Candidate, company_name: str-) -> str:- return (- f"Write a short, warm availability-request message to {candidate.full_name} to "- f"schedule interviews for the {engagement.role_title} role at {company_name}.\n\n"- "Output: the message body only (no subject, no commentary). Under 120 words. "- "Explain the loop at a high level (how many conversations, roughly how long), "- "ask for a few windows over the next 1-2 weeks, and keep it easy and respectful "- "of their time. Sign off with a [Your name] placeholder."- )diff --git a/packages/core/openexecutive/workflows/new_hire_onboarding.py b/packages/core/openexecutive/workflows/new_hire_onboarding.pydeleted file mode 100644index abd841b7..00000000--- a/packages/core/openexecutive/workflows/new_hire_onboarding.py+++ /dev/null@@ -1,363 +0,0 @@-"""New-hire onboarding workflow — the placed → Person handoff.--When an offer is accepted (candidate ``placed``), the talent module and the-people module need to connect: the candidate becomes a real-:class:`~openexecutive.people.models.Person` the Executive can address, and-their first 90 days get a plan plus milestone check-ins.--This workflow is the *explicit* trigger for that handoff — Person creation-is never a hidden side effect of a stage change. It is idempotent: re-running-matches the existing Person (by email, else exact name) and updates their-role instead of duplicating them.--Posture: milestone reminders go to the *principal* (never the new hire) —-each fires as a prompt to run the check-in themselves.-"""-from __future__ import annotations--import logging-from collections.abc import AsyncIterator-from datetime import UTC, date, datetime, time, timedelta-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage, Engagement, OfferStatus-from openexecutive.talent.reminders import (- ReminderContext,- artifact_header,- resolve_reminder_context,- schedule_reminder,-)-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)--logger = logging.getLogger(__name__)--_SPECIALIST = "chro"--# Day offsets for the milestone check-in reminders. Day 7 catches early-# drift; 30/60/90 mirror the plan the chro drafts.-_CHECKIN_DAYS = (7, 30, 60, 90)---class NewHireOnboardingInput(BaseModel):- """Inputs for the New-Hire Onboarding workflow."""-- candidate_id: int = Field(..., description="The placed candidate to onboard.")- start_date: str = Field(- default="",- description="The hire's start date (ISO date, e.g. 2026-07-01). Defaults to today.",- )- focus_notes: str = Field(- default="",- description=(- "Optional emphasis for the 30/60/90 plan (e.g. 'first priority is "- "stabilizing the field ops team')."- ),- max_length=2000,- )---class NewHireOnboardingWorkflow(Workflow):- name = "new_hire_onboarding"- title = "New-Hire Onboarding (30/60/90)"- description = (- "Turns a placed candidate into a Person on the roster, drafts a "- "role-specific 30/60/90 onboarding plan, and schedules milestone "- "check-in reminders to you (the principal). Never contacts the new "- "hire directly. Run it after recording an accepted offer."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 3-- def input_model(self) -> type[BaseModel]:- return NewHireOnboardingInput-- def sample_inputs(self) -> dict[str, Any]:- return {- "candidate_id": 1,- "start_date": "",- "focus_notes": "first priority is stabilizing the field ops team",- }-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(- id="load",- title="Load the placed candidate",- description="Verify the hire is placed (or their offer accepted).",- ),- WorkflowStepDef(- id="create_person",- title="Add to the roster",- description="Create (or update) the Person record for the new hire.",- ),- WorkflowStepDef(- id="design_plan",- title="Draft the 30/60/90 plan",- description="Role-specific onboarding plan via the people specialist.",- ),- WorkflowStepDef(- id="schedule_checkins",- title="Schedule check-ins",- description="Queue day-7/30/60/90 check-in reminders to you.",- ),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, NewHireOnboardingInput)-- yield WorkflowEvent(- type="step_start", step_id="load", step_title="Load the placed candidate"- )- ctx = resolve_reminder_context(inputs.candidate_id)- if isinstance(ctx, str):- yield WorkflowEvent(type="error", message=ctx)- return- accepted = talent_store.list_offers(- candidate_id=inputs.candidate_id, status=OfferStatus.ACCEPTED- )- if ctx.candidate.stage is not CandidateStage.PLACED and not accepted:- yield WorkflowEvent(- type="error",- message=(- f"{ctx.candidate.full_name} is not placed and has no accepted "- "offer — record the offer acceptance first "- "(record_offer_decision)."- ),- )- return- try:- start = (- date.fromisoformat(inputs.start_date)- if inputs.start_date.strip()- else datetime.now(UTC).date()- )- except ValueError:- yield WorkflowEvent(- type="error",- message=f"start_date is not an ISO date: {inputs.start_date!r}",- )- return- yield WorkflowEvent(- type="step_done",- step_id="load",- summary=(- f"{ctx.candidate.full_name} → {ctx.engagement.role_title} "- f"({ctx.company_name}), starting {start.isoformat()}."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="create_person", step_title="Add to the roster"- )- person_id, created = _upsert_hire_person(ctx)- yield WorkflowEvent(- type="step_done",- step_id="create_person",- summary=(- f"{'Added' if created else 'Updated'} {ctx.candidate.full_name} "- f"on the roster (person {person_id})."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="design_plan", step_title="Draft the 30/60/90 plan"- )- rag = retrieve(- query=f"executive onboarding 30 60 90 plan {ctx.engagement.role_title}",- specialist_name=_SPECIALIST,- n_builtin=3,- n_company=2,- store=store,- )- plan = (- await route_to_specialist(- specialist_name=_SPECIALIST,- query=_plan_prompt(ctx.engagement, ctx.candidate.full_name, ctx.company_name,- start, inputs.focus_notes),- retrieved_knowledge=rag,- )- ).strip()- yield WorkflowEvent(- type="step_done", step_id="design_plan", summary="30/60/90 plan drafted."- )-- yield WorkflowEvent(- type="step_start", step_id="schedule_checkins", step_title="Schedule check-ins"- )- now = datetime.now(UTC)- action_ids: list[int] = []- scheduled_days: list[int] = []- for day in _CHECKIN_DAYS:- run_at = datetime.combine(start + timedelta(days=day), time(9, 0), tzinfo=UTC)- if run_at <= now:- continue # don't fire check-ins for milestones already past- action_ids.append(- schedule_reminder(- ctx=ctx,- run_at=run_at,- intent_text=_checkin_text(day, ctx),- )- )- scheduled_days.append(day)- yield WorkflowEvent(- type="step_done",- step_id="schedule_checkins",- summary=(- f"Scheduled {len(action_ids)} check-in reminders "- f"(days {', '.join(str(d) for d in scheduled_days) or '—'}) "- f"to {ctx.principal.full_name}."- ),- )-- yield WorkflowEvent(- type="result",- data={- "person_id": person_id,- "person_created": created,- "candidate_id": ctx.candidate.id,- "engagement_id": ctx.engagement.id,- "scheduled_count": len(action_ids),- "action_ids": action_ids,- },- )- yield WorkflowEvent(- type="artifact",- content=_assemble_artifact(ctx, plan, start, scheduled_days),- )---def _upsert_hire_person(ctx: ReminderContext) -> tuple[int, bool]:- """Create or update the Person record for the hire. Returns (id, created).-- Idempotent: matches an existing non-archived Person by case-insensitive- email (when the candidate has one), else by exact full name, and updates- their role rather than duplicating. New hires get no authority scopes —- those are granted deliberately, not by onboarding.- """- from openexecutive.people.store import (- find_person_by_email,- list_people,- upsert_person,- )-- candidate = ctx.candidate- existing = None- if candidate.email:- existing = find_person_by_email(candidate.email)- if existing is None:- existing = next(- (p for p in list_people() if p.full_name == candidate.full_name), None- )-- dept_slugs = _resolvable_department_slugs(ctx.engagement)- if existing is not None and existing.id is not None:- upsert_person(- full_name=existing.full_name,- role=ctx.engagement.role_title,- is_principal=existing.is_principal,- # The engagement is the source of truth for the NEW role (role is- # overwritten above for the same reason) — a re-hire moving- # departments must not keep the stale slugs. Existing slugs only- # survive when the engagement's department doesn't resolve.- department_slugs=dept_slugs or existing.department_slugs,- email=existing.email or candidate.email,- slack_user_id=existing.slack_user_id,- telegram_chat_id=existing.telegram_chat_id,- discord_user_id=existing.discord_user_id,- preferred_channel=existing.preferred_channel,- response_sla_hours=existing.response_sla_hours,- on_leave_until=existing.on_leave_until,- reports_to_person_id=existing.reports_to_person_id,- person_id=existing.id,- )- return existing.id, False- person_id = upsert_person(- full_name=candidate.full_name,- role=ctx.engagement.role_title,- email=candidate.email,- department_slugs=dept_slugs,- )- return person_id, True---def _resolvable_department_slugs(engagement: Engagement) -> list[str]:- """Map the engagement's free-text department to a real slug, if it is one.-- ``Engagement.department`` is a plain label, not a FK — only pass it onto- the Person when it resolves in the department registry.- """- from openexecutive.departments.registry import get_state-- label = engagement.department.strip()- if not label:- return []- for candidate_slug in (label, label.lower(), label.lower().replace(" ", "_")):- if get_state(candidate_slug) is not None:- return [candidate_slug]- return []---def _checkin_text(day: int, ctx: ReminderContext) -> str:- return (- f"Onboarding check-in (day {day}) for {ctx.candidate.full_name}, "- f"{ctx.engagement.role_title} at {ctx.company_name}. DM the principal "- f"the day-{day} milestone questions from the onboarding plan so they "- "can run the check-in themselves. Do NOT contact the new hire "- "directly — this is a reminder for the principal."- )---def _assemble_artifact(- ctx: ReminderContext, plan: str, start: date, scheduled_days: list[int]-) -> str:- lines = artifact_header(- ctx,- title="Onboarding Plan",- disclaimer=(- "Check-in reminders go to you — OE never contacts the new hire "- "directly. You run each milestone conversation yourself."- ),- meta_lines=[- f"**Start date:** {start.isoformat()} ",- f"**Check-ins:** day {', '.join(str(d) for d in scheduled_days) or '(none scheduled)'} ",- ],- )- lines += ["## 30/60/90 plan", "", plan]- return "\n".join(lines).strip() + "\n"---def _plan_prompt(- engagement: Engagement,- hire_name: str,- company_name: str,- start: date,- focus_notes: str,-) -> str:- focus_block = (- f"\n\nEmphasis from the principal: {focus_notes.strip()}" if focus_notes.strip() else ""- )- return (- f"Draft a 30/60/90-day onboarding plan for {hire_name}, our new "- f"{engagement.role_title} at {company_name}, starting {start.isoformat()}.\n\n"- f"Role must-haves / mandate:\n{engagement.must_haves or '(not specified)'}\n"- f"{engagement.description or ''}{focus_block}\n\n"- "Output, in Markdown: a section each for days 1-30 (learn), 31-60 "- "(own), 61-90 (deliver), each with 3-5 concrete outcomes tied to this "- "role's mandate, plus a final section of milestone check-in questions "- "for day 7, 30, 60, and 90. No preamble."- )diff --git a/packages/core/openexecutive/workflows/offer_approval.py b/packages/core/openexecutive/workflows/offer_approval.pydeleted file mode 100644index 69907580..00000000--- a/packages/core/openexecutive/workflows/offer_approval.py+++ /dev/null@@ -1,439 +0,0 @@-"""Offer package & approval workflow — closing the hire loop.--Drafts a complete offer package for a candidate (terms via the CHRO-specialist anchored on the engagement's comp band, closing plan via the-talent specialist), persists it as an :class:`~openexecutive.talent.models.Offer`,-DMs the HIRING_SIGNOFF approver a summary, and pauses on a-``WaitForHumanEvent`` gate so the approval is recorded against the run.--This is the first *built-in* workflow to yield the gate (previously only-user-created dynamic workflows did). Paused runs never auto-resume-(generator resume is deferred upstream), so the gate's job here is to-*record* the sign-off — the ``pending_approval → extended`` transition is an-explicit follow-up action (the ``extend_offer`` tool / ``POST-/offers/{id}/extend``) that consults the recorded resolution via-``openexecutive.talent.offers``. The ``result`` and ``artifact`` events are-yielded *before* the gate, and the package Markdown is persisted onto the-Offer row, so nothing is lost when the run pauses.--Posture: OE never sends the offer to the candidate. The approver gets the-sign-off request; the principal extends the offer themselves after sign-off.-"""-from __future__ import annotations--import json-import logging-from collections.abc import AsyncIterator-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import (- Candidate,- CandidateStage,- Engagement,- Offer,- OfferStatus,-)-from openexecutive.talent.offers import gate_context_summary-from openexecutive.talent.reminders import (- ReminderContext,- artifact_header,- person_channel_raw,- resolve_reminder_context,-)-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)-from openexecutive.workflows.wait_for_human import WaitForHumanEvent--logger = logging.getLogger(__name__)--_TERMS_SPECIALIST = "chro"-_CLOSE_SPECIALIST = "talent"--# Candidates must have at least been interviewed before an offer is drafted.-_OFFERABLE_STAGES = (CandidateStage.INTERVIEWED, CandidateStage.OFFER)--_SIGNOFF_TIMEOUT_HOURS = 72---class OfferApprovalInput(BaseModel):- """Inputs for the Offer Package & Approval workflow."""-- candidate_id: int = Field(..., description="Candidate to draft the offer for.")- comp_notes: str = Field(- default="",- description=(- "Optional terms the principal already has in mind (base, equity, "- "sign-on, start date…). The drafted terms anchor on these plus the "- "engagement's comp band."- ),- max_length=2000,- )- angle: str = Field(- default="",- description="Optional emphasis for the close (e.g. 'they have a competing offer').",- max_length=2000,- )---class OfferApprovalWorkflow(Workflow):- name = "offer_approval"- title = "Offer Package & Approval"- description = (- "Drafts a complete offer package (terms anchored on the engagement's "- "comp band, plus a closing plan), sends the hiring sign-off request to "- "the HIRING_SIGNOFF approver, and pauses until they reply. After "- "approval, mark the offer extended (extend_offer) when you send it — "- "OE never sends the offer to the candidate."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 4-- def input_model(self) -> type[BaseModel]:- return OfferApprovalInput-- def sample_inputs(self) -> dict[str, Any]:- return {- "candidate_id": 1,- "comp_notes": "base around the top of band, 0.5% equity, modest sign-on",- "angle": "they are also in late stages with a competitor",- }-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(- id="load",- title="Load candidate & approver",- description="Fetch the candidate, engagement, and the hiring sign-off approver.",- ),- WorkflowStepDef(- id="draft_terms",- title="Draft offer terms",- description="Comp package anchored on the engagement's comp band.",- ),- WorkflowStepDef(- id="close_plan",- title="Closing plan",- description="Closing risks, competing-offer posture, recommended expiry window.",- ),- WorkflowStepDef(- id="persist",- title="Persist the offer",- description="Save the offer package and move the candidate to the offer stage.",- ),- WorkflowStepDef(- id="request_signoff",- title="Request sign-off",- description="DM the approver and pause until they approve or reject.",- ),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, OfferApprovalInput)-- yield WorkflowEvent(- type="step_start", step_id="load", step_title="Load candidate & approver"- )- ctx = resolve_reminder_context(inputs.candidate_id)- if isinstance(ctx, str):- yield WorkflowEvent(type="error", message=ctx)- return- if ctx.candidate.stage not in _OFFERABLE_STAGES:- yield WorkflowEvent(- type="error",- message=(- f"{ctx.candidate.full_name} is at stage "- f"'{ctx.candidate.stage.value}' — screen and interview them "- "before drafting an offer."- ),- )- return- if talent_store.get_open_offer_for_candidate(inputs.candidate_id) is not None:- yield WorkflowEvent(- type="error",- message=(- f"{ctx.candidate.full_name} already has an open offer — record "- "a decision on it (or rescind it) before drafting another."- ),- )- return- approver = _resolve_approver(ctx)- yield WorkflowEvent(- type="step_done",- step_id="load",- summary=(- f"{ctx.candidate.full_name} for {ctx.engagement.role_title} "- f"({ctx.company_name}); sign-off → {approver.full_name}."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="draft_terms", step_title="Draft offer terms"- )- rag = retrieve(- query=(- f"compensation offer design {ctx.engagement.role_title} "- f"{ctx.engagement.comp_band}"- ),- specialist_name=_TERMS_SPECIALIST,- n_builtin=3,- n_company=2,- store=store,- )- terms = (- await route_to_specialist(- specialist_name=_TERMS_SPECIALIST,- query=_terms_prompt(ctx.engagement, ctx.candidate, ctx.company_name, inputs.comp_notes),- retrieved_knowledge=rag,- )- ).strip()- yield WorkflowEvent(- type="step_done", step_id="draft_terms", summary=f"Drafted terms ({len(terms)} chars)."- )-- yield WorkflowEvent(- type="step_start", step_id="close_plan", step_title="Closing plan"- )- close_plan = (- await route_to_specialist(- specialist_name=_CLOSE_SPECIALIST,- query=_close_prompt(ctx.engagement, ctx.candidate, ctx.company_name, inputs.angle),- )- ).strip()- yield WorkflowEvent(- type="step_done", step_id="close_plan", summary="Closing plan ready."- )-- yield WorkflowEvent(- type="step_start", step_id="persist", step_title="Persist the offer"- )- comp_summary = inputs.comp_notes.strip() or ctx.engagement.comp_band or "see package"- try:- offer_id = talent_store.create_offer(- candidate_id=inputs.candidate_id,- engagement_id=ctx.candidate.engagement_id,- comp_summary=comp_summary,- )- except ValueError as exc:- # Raced another create between the load guard and here.- yield WorkflowEvent(type="error", message=str(exc))- return- offer = talent_store.get_offer(offer_id)- assert offer is not None- artifact_md = _assemble_artifact(ctx, offer, terms, close_plan, approver.full_name)- talent_store.update_offer_terms(offer_id, package_md=artifact_md)- talent_store.set_offer_status(offer_id, OfferStatus.PENDING_APPROVAL)- if ctx.candidate.stage is CandidateStage.INTERVIEWED:- # Mirrors record_screening advancing lead → screened: drafting an- # offer is what moves a candidate into the offer stage.- talent_store.set_candidate_stage(inputs.candidate_id, CandidateStage.OFFER)- yield WorkflowEvent(- type="step_done",- step_id="persist",- summary=f"Offer {offer_id} saved (pending approval).",- )-- yield WorkflowEvent(- type="step_start", step_id="request_signoff", step_title="Request sign-off"- )- question = (- f"Approve the offer to {ctx.candidate.full_name} for the "- f"{ctx.engagement.role_title} role? (offer_id={offer_id}) "- f"Terms: {comp_summary}"- )- outbound_message_id = await _dm_approver(approver.id or 0, question, offer_id, ctx)- channel, channel_ref = person_channel_raw(approver) or ("", "")- yield WorkflowEvent(- type="step_done",- step_id="request_signoff",- summary=f"Sign-off requested from {approver.full_name}; run pauses until they reply.",- )-- # result + artifact BEFORE the gate: the HTTP runner stops at the gate- # without completing the run, so anything after it would be lost.- yield WorkflowEvent(- type="result",- data={- "offer_id": offer_id,- "candidate_id": ctx.candidate.id,- "engagement_id": ctx.engagement.id,- "approver_person_id": approver.id,- },- )- yield WorkflowEvent(type="artifact", content=artifact_md)-- gate = WaitForHumanEvent(- person_id=approver.id or 0,- question=question,- timeout_hours=_SIGNOFF_TIMEOUT_HOURS,- on_timeout="escalate",- context_summary=gate_context_summary(- offer, ctx.candidate.full_name, ctx.engagement.role_title- ),- expected_reply_shape="approve_reject",- department=_department_slug(ctx.engagement),- outbound_message_id=outbound_message_id,- channel=channel,- channel_ref=channel_ref,- )- # WaitForHumanEvent is a sentinel the runner isinstance-checks; it- # isn't a WorkflowEvent, hence the typed-yield ignore (same as- # workflows/dynamic.py).- yield gate # type: ignore[misc]- return---def _resolve_approver(ctx: ReminderContext) -> Any:- """The HIRING_SIGNOFF approver, falling back to the principal.-- ``find_approvers`` prefers delegated humans over the principal and- includes WILDCARD holders; an empty result (no scope rows configured at- all) falls back to the principal, who is the operator of record.- """- from openexecutive.people.models import AuthorityScope- from openexecutive.people.store import find_approvers-- approvers = find_approvers(AuthorityScope.HIRING_SIGNOFF)- return approvers[0] if approvers else ctx.principal---def _department_slug(engagement: Engagement) -> str:- """Resolve the engagement's free-text department to a real slug, or ''.-- The gate's ``department`` drives timeout escalation routing — only pass- it when it resolves to an actual department.- """- from openexecutive.departments.registry import get_state-- label = engagement.department.strip()- if not label:- return ""- for candidate_slug in (label, label.lower(), label.lower().replace(" ", "_")):- if get_state(candidate_slug) is not None:- return candidate_slug- return ""---async def _dm_approver(- approver_person_id: int, question: str, offer_id: int, ctx: ReminderContext-) -> str:- """Best-effort DM of the sign-off request to the approver.-- Delegates to ``handle_message_person`` (same path the scheduler uses for- dynamic-workflow artifact delivery) — it resolves the channel server-side- and falls back to a briefing alert when no DM channel is deliverable, so- the request always lands somewhere visible. Returns the outbound message- id when the channel reports one, else "".- """- from openexecutive.orchestrator.schedule_tools import handle_message_person-- text = (- f"Hiring sign-off needed: {question}\n\n"- f"Full package: /talent/candidates/{ctx.candidate.id}\n"- "Reply approve / reject / defer."- )- try:- raw = await handle_message_person(- {"person_id": approver_person_id, "text": text}- )- except Exception: # noqa: BLE001 — an undeliverable DM must not kill the gate- logger.warning(- "offer_approval: sign-off DM failed (offer %s)", offer_id, exc_info=True- )- return ""- try:- parsed = json.loads(raw)- except (ValueError, TypeError):- return ""- return str(parsed.get("message_id") or parsed.get("ts") or "")---def _assemble_artifact(- ctx: ReminderContext,- offer: Offer,- terms: str,- close_plan: str,- approver_name: str,-) -> str:- lines = artifact_header(- ctx,- title="Offer Package",- disclaimer=(- "Draft for sign-off — OE never sends the offer to the candidate. "- f"After {approver_name} approves, you extend the offer yourself and "- "mark it extended so expiry reminders start."- ),- meta_lines=[- f"**Comp band:** {ctx.engagement.comp_band or '(not set — confirm comp before extending)'} ",- f"**Sign-off:** {approver_name} ",- f"**Offer id:** {offer.id} ",- ],- )- lines += [- "## Proposed terms",- "",- terms,- "",- "## Closing plan",- "",- close_plan,- "",- "## Next steps",- "",- f"1. {approver_name} approves or rejects the sign-off request.",- "2. On approval, you send the offer to the candidate yourself.",- "3. Mark it extended (extend_offer) — expiry reminders are scheduled then.",- "4. Record the outcome (accepted / declined / expired) when you hear back.",- ]- return "\n".join(lines).strip() + "\n"---def _terms_prompt(- engagement: Engagement, candidate: Candidate, company_name: str, comp_notes: str-) -> str:- band = engagement.comp_band.strip() or (- "(none set — flag clearly that the principal must confirm comp before extending)"- )- notes_block = (- f"\n\nTerms the principal has in mind:\n{comp_notes.strip()}" if comp_notes.strip() else ""- )- return (- f"Draft the offer TERMS for {candidate.full_name} "- f"({candidate.current_title or 'an executive'}"- f"{f' at {candidate.current_company}' if candidate.current_company else ''}) "- f"for the {engagement.role_title} role at {company_name}.\n\n"- f"Comp band for this role: {band}\n"- f"Role must-haves / context:\n{engagement.must_haves or '(not specified)'}\n"- f"{engagement.description or ''}{notes_block}\n\n"- "Output: a concise terms section in Markdown — base salary (anchored to "- "the band), equity, sign-on/relocation if warranted, start date posture, "- "and any contingencies (references, background check). State the "- "reasoning for each number in one line. No preamble, no commentary."- )---def _close_prompt(- engagement: Engagement, candidate: Candidate, company_name: str, angle: str-) -> str:- angle_block = f"\n\nContext from the principal: {angle.strip()}" if angle.strip() else ""- return (- f"We are about to extend an offer to {candidate.full_name} for the "- f"{engagement.role_title} role at {company_name}.{angle_block}\n\n"- "Output, in Markdown: (1) the top closing risks for this specific "- "candidate and how to pre-empt each, (2) competing-offer posture — what "- "to do if they shop it, (3) a recommended expiry window for the offer "- "with one line of reasoning. Keep it tight; no preamble."- )diff --git a/packages/core/openexecutive/workflows/reference_check.py b/packages/core/openexecutive/workflows/reference_check.pydeleted file mode 100644index 3a13f008..00000000--- a/packages/core/openexecutive/workflows/reference_check.py+++ /dev/null@@ -1,241 +0,0 @@-"""Reference check workflow — Phase 3 recruiting automation.--Drafts a reference-check rubric (questions + what a concerning answer looks like)-plus a reference-facing outreach message, then schedules a single reminder to the-principal to conduct the checks. Draft-and-approve: OE never contacts references-directly — the reminder hands the principal the rubric and the ready-to-send-outreach.--Shares context/channel/scheduling machinery with the other talent workflows via-``openexecutive.talent.reminders``.-"""-from __future__ import annotations--from collections.abc import AsyncIterator-from datetime import UTC, datetime-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.talent.models import Candidate, Engagement-from openexecutive.talent.reminders import (- ReminderContext,- artifact_header,- resolve_reminder_context,- schedule_reminder,-)-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)--_SPECIALIST = "talent"-_MAX_REFERENCES = 5---class ReferenceCheckInput(BaseModel):- """Inputs for the Reference Check workflow."""-- candidate_id: int = Field(..., description="Candidate to run reference checks for.")- reference_count: int = Field(- default=2, ge=1, le=_MAX_REFERENCES,- description="How many references to plan for (1-5).",- )- reference_notes: str = Field(- default="",- description="Optional known references or focus areas (names, relationships, concerns to probe).",- max_length=2000,- )---class ReferenceCheckWorkflow(Workflow):- name = "reference_check"- title = "Reference Check"- description = (- "Drafts a reference-check rubric and a reference-outreach message, then "- "schedules a reminder to you to conduct the checks. Never contacts "- "references directly."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 3-- def input_model(self) -> type[BaseModel]:- return ReferenceCheckInput-- def sample_inputs(self) -> dict[str, Any]:- return {- "candidate_id": 1,- "reference_count": 2,- "reference_notes": "One former manager, one former direct report. Probe the 2020 downturn.",- }-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(- id="load",- title="Load candidate & recipient",- description="Fetch the candidate, engagement, and the principal who'll conduct.",- ),- WorkflowStepDef(- id="draft",- title="Draft rubric & outreach",- description="Reference questions + a reference-facing outreach message.",- ),- WorkflowStepDef(- id="schedule",- title="Schedule reminder",- description="Queue a reminder to you to conduct the checks.",- ),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, ReferenceCheckInput)-- yield WorkflowEvent(- type="step_start", step_id="load", step_title="Load candidate & recipient"- )- ctx = resolve_reminder_context(inputs.candidate_id)- if isinstance(ctx, str):- yield WorkflowEvent(type="error", message=ctx)- return- yield WorkflowEvent(- type="step_done",- step_id="load",- summary=(- f"{ctx.candidate.full_name} for {ctx.engagement.role_title} "- f"({ctx.company_name}); reminder → {ctx.principal.full_name}."- ),- )-- yield WorkflowEvent(- type="step_start", step_id="draft", step_title="Draft rubric & outreach"- )- rag = retrieve(- query=f"executive reference check questions {ctx.engagement.role_title}",- specialist_name=_SPECIALIST,- n_builtin=3,- n_company=2,- store=store,- )- rubric = (- await route_to_specialist(- specialist_name=_SPECIALIST,- query=_rubric_prompt(ctx.engagement, ctx.candidate, inputs.reference_notes),- retrieved_knowledge=rag,- )- ).strip()- outreach = (- await route_to_specialist(- specialist_name=_SPECIALIST,- query=_outreach_prompt(ctx.engagement, ctx.candidate, ctx.company_name),- )- ).strip()- yield WorkflowEvent(- type="step_done",- step_id="draft",- summary=f"Drafted a rubric and outreach for {inputs.reference_count} reference(s).",- )-- yield WorkflowEvent(- type="step_start", step_id="schedule", step_title="Schedule reminder"- )- action_id = schedule_reminder(- ctx=ctx,- run_at=datetime.now(UTC),- intent_text=_ref_reminder_text(ctx, inputs.reference_count, rubric, outreach),- )- yield WorkflowEvent(- type="step_done",- step_id="schedule",- summary=f"Scheduled a reference-check reminder to {ctx.principal.full_name}.",- )-- yield WorkflowEvent(- type="result",- data={- "candidate_id": ctx.candidate.id,- "engagement_id": ctx.engagement.id,- "scheduled_count": 1,- "action_ids": [action_id],- },- )- yield WorkflowEvent(- type="artifact",- content=_assemble_artifact(ctx, inputs.reference_count, rubric, outreach),- )---def _ref_reminder_text(- ctx: ReminderContext, reference_count: int, rubric: str, outreach: str-) -> str:- return (- f"Reference checks ({reference_count}) for {ctx.candidate.full_name} on the "- f"{ctx.engagement.role_title} search ({ctx.company_name}). Send the principal the "- "rubric below and the ready-to-send reference-outreach so they can line up and "- "run the references themselves. Do NOT contact the references directly.\n\n"- f"--- REFERENCE RUBRIC ---\n{rubric}\n--- END RUBRIC ---\n\n"- f"--- REFERENCE OUTREACH (to send to references) ---\n{outreach}\n"- "--- END OUTREACH ---"- )---def _assemble_artifact(- ctx: ReminderContext, reference_count: int, rubric: str, outreach: str-) -> str:- lines = artifact_header(- ctx,- title="Reference Check",- disclaimer=(- "Drafts only — OE schedules a reminder to you to run the references; you "- "contact them yourself. OE never contacts references directly."- ),- meta_lines=[f"**References planned:** {reference_count} "],- )- lines += [- "## Reference Rubric",- "",- rubric or "_(none generated)_",- "",- "## Reference Outreach (to send to references)",- "",- outreach or "_(none generated)_",- ]- return "\n".join(lines).strip() + "\n"---def _rubric_prompt(engagement: Engagement, candidate: Candidate, notes: str) -> str:- notes_block = f"\n\nKnown references / focus from the principal: {notes.strip()}" if notes.strip() else ""- return (- f"Write a reference-check rubric for {candidate.full_name}, a candidate for the "- f"{engagement.role_title} role.\n\n"- f"Role must-haves / context:\n{engagement.must_haves or '(not specified)'}\n"- f"{engagement.description or ''}{notes_block}\n\n"- "Output (Markdown): 6-8 specific questions to ask every reference, each with a "- "one-line note on what answer would CONCERN us (the signal we're listening for). "- "Tie the questions to this role's must-haves and risks — not a generic 'would you "- "rehire them' list. Add a final question that invites the reference to flag "- "anything we didn't ask about."- )---def _outreach_prompt(- engagement: Engagement, candidate: Candidate, company_name: str-) -> str:- return (- f"Write a short, professional message to a REFERENCE (not the candidate) to set "- f"up a reference conversation about {candidate.full_name}, who we're considering "- f"for the {engagement.role_title} role at {company_name}.\n\n"- "Output: the message body only (no subject, no commentary). Under 120 words. "- "Briefly say why we're reaching out, that the candidate gave their name, ask for "- "20-30 minutes, and offer a few windows. Warm and respectful of their time. Sign "- "off with a [Your name] placeholder."- )diff --git a/packages/core/openexecutive/workflows/role_onboarding.py b/packages/core/openexecutive/workflows/role_onboarding.pydeleted file mode 100644index 5349756d..00000000--- a/packages/core/openexecutive/workflows/role_onboarding.py+++ /dev/null@@ -1,492 +0,0 @@-"""Role onboarding workflow — generates a role-tailored welcome brief (and an-optional daily ramp drip) for a new hire, leaning on everything the system-already knows: company profile, departments, the people roster, and company-doc-RAG.--Mirrors the section-by-section shape of ``exec_search_brief`` but oriented to-ramp-up. Role context can come from an onboarding *plan* (the normal path —-``plan_id``), or from free-text inputs for an ad-hoc run. When a plan is given,-the generated brief, reading list, and ramp segments are written back onto it.-The lead specialist is resolved per role (department specialist_key → function-map → cso), so any role — exec or IC — gets a relevant lens.-"""-from __future__ import annotations--import logging-import re-from collections.abc import AsyncIterator-from typing import Any--from pydantic import BaseModel, Field--from openexecutive.knowledge.retriever import retrieve-from openexecutive.knowledge.store import ChromaDBStore-from openexecutive.memory.company_profile import CompanyProfile-from openexecutive.onboarding.profile_builder import load_or_create_profile-from openexecutive.orchestrator.router import route_to_specialist-from openexecutive.staff_onboarding import store as onboarding_store-from openexecutive.staff_onboarding.specialists import resolve_specialist-from openexecutive.workflows.base import (- Workflow,- WorkflowEvent,- WorkflowSection,- WorkflowStepDef,-)--logger = logging.getLogger(__name__)--_RAMP_MAX = 30 # safety cap on generated daily segments per run---class RoleOnboardingInput(BaseModel):- """Inputs for the role-onboarding workflow.-- Supply ``plan_id`` to drive (and write back to) an existing onboarding plan;- otherwise supply at least ``full_name`` + ``role`` for an ad-hoc brief.- """-- plan_id: int | None = Field(- default=None,- description="Onboarding plan to generate for and write the brief back to.",- )- full_name: str = Field(- default="", description="New hire's name (used when no plan_id).",- )- role: str = Field(default="", description="Role/title, e.g. 'Fractional CFO'.")- function: str = Field(- default="",- description="Function the role sits in (engineering, sales, finance, …). "- "Helps pick the lead specialist.",- )- focus: str = Field(default="", description="Optional one-line emphasis for the brief.")- ramp_days: int | None = Field(- default=None, ge=0, le=_RAMP_MAX,- description="Number of daily ramp-drip messages to generate. None = use "- "the plan template's value; 0 = force no drip; >0 = override the template.",- )---class RoleOnboardingWorkflow(Workflow):- name = "role_onboarding"- title = "Role Onboarding"- description = (- "Generates a role-tailored onboarding brief for a new hire — company "- "landscape, the state of their function, who's who, a 30/60/90 plan, "- "and the questions to ask in week one — plus an optional daily ramp "- "drip. Tailors via the role's domain specialist and writes the brief "- "back onto the onboarding plan."- )- section = WorkflowSection.PEOPLE- estimated_minutes = 4-- def input_model(self) -> type[BaseModel]:- return RoleOnboardingInput-- def sample_inputs(self) -> dict[str, Any]:- return {- "full_name": "Priya Rao",- "role": "Fractional CFO",- "function": "finance",- "focus": "Series B readiness",- "ramp_days": 3,- }-- def steps(self) -> list[WorkflowStepDef]:- return [- WorkflowStepDef(id="context", title="Load context",- description="Company profile, roster, role context, RAG."),- WorkflowStepDef(id="company_landscape", title="Company landscape",- description="What the company is, market, priorities."),- WorkflowStepDef(id="function_state", title="Function state",- description="Current state of the function this role owns."),- WorkflowStepDef(id="people_map", title="People map",- description="Who's who and the key working relationships."),- WorkflowStepDef(id="first_90", title="30/60/90 plan",- description="Prioritized first-90-days plan."),- WorkflowStepDef(id="week_one", title="Week-one questions",- description="The sharp questions to ask in week one."),- WorkflowStepDef(id="ramp", title="Ramp drip",- description="Optional per-day ramp messages."),- WorkflowStepDef(id="assemble", title="Assemble brief",- description="Combine into one Markdown brief; save to plan."),- ]-- async def run(- self,- inputs: BaseModel,- store: ChromaDBStore,- ) -> AsyncIterator[WorkflowEvent]:- assert isinstance(inputs, RoleOnboardingInput)- ctx = _Ctx(inputs)-- # ---- context ------------------------------------------------------ yield WorkflowEvent(type="step_start", step_id="context", step_title="Load context")- _load_context(ctx, store)- if not ctx.full_name:- yield WorkflowEvent(- type="error",- message="role_onboarding needs a plan_id or a full_name to run.",- )- return- yield WorkflowEvent(- type="step_done", step_id="context",- summary=f"hire={ctx.full_name!r} role={ctx.role!r} specialist={ctx.specialist}",- )-- company_ctx = _company_block(ctx.profile)-- # ---- company_landscape (cso) ------------------------------------- yield WorkflowEvent(type="step_start", step_id="company_landscape",- step_title="Company landscape")- ctx.company_landscape = await route_to_specialist(- specialist_name="cso", query=_company_prompt(ctx),- context=company_ctx, retrieved_knowledge=ctx.rag,- )- yield WorkflowEvent(type="step_done", step_id="company_landscape",- summary=_first_line(ctx.company_landscape))-- # ---- function_state (domain specialist) -------------------------- yield WorkflowEvent(type="step_start", step_id="function_state",- step_title="Function state")- ctx.function_state = await route_to_specialist(- specialist_name=ctx.specialist, query=_function_prompt(ctx),- context=company_ctx, retrieved_knowledge=ctx.rag,- )- yield WorkflowEvent(type="step_done", step_id="function_state",- summary=_first_line(ctx.function_state))-- # ---- people_map (chro) ------------------------------------------- yield WorkflowEvent(type="step_start", step_id="people_map", step_title="People map")- ctx.people_map = await route_to_specialist(- specialist_name="chro", query=_people_prompt(ctx),- context=company_ctx + "\n\n" + ctx.roster_block, retrieved_knowledge="",- )- yield WorkflowEvent(type="step_done", step_id="people_map",- summary=_first_line(ctx.people_map))-- # ---- first_90 (domain specialist) -------------------------------- yield WorkflowEvent(type="step_start", step_id="first_90", step_title="30/60/90 plan")- ctx.first_90 = await route_to_specialist(- specialist_name=ctx.specialist, query=_first90_prompt(ctx),- context=company_ctx, retrieved_knowledge=ctx.rag,- )- yield WorkflowEvent(type="step_done", step_id="first_90",- summary=_first_line(ctx.first_90))-- # ---- week_one (domain specialist) -------------------------------- yield WorkflowEvent(type="step_start", step_id="week_one",- step_title="Week-one questions")- ctx.week_one = await route_to_specialist(- specialist_name=ctx.specialist, query=_weekone_prompt(ctx),- context=company_ctx, retrieved_knowledge="",- )- yield WorkflowEvent(type="step_done", step_id="week_one",- summary=_first_line(ctx.week_one))-- # ---- ramp (optional) --------------------------------------------- yield WorkflowEvent(type="step_start", step_id="ramp", step_title="Ramp drip")- if ctx.ramp_days:- raw = await route_to_specialist(- specialist_name=ctx.specialist, query=_ramp_prompt(ctx),- context=company_ctx, retrieved_knowledge="",- )- ctx.ramp_segments = _split_ramp(raw, ctx.ramp_days)- yield WorkflowEvent(- type="step_done", step_id="ramp",- summary=f"{len(ctx.ramp_segments)} ramp segment(s)",- )-- # ---- assemble ----------------------------------------------------- yield WorkflowEvent(type="step_start", step_id="assemble", step_title="Assemble brief")- artifact = _assemble(ctx)- if ctx.plan_id is not None:- # Only (re)write ramp fields when this run actually produced a drip,- # so re-running just to refresh the brief can't wipe an in-progress- # ramp's segments/index.- ramp_kwargs: dict[str, Any] = {}- if ctx.ramp_days and ctx.ramp_segments:- ramp_kwargs = {"ramp_segments": ctx.ramp_segments, "ramp_next_index": 0}- try:- onboarding_store.update_plan(- ctx.plan_id,- brief_artifact=artifact,- reading_list=ctx.reading_list,- **ramp_kwargs,- )- except Exception:- logger.exception("role_onboarding: failed to write brief to plan %s",- ctx.plan_id)- yield WorkflowEvent(type="step_done", step_id="assemble",- summary=f"{len(artifact)} chars; saved={ctx.plan_id is not None}")-- yield WorkflowEvent(- type="result",- data={- "plan_id": ctx.plan_id,- "specialist": ctx.specialist,- "ramp_segments": ctx.ramp_segments,- "reading_list": ctx.reading_list,- },- )- yield WorkflowEvent(type="artifact", content=artifact)- yield WorkflowEvent(type="done")---class _Ctx:- def __init__(self, inputs: RoleOnboardingInput) -> None:- self.inputs = inputs- self.plan_id: int | None = inputs.plan_id- self.full_name: str = inputs.full_name- self.role: str = inputs.role- self.function: str = inputs.function- self.focus: str = inputs.focus- # None until resolved in _load_context (caller value vs template vs 0).- self.ramp_days: int | None = inputs.ramp_days- self.department: str = ""- self.start_date: str = ""- self.profile: CompanyProfile | None = None- self.specialist: str = "cso"- self.rag: str = ""- self.roster_block: str = ""- self.reading_list: list[str] = []- self.company_landscape: str = ""- self.function_state: str = ""- self.people_map: str = ""- self.first_90: str = ""- self.week_one: str = ""- self.ramp_segments: list[str] = []---def _load_context(ctx: _Ctx, store: ChromaDBStore) -> None:- """Resolve role context from the plan (if any) + company profile + roster."""- if ctx.plan_id is not None:- plan = onboarding_store.get_plan(ctx.plan_id)- if plan is not None:- ctx.full_name = plan.full_name or ctx.full_name- ctx.role = plan.role or ctx.role- ctx.start_date = plan.start_date- if plan.template_name:- tmpl = onboarding_store.get_template(plan.template_name)- if tmpl is not None:- ctx.department = tmpl.department- # Caller value wins; fall back to the template's only when- # the caller didn't specify (None). An explicit 0 stays 0.- if ctx.ramp_days is None:- ctx.ramp_days = min(tmpl.ramp_days, _RAMP_MAX)-- # No value from caller or template → no drip.- if ctx.ramp_days is None:- ctx.ramp_days = 0-- try:- ctx.profile = load_or_create_profile()- except Exception:- logger.exception("role_onboarding: load_or_create_profile failed")- ctx.profile = None-- ctx.specialist = resolve_specialist(- role=ctx.role, function=ctx.function, department=ctx.department,- )-- try:- ctx.rag = retrieve(- query=f"onboarding ramp {ctx.role} {ctx.function} first 90 days",- specialist_name=ctx.specialist, n_builtin=5, n_company=3, store=store,- )- except Exception:- logger.exception("role_onboarding: retrieve failed")- ctx.rag = ""-- ctx.roster_block = _roster_block()- ctx.reading_list = _reading_list(ctx.specialist, store)---def _roster_block() -> str:- try:- from openexecutive.people.store import list_people-- people = list_people()- except Exception:- logger.exception("role_onboarding: list_people failed")- return ""- lines: list[str] = []- for p in people[:50]:- role = f" — {p.role}" if p.role else ""- depts = f" [{', '.join(p.department_slugs)}]" if p.department_slugs else ""- lines.append(f"- {p.full_name}{role}{depts}")- if not lines:- return ""- return "CURRENT TEAM:\n" + "\n".join(lines)---def _reading_list(specialist: str, store: ChromaDBStore) -> list[str]:- """Best-effort: distinct company-doc filenames relevant to this role."""- try:- results = store.query(- query_text=f"onboarding {specialist} role overview",- collection=ChromaDBStore.COMPANY_COLLECTION,- n_results=8,- )- except Exception:- logger.exception("role_onboarding: reading-list query failed")- return []- seen: list[str] = []- for item in results or []:- name = (item.get("metadata") or {}).get("filename")- if name and name not in seen:- seen.append(name)- return seen[:5]---def _company_block(profile: CompanyProfile | None) -> str:- if profile is None or profile.is_empty():- return ""- return profile.to_prompt_block()---def _focus_line(ctx: _Ctx) -> str:- return f"\n\nEmphasis for this hire: {ctx.focus}" if ctx.focus else ""---def _company_prompt(ctx: _Ctx) -> str:- return (- f"A new hire — {ctx.full_name}, joining as {ctx.role or 'a new team member'} — "- "needs to understand this company fast. Write the **Company Landscape** "- "section of their onboarding brief.{focus}\n\n"- "Output (Markdown):\n"- "## Company Landscape\n"- "### What we do & where we are\n2-4 sentences: the business, stage, model.\n"- "### Market & competition\nThe competitive picture they should hold.\n"- "### Strategic priorities\nThe few company priorities their work ladders up to.\n"- ).replace("{focus}", _focus_line(ctx))---def _function_prompt(ctx: _Ctx) -> str:- return (- f"You are the functional leader closest to {ctx.full_name}'s role "- f"({ctx.role or 'this role'}). Write the **State of the Function** they're "- "inheriting — be concrete and honest.{focus}\n\n"- "Output (Markdown):\n"- "## State of Your Function\n"- "### What's working\n2-4 bullets.\n"- "### What's broken or unfinished\n2-4 bullets.\n"- "### The metrics that matter\nThe few numbers they should track from day one.\n"- ).replace("{focus}", _focus_line(ctx))---def _people_prompt(ctx: _Ctx) -> str:- return (- f"Using the team roster provided, write the **People Map** for "- f"{ctx.full_name} ({ctx.role or 'new hire'}): who they'll work with most "- "and why. If the roster is empty, give the archetypal stakeholders for "- "this role instead.\n\n"- "Output (Markdown):\n"- "## People Map\n"- "### Key relationships\n"- "Bullet list: each person/role and what to align with them on.\n"- "### First intro 1:1s to schedule\nWho to meet in week one, and why.\n"- )---def _first90_prompt(ctx: _Ctx) -> str:- return (- f"Draft a prioritized **30/60/90-Day Plan** for {ctx.full_name} as "- f"{ctx.role or 'the new hire'}, grounded in the company's strategic "- "priorities and the state of their function.{focus}\n\n"- "Output (Markdown):\n"- "## 30 / 60 / 90 Day Plan\n"- "### First 30 days — learn & stabilize\n3-5 bullets.\n"- "### Days 31-60 — own & improve\n3-5 bullets.\n"- "### Days 61-90 — deliver\n3-5 bullets, each with a visible outcome.\n"- ).replace("{focus}", _focus_line(ctx))---def _weekone_prompt(ctx: _Ctx) -> str:- return (- f"List the sharp **Questions {ctx.full_name} Should Ask in Week One** — "- "the ones that surface how things really work here, not generic ones.\n\n"- "Output (Markdown):\n"- "## Questions to Ask in Week One\n"- "5-8 specific questions, each with one line on why it matters.\n"- )---def _ramp_prompt(ctx: _Ctx) -> str:- return (- f"Write a {ctx.ramp_days}-day **ramp drip** for {ctx.full_name} "- f"({ctx.role or 'new hire'}): one short, friendly daily message (2-4 "- "sentences) they'll receive on each of their first business days. Each "- "should give one concrete thing to do or learn that day, building on the "- "prior days.\n\n"- f"Output EXACTLY {ctx.ramp_days} messages, each on its own block, prefixed "- "with 'DAY n:' (e.g. 'DAY 1:'). No other headers."- )---_RAMP_RE = re.compile(r"^\s*DAY\s*\d+\s*:\s*", re.IGNORECASE | re.MULTILINE)---def _split_ramp(raw: str, expected: int) -> list[str]:- """Split the model's ramp output into per-day segments.-- Primary parse splits on the ``DAY n:`` markers; if that yields nothing- usable, fall back to splitting on blank lines. Either way the result is- capped at ``expected`` so a chatty model can't over-produce.- """- if not raw or not raw.strip():- return []- # Use the DAY-marker split when the markers are actually present (so a valid- # single-day drip isn't mistaken for a parse failure); otherwise fall back to- # paragraph splitting.- if _RAMP_RE.search(raw):- parts = [p.strip() for p in _RAMP_RE.split(raw) if p.strip()]- else:- parts = [p.strip() for p in re.split(r"\n\s*\n", raw) if p.strip()]- return parts[:expected]---def _first_line(text: str, max_len: int = 140) -> str:- if not text:- return "(empty)"- line = text.strip().split("\n", 1)[0].lstrip("# ").strip()- return line[: max_len - 1] + "…" if len(line) > max_len else line---def _ensure_heading(text: str, expected_heading: str) -> str:- stripped = (text or "").strip()- if not stripped:- return f"{expected_heading}\n\n_(No content generated for this section.)_"- first_line = stripped.split("\n", 1)[0]- if first_line.startswith("##"):- return stripped- return f"{expected_heading}\n\n{stripped}"---def _assemble(ctx: _Ctx) -> str:- title_role = f" — {ctx.role}" if ctx.role else ""- parts = [- f"# Onboarding Brief: {ctx.full_name}{title_role}",- "",- _ensure_heading(ctx.company_landscape, "## Company Landscape"),- "",- _ensure_heading(ctx.function_state, "## State of Your Function"),- "",- _ensure_heading(ctx.people_map, "## People Map"),- "",- _ensure_heading(ctx.first_90, "## 30 / 60 / 90 Day Plan"),- "",- _ensure_heading(ctx.week_one, "## Questions to Ask in Week One"),- ]- if ctx.reading_list:- parts += ["", "## Suggested Reading", ""]- parts += [f"- {name}" for name in ctx.reading_list]- parts += [- "",- "---",- "*Drafted by Open Executive from your company context. Review with the "- "hiring manager before sharing.*",- ]- return "\n".join(parts).strip() + "\n"---__all__ = ["RoleOnboardingInput", "RoleOnboardingWorkflow"]diff --git a/packages/core/tests/unit/test_action_chips.py b/packages/core/tests/unit/test_action_chips.pyindex 79d61ef8..675658a8 100644--- a/packages/core/tests/unit/test_action_chips.py+++ b/packages/core/tests/unit/test_action_chips.py@@ -135,66 +135,14 @@ def test_set_department_head_chip_with_link() -> None:assert chip["link"] == "/departments/marketing"-def test_set_candidate_stage_chip_with_link() -> None:+def test_chip_suppressed_on_not_found() -> None:+ # The generic `status: not_found` suppression: a write that matched no row+ # changed nothing, so it must not paint a green ✓. Here archive_person+ # against an id that doesn't exist (people_tools returns that shape).chip = summarize_action(- tool_name="set_candidate_stage",- tool_input={"candidate_id": 12, "stage": "interviewed"},- tool_result=json.dumps({"status": "ok", "candidate_id": 12, "stage": "interviewed"}),- )- assert chip is not None- assert chip["summary"] == "Moved candidate #12 → interviewed"- assert chip["link"] == "/talent/candidates/12"---def test_create_engagement_chip_with_link() -> None:- chip = summarize_action(- tool_name="create_engagement",- tool_input={"role_title": "VP Drilling", "department": "Drilling"},- tool_result=json.dumps({"status": "ok", "engagement": {"id": 9}}),- )- assert chip is not None- assert chip["summary"] == "Opened search: VP Drilling"- # In-house model: the chip links to the searches list, not a client page.- assert chip["link"] == "/talent/searches"---def test_create_candidate_chip_with_link() -> None:- chip = summarize_action(- tool_name="create_candidate",- tool_input={"engagement_id": 9, "full_name": "Dana Wells"},- tool_result=json.dumps({"status": "ok", "candidate": {"id": 3}}),- )- assert chip is not None- assert chip["summary"] == "Added candidate Dana Wells"- assert chip["link"] == "/talent/engagements/9"---def test_create_candidate_chip_suppressed_on_not_found() -> None:- # The generic `status: not_found` suppression still applies — here a- # create_candidate against an engagement that doesn't exist returns no ✓.- chip = summarize_action(- tool_name="create_candidate",- tool_input={"engagement_id": 9999, "full_name": "Ghost"},- tool_result=json.dumps({"status": "not_found", "engagement_id": 9999}),- )- assert chip is None---def test_start_talent_workflow_chip() -> None:- chip = summarize_action(- tool_name="start_talent_workflow",- tool_input={"workflow": "candidate_screen", "inputs": {"engagement_id": 1, "candidate_id": 2}},- tool_result=json.dumps({"ok": True, "run_id": "abc"}),- )- assert chip is not None- assert chip["summary"] == "Ran candidate screen"---def test_start_talent_workflow_chip_suppressed_on_error() -> None:- chip = summarize_action(- tool_name="start_talent_workflow",- tool_input={"workflow": "candidate_screen", "inputs": {}},- tool_result=json.dumps({"error": "invalid inputs"}),+ tool_name="archive_person",+ tool_input={"person_id": 9999},+ tool_result=json.dumps({"status": "not_found", "person_id": 9999}),)assert chip is None@@ -350,12 +298,6 @@ _KNOWN_READ_ONLY_TOOLS: frozenset[str] = frozenset({"load_skill",# mcp_gateway"search_tools",- # talent_tools — pipeline reads (writes are in SIDE_EFFECTING_TOOLS)- "list_engagements",- "list_candidates",- "get_candidate",- "match_candidates",- "list_offers",# workflow_run_tools — catalog read (run_workflow is in SIDE_EFFECTING_TOOLS)"list_workflows",})@@ -374,7 +316,6 @@ def _all_registered_tool_names() -> set[str]:from openexecutive.orchestrator.people_tools import PEOPLE_TOOL_HANDLERSfrom openexecutive.orchestrator.schedule_tools import SCHEDULE_TOOL_HANDLERSfrom openexecutive.orchestrator.skills_tools import SKILL_TOOL_HANDLERS- from openexecutive.orchestrator.talent_tools import TALENT_TOOL_HANDLERSfrom openexecutive.orchestrator.workflow_run_tools import WORKFLOW_RUN_TOOL_HANDLERSreturn (@@ -385,7 +326,6 @@ def _all_registered_tool_names() -> set[str]:| set(BROADCAST_TOOL_HANDLERS)| set(DRAFT_ARTIFACT_TOOL_HANDLERS)| set(MCP_TOOL_NAMES)- | set(TALENT_TOOL_HANDLERS)| set(WORKFLOW_RUN_TOOL_HANDLERS)# `create_alert` is in chat module rather than a HANDLERS dict.| {"create_alert"}diff --git a/packages/core/tests/unit/test_architecture_facts.py b/packages/core/tests/unit/test_architecture_facts.pyindex 6c8c826b..da81ae93 100644--- a/packages/core/tests/unit/test_architecture_facts.py+++ b/packages/core/tests/unit/test_architecture_facts.py@@ -47,14 +47,6 @@ def test_sections_have_unique_stable_ids() -> None:# `user_guide` — documents the /guide user-guide surface (plain-language# per-feature overviews). New top-level module under packages/core."user_guide",- # `talent` — the talent-intelligence / executive-search vertical- # (clients/engagements/candidates, matching graph, recruiting workflows,- # /talent UI). New top-level module under packages/core.- "talent",- # `staff_onboarding` — onboarding a person INTO the company (templates,- # per-hire plans + task checklists, role_onboarding brief workflow, ramp- # drip, chat + /today integration). New top-level module.- "staff_onboarding",# `clients` — named client-company slots for fractional / multi-client# use (save-back switching, per-client MCP config). New top-level module."clients",diff --git a/packages/core/tests/unit/test_briefing_context_render.py b/packages/core/tests/unit/test_briefing_context_render.pyindex 58ce496f..1a90832e 100644--- a/packages/core/tests/unit/test_briefing_context_render.py+++ b/packages/core/tests/unit/test_briefing_context_render.py@@ -26,7 +26,6 @@ def _today() -> dict:_proposal(3, hours_ago=90),],"people": [{"full_name": "Dana", "role": "CFO", "awaiting_count": 1, "soonest_sla_at": "x"}],- "talent": [],}diff --git a/packages/core/tests/unit/test_briefing_narrative_cache.py b/packages/core/tests/unit/test_briefing_narrative_cache.pyindex 78995641..7cebdbb6 100644--- a/packages/core/tests/unit/test_briefing_narrative_cache.py+++ b/packages/core/tests/unit/test_briefing_narrative_cache.py@@ -57,20 +57,6 @@ def test_hash_changes_when_proposals_change() -> None:narrative_cache.build_narrative_input_hash(changed)-def test_hash_changes_when_talent_pipeline_changes() -> None:- base = {- "proposals": [], "departments": [], "people": [],- "talent": [{"engagement_id": 1, "needs_screening": 2, "offers_out": 0, "stalled_count": 0}],- }- # An offer landing on the same search must re-write the brief.- changed = {- "proposals": [], "departments": [], "people": [],- "talent": [{"engagement_id": 1, "needs_screening": 2, "offers_out": 1, "stalled_count": 0}],- }- assert narrative_cache.build_narrative_input_hash(base) != \- narrative_cache.build_narrative_input_hash(changed)--def test_hash_differs_by_scope() -> None:# Same content, different viewer → distinct cache keys (no cross-user reuse).data = {"proposals": [], "departments": [], "people": []}diff --git a/packages/core/tests/unit/test_candidate_outreach_workflow.py b/packages/core/tests/unit/test_candidate_outreach_workflow.pydeleted file mode 100644index 8380b5ac..00000000--- a/packages/core/tests/unit/test_candidate_outreach_workflow.py+++ /dev/null@@ -1,159 +0,0 @@-"""Tests for the CandidateOutreachWorkflow (Phase 3 recruiting automation)."""-from __future__ import annotations--import asyncio-from pathlib import Path-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.talent import store as talent_store-from openexecutive.workflows.candidate_outreach import (- CandidateOutreachInput,- CandidateOutreachWorkflow,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- """One shared episodic_memory.db for talent + people + scheduled_actions."""- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- return path---CANDIDATE_EMAIL = "[email protected]"---def _seed_candidate(db: Path) -> int:- eid = talent_store.upsert_engagement(- role_title="VP Drilling", department="Drilling",- must_haves="cycle-tested upstream lead",- )- # Candidate HAS an email so the "never route to the candidate" assertion is- # a real check, not trivially true.- return talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", current_title="Drilling Director",- current_company="Permian Co", email=CANDIDATE_EMAIL,- )---def _seed_principal(*, email: str = "[email protected]", preferred: str = "email") -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email=email,- preferred_channel=preferred, # type: ignore[arg-type]- )---def _run(candidate_id: int, follow_up_count: int = 2) -> list:- workflow = CandidateOutreachWorkflow()- inputs = CandidateOutreachInput(- candidate_id=candidate_id, follow_up_count=follow_up_count, follow_up_interval_days=3- )- events: list = []-- # Mock returns exactly one body per expected specialist call (first touch +- # one per follow-up). Sized to the call count so an extra/missing call would- # raise StopAsyncIteration rather than passing silently.- bodies = ["FIRST_TOUCH_BODY"] + [f"FOLLOWUP_{k}_BODY" for k in range(1, follow_up_count + 1)]- mock_specialist = AsyncMock(side_effect=bodies)-- async def _collect() -> None:- async for ev in workflow.run(inputs=inputs, store=MagicMock()):- events.append(ev)-- with patch(- "openexecutive.workflows.candidate_outreach.route_to_specialist",- mock_specialist,- ), patch("openexecutive.workflows.candidate_outreach.retrieve", return_value=""):- asyncio.run(_collect())- # When the run reaches drafting, exactly 1 + follow_up_count calls are made.- if events and events[-1].type != "error":- assert mock_specialist.await_count == len(bodies)- return events---def test_schedules_reminders_to_principal_not_candidate(db: Path) -> None:- cand_id = _seed_candidate(db)- principal_id = _seed_principal(email="[email protected]")- events = _run(cand_id, follow_up_count=2)-- assert "error" not in [e.type for e in events]- result = next(e for e in events if e.type == "result")- assert result.data["scheduled_count"] == 3 # first + 2 follow-ups-- actions = episodic.list_scheduled_actions()- assert len(actions) == 3- for a in actions:- # Reminders go to the PRINCIPAL, never the candidate.- assert a.assigned_to_person_id == principal_id- assert a.channel == "email"- assert a.channel_ref == "[email protected]"- # Real check now that the candidate HAS an email: no reminder is routed- # to the candidate.- assert a.channel_ref != CANDIDATE_EMAIL- assert "Do NOT contact the candidate directly" in a.intent_text- assert "Dana Cole" in a.intent_text-- # The drafted bodies are carried in the reminders.- intents = " ".join(a.intent_text for a in actions)- assert "FIRST_TOUCH_BODY" in intents- assert "FOLLOWUP_1_BODY" in intents- assert "FOLLOWUP_2_BODY" in intents---def test_artifact_contains_sequence(db: Path) -> None:- cand_id = _seed_candidate(db)- _seed_principal()- events = _run(cand_id, follow_up_count=1)- artifact = next(e for e in events if e.type == "artifact")- assert "Outreach Sequence — Dana Cole" in artifact.content- assert "First touch" in artifact.content- assert "Follow-up 1" in artifact.content- assert "FIRST_TOUCH_BODY" in artifact.content---def test_zero_follow_ups_schedules_only_first(db: Path) -> None:- cand_id = _seed_candidate(db)- _seed_principal()- events = _run(cand_id, follow_up_count=0)- assert next(e for e in events if e.type == "result").data["scheduled_count"] == 1- assert len(episodic.list_scheduled_actions()) == 1---def test_unknown_candidate_errors(db: Path) -> None:- _seed_principal()- events = _run(9999)- assert events[-1].type == "error"- assert "Candidate 9999 not found" in events[-1].message- assert episodic.list_scheduled_actions() == []---def test_no_principal_errors_and_schedules_nothing(db: Path) -> None:- cand_id = _seed_candidate(db)- # No principal seeded.- events = _run(cand_id)- assert events[-1].type == "error"- assert "No principal configured" in events[-1].message- assert episodic.list_scheduled_actions() == []---def test_principal_without_channel_errors(db: Path) -> None:- cand_id = _seed_candidate(db)- # Principal with no email/slack/etc. → no reachable channel.- people_store.upsert_person(full_name="Alex", is_principal=True, preferred_channel="any")- events = _run(cand_id)- assert events[-1].type == "error"- assert "no reachable channel" in events[-1].message- assert episodic.list_scheduled_actions() == []---# (principal-channel resolution is covered in test_talent_reminders.py, where-# the helper now lives.)diff --git a/packages/core/tests/unit/test_candidate_screen_workflow.py b/packages/core/tests/unit/test_candidate_screen_workflow.pydeleted file mode 100644index e97f4230..00000000--- a/packages/core/tests/unit/test_candidate_screen_workflow.py+++ /dev/null@@ -1,150 +0,0 @@-"""Tests for the CandidateScreenWorkflow."""-from __future__ import annotations--from pathlib import Path-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage-from openexecutive.workflows.candidate_screen import (- CandidateScreenInput,- CandidateScreenWorkflow,- _parse_fit_score,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---_ASSESSMENT = (- "Fit score: 84/100 — directly led drilling through the 2020 downturn.\n\n"- "**Evidence for fit**\n- 12 years upstream, cycle-tested.\n\n"- "**Recommendation:** advance."-)---def _run(engagement_id: int, candidate_id: int) -> list:- workflow = CandidateScreenWorkflow()- inputs = CandidateScreenInput(engagement_id=engagement_id, candidate_id=candidate_id)- store = MagicMock()- events: list = []-- async def _collect() -> None:- async for event in workflow.run(inputs=inputs, store=store):- events.append(event)-- import asyncio-- with patch(- "openexecutive.workflows.candidate_screen.route_to_specialist",- new_callable=AsyncMock,- return_value=_ASSESSMENT,- ), patch(- "openexecutive.workflows.candidate_screen.retrieve", return_value=""- ):- asyncio.run(_collect())- return events---def _seed(db: Path) -> tuple[int, int]:- eid = talent_store.upsert_engagement(- role_title="VP Drilling", department="Drilling",- must_haves="cycle-tested upstream lead",- )- cand_id = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- return eid, cand_id---def test_screen_persists_score_and_advances(db: Path) -> None:- eid, cand_id = _seed(db)- events = _run(eid, cand_id)-- types = [e.type for e in events]- assert "artifact" in types- assert "error" not in types-- artifact = next(e for e in events if e.type == "artifact")- assert "Dana Cole" in artifact.content- assert "84/100" in artifact.content-- result = next(e for e in events if e.type == "result")- assert result.data["fit_score"] == 84- assert result.data["recorded"] is True-- cand = talent_store.get_candidate(cand_id)- assert cand is not None- assert cand.fit_score == 84- assert cand.stage == CandidateStage.SCREENED---def test_screen_unknown_candidate_errors(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="CFO", department="Finance")- events = _run(eid, 9999)- assert events[-1].type == "error"- assert "Candidate 9999 not found" in events[-1].message---def test_screen_candidate_engagement_mismatch_errors(db: Path) -> None:- eid1 = talent_store.upsert_engagement(role_title="CFO", department="Finance")- eid2 = talent_store.upsert_engagement(role_title="COO", department="Ops")- cand_id = talent_store.upsert_candidate(engagement_id=eid2, full_name="Dana")- events = _run(eid1, cand_id) # screen against the wrong engagement- assert events[-1].type == "error"- assert "belongs to engagement" in events[-1].message---def test_parse_fit_score_variants() -> None:- # Only the mandated N/100 form is parsed.- assert _parse_fit_score("Fit score: 84/100 — strong.") == 84- assert _parse_fit_score("I'd put them at 73/100 overall.") == 73- assert _parse_fit_score("") is None- assert _parse_fit_score("No number anywhere here.") is None- # Bare numbers without a /100 denominator are deliberately NOT parsed —- # recording a wrong score is worse than skipping (caller emits artifact,- # persists nothing).- assert _parse_fit_score("Fit score: 82 — strong, no denominator.") is None- assert _parse_fit_score("Overall score of 60.") is None- # Out-of-range guarded: 250 is rejected, the valid /100 form wins instead.- assert _parse_fit_score("ranked 250th; fit 45/100") == 45- assert _parse_fit_score("I'd give 150/100 if I could; realistic fit: 82/100") == 82- # Criteria-count language must not be mistaken for the score.- assert _parse_fit_score("Fit score: 3/5 must-haves met; overall 82/100") == 82- assert _parse_fit_score("Fit score: 4 of 5 met. I'd rate 75 overall.") is None- # Qualifying text before the score doesn't capture the percentage.- assert _parse_fit_score("Fit score: top 10% of candidates. Score: 82/100.") == 82---def test_screen_no_score_skips_persistence(db: Path) -> None:- eid, cand_id = _seed(db)- workflow = CandidateScreenWorkflow()- inputs = CandidateScreenInput(engagement_id=eid, candidate_id=cand_id)- events: list = []-- async def _collect() -> None:- async for event in workflow.run(inputs=inputs, store=MagicMock()):- events.append(event)-- import asyncio-- with patch(- "openexecutive.workflows.candidate_screen.route_to_specialist",- new_callable=AsyncMock,- return_value="A qualitative read with no number at all.",- ), patch("openexecutive.workflows.candidate_screen.retrieve", return_value=""):- asyncio.run(_collect())-- result = next(e for e in events if e.type == "result")- assert result.data["fit_score"] is None- assert result.data["recorded"] is False- # Candidate stays a lead, no score recorded.- cand = talent_store.get_candidate(cand_id)- assert cand is not None- assert cand.fit_score is None- assert cand.stage == CandidateStage.LEADdiff --git a/packages/core/tests/unit/test_chat_route_page_context.py b/packages/core/tests/unit/test_chat_route_page_context.pyindex c8443c04..48840893 100644--- a/packages/core/tests/unit/test_chat_route_page_context.py+++ b/packages/core/tests/unit/test_chat_route_page_context.py@@ -182,9 +182,9 @@ def test_unknown_guide_section_is_skipped() -> None:"""A guide id with no prebuilt file must not break the block — explaintier still works from route + title."""block = _build_page_context_block(- PageContext(route="/talent", title="Talent", guide_section_id="no-such-section")+ PageContext(route="/people", title="People", guide_section_id="no-such-section"))- assert 'PAGE: /talent — "Talent"' in block+ assert 'PAGE: /people — "People"' in blockassert "USER GUIDE" not in blockdiff --git a/packages/core/tests/unit/test_client_slots.py b/packages/core/tests/unit/test_client_slots.pyindex 1db5c43b..2a046376 100644--- a/packages/core/tests/unit/test_client_slots.py+++ b/packages/core/tests/unit/test_client_slots.py@@ -1,8 +1,8 @@"""Client-slot round-trip tests: save → switch → switch back must be lossless.The slot mechanism's whole contract is "a slot is a faithful save file" —-these tests prove the SQLite state (decisions, scheduled actions, onboarding-plans), the company artifacts (profile, docs, mcp_servers.json), and the+these tests prove the SQLite state (decisions, scheduled actions, the people+roster), the company artifacts (profile, docs, mcp_servers.json), and theoperator-level tables behave correctly across switches. The vector andHoncho layers are stubbed: they're side effects of a switch, not part of theround-trip contract under test.@@ -45,7 +45,6 @@ def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:from openexecutive.departments import store as dept_storefrom openexecutive.memory import episodicfrom openexecutive.people import store as people_store- from openexecutive.staff_onboarding import store as onboarding_storemonkeypatch.setattr(episodic, "DB_PATH", db_path)monkeypatch.setattr(people_store, "DB_PATH", db_path)@@ -53,7 +52,6 @@ def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:episodic.initialize_db(db_path)people_store.initialize_db(db_path)dept_store.initialize_db(db_path)- onboarding_store.initialize_db(db_path)async def _no_vector(_settings: Any, _app_state: Any) -> int:return 0@@ -123,19 +121,15 @@ async def test_create_from_current_captures_state_and_activates(env: SimpleNamesasync def test_switch_round_trip_is_lossless(env: SimpleNamespace) -> None:- # Client A: full company with an onboarding plan and a scheduled action.+ # Client A: full company with a roster entry and a scheduled action._seed_live_company(env, "Acme Corp")- from openexecutive.staff_onboarding import store as onboarding_store- from openexecutive.staff_onboarding.models import OnboardingTemplate, TaskSpec-- onboarding_store.upsert_template(- OnboardingTemplate(- name="cfo_ramp",- title="Fractional CFO ramp",- department="finance",- task_specs=[TaskSpec(title="Cash review")],- ),- env.db_path,+ from openexecutive.people import store as people_store++ people_store.upsert_person(+ full_name="Dana Acme",+ role="CFO",+ email="[email protected]",+ db_path=env.db_path,)conn = sqlite3.connect(str(env.db_path))conn.execute(@@ -154,6 +148,8 @@ async def test_switch_round_trip_is_lossless(env: SimpleNamespace) -> None:await activate_client_slot(env.settings, "beta_inc")assert get_active_client(env.settings) == "beta_inc"assert _decision_summaries(env.db_path) == []+ # Acme's roster must not leak into Beta — the other half of the witness.+ assert people_store.find_person_by_email("[email protected]", env.db_path) is Noneassert not env.settings.mcp_servers_config_path.exists()assert "Beta Inc" in env.settings.company_profile_path.read_text()@@ -168,7 +164,7 @@ async def test_switch_round_trip_is_lossless(env: SimpleNamespace) -> None:assert (env.company / "docs" / "strategy.md").exists()assert not (env.company / "docs" / "beta.md").exists()assert env.settings.mcp_servers_config_path.exists()- assert onboarding_store.get_template("cfo_ramp", env.db_path) is not None+ assert people_store.find_person_by_email("[email protected]", env.db_path) is not Noneconn = sqlite3.connect(str(env.db_path))actions = conn.execute("SELECT intent_text FROM scheduled_actions").fetchall()conn.close()diff --git a/packages/core/tests/unit/test_dynamic_workflow_run.py b/packages/core/tests/unit/test_dynamic_workflow_run.pyindex cceb513c..563d670c 100644--- a/packages/core/tests/unit/test_dynamic_workflow_run.py+++ b/packages/core/tests/unit/test_dynamic_workflow_run.py@@ -173,3 +173,106 @@ async def test_run_reports_placeholder_error(monkeypatch: pytest.MonkeyPatch) ->events = await _collect(wf, bad_inputs)errors = [e for e in events if getattr(e, "type", None) == "error"]assert errors and "placeholder error" in errors[0].message+++def _never_route(called: list[str]) -> Any:+ async def fake_route(**kwargs: Any) -> str: # pragma: no cover - must not run+ called.append(kwargs["specialist_name"])+ return "Unknown specialist: talent"+ return fake_route+++async def test_run_fails_loudly_when_stored_specialist_no_longer_exists(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Definitions are validated on create/update, not on load, so a stored+ definition can name a specialist that has since been removed (the `talent`+ key). The run must emit an error event before doing anything — not feed+ "Unknown specialist" into the synthesis step as if it were analysis."""+ called: list[str] = []+ monkeypatch.setattr(dyn, "route_to_specialist", _never_route(called))+ d = _def(+ steps=[+ {"kind": "specialist", "id": "screen", "title": "Screen",+ "specialist": "talent", "goal": "Assess {topic}."},+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},+ ],+ )+ wf = DynamicWorkflow(d)+ inputs = wf.input_model()(topic="a candidate")+ events = await _collect(wf, inputs)+ types = [getattr(e, "type", None) for e in events]+ # Pre-flight: the error is the ONLY event — not even the context step ran.+ assert types == ["error"]+ assert "'talent'" in events[0].message and "'screen'" in events[0].message+ assert "artifact" not in types+ assert called == []+++async def test_run_fails_when_synthesis_step_names_missing_specialist(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A synthesis step with `instructions` consults its own `specialist` and+ returns that consult as the WHOLE artifact — the same hole, one field over."""+ called: list[str] = []+ monkeypatch.setattr(dyn, "route_to_specialist", _never_route(called))+ d = _def(+ steps=[+ {"kind": "synthesis", "id": "assemble", "title": "Assemble",+ "instructions": "Polish this.", "specialist": "talent"},+ ],+ )+ wf = DynamicWorkflow(d)+ events = await _collect(wf, wf.input_model()(topic="x"))+ assert [getattr(e, "type", None) for e in events] == ["error"]+ assert "'assemble'" in events[0].message+ assert called == []+++async def test_synthesis_without_instructions_ignores_its_specialist_field(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Without `instructions` the synthesis step never consults anyone, so a+ stale default there must not fail an otherwise-valid workflow."""+ async def fake_route(**kwargs: Any) -> str:+ return "analysis"+ monkeypatch.setattr(dyn, "route_to_specialist", fake_route)+ d = _def(+ steps=[+ {"kind": "specialist", "id": "research", "title": "Research",+ "specialist": "cso", "goal": "Analyze {topic}."},+ {"kind": "synthesis", "id": "assemble", "title": "Assemble",+ "specialist": "talent"},+ ],+ )+ wf = DynamicWorkflow(d)+ events = await _collect(wf, wf.input_model()(topic="x"))+ types = [getattr(e, "type", None) for e in events]+ assert "error" not in types and "artifact" in types+++async def test_stale_specialist_fails_before_an_earlier_approval_gate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The check is pre-flight: a gate BEFORE the stale step must not pause the+ run and DM a human for sign-off on a workflow that cannot complete."""+ called: list[str] = []+ monkeypatch.setattr(dyn, "route_to_specialist", _never_route(called))+ d = _def(+ steps=[+ {"kind": "approval_gate", "id": "gate", "title": "Gate",+ "person_id": 7, "question": "Proceed with {topic}?"},+ {"kind": "specialist", "id": "screen", "title": "Screen",+ "specialist": "talent", "goal": "Assess {topic}."},+ {"kind": "synthesis", "id": "assemble", "title": "Assemble"},+ ],+ )+ wf = DynamicWorkflow(d)+ events = await _collect(wf, wf.input_model()(topic="x"))+ assert not any(isinstance(e, WaitForHumanEvent) for e in events)+ assert [getattr(e, "type", None) for e in events] == ["error"]+ assert called == []diff --git a/packages/core/tests/unit/test_exec_search_brief_registered.py b/packages/core/tests/unit/test_exec_search_brief_registered.pynew file mode 100644index 00000000..3393b5df--- /dev/null+++ b/packages/core/tests/unit/test_exec_search_brief_registered.py@@ -0,0 +1,14 @@+"""`exec_search_brief` survived the talent-vertical removal: it is an advisory+hiring brief from the CHRO, not part of the candidate pipeline."""+from __future__ import annotations++from openexecutive.workflows import WORKFLOW_REGISTRY+from openexecutive.workflows.exec_search_brief import ExecSearchBriefWorkflow+++def test_exec_search_brief_is_registered_and_builds_inputs() -> None:+ wf = WORKFLOW_REGISTRY["exec_search_brief"]+ assert isinstance(wf, ExecSearchBriefWorkflow)+ fields = wf.input_model().model_fields+ assert "role_title" in fields+ assert not wf.meta().is_customdiff --git a/packages/core/tests/unit/test_interview_coordination_workflow.py b/packages/core/tests/unit/test_interview_coordination_workflow.pydeleted file mode 100644index 57348dab..00000000--- a/packages/core/tests/unit/test_interview_coordination_workflow.py+++ /dev/null@@ -1,105 +0,0 @@-"""Tests for the InterviewCoordinationWorkflow."""-from __future__ import annotations--import asyncio-from pathlib import Path-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.talent import store as talent_store-from openexecutive.workflows.interview_coordination import (- InterviewCoordinationInput,- InterviewCoordinationWorkflow,-)--CANDIDATE_EMAIL = "[email protected]"---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- return path---def _seed_candidate() -> int:- eid = talent_store.upsert_engagement(role_title="VP Drilling", department="Drilling")- return talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", current_title="Drilling Director",- email=CANDIDATE_EMAIL,- )---def _seed_principal() -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email="[email protected]",- preferred_channel="email",- )---def _run(candidate_id: int) -> list:- workflow = InterviewCoordinationWorkflow()- inputs = InterviewCoordinationInput(candidate_id=candidate_id, num_rounds=4)- events: list = []-- async def _collect() -> None:- async for ev in workflow.run(inputs=inputs, store=MagicMock()):- events.append(ev)-- with patch(- "openexecutive.workflows.interview_coordination.route_to_specialist",- new_callable=AsyncMock,- side_effect=["LOOP_BODY", "AVAIL_BODY"],- ), patch("openexecutive.workflows.interview_coordination.retrieve", return_value=""):- asyncio.run(_collect())- return events---def test_schedules_one_reminder_to_principal(db: Path) -> None:- cand_id = _seed_candidate()- pid = _seed_principal()- events = _run(cand_id)- assert "error" not in [e.type for e in events]- assert next(e for e in events if e.type == "result").data["scheduled_count"] == 1-- actions = episodic.list_scheduled_actions()- assert len(actions) == 1- a = actions[0]- assert a.assigned_to_person_id == pid- assert a.channel_ref == "[email protected]"- assert a.channel_ref != CANDIDATE_EMAIL- assert "Do NOT contact the candidate directly" in a.intent_text- assert "LOOP_BODY" in a.intent_text- assert "AVAIL_BODY" in a.intent_text---def test_artifact_has_loop_and_availability(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- artifact = next(e for e in _run(cand_id) if e.type == "artifact")- assert "Proposed Interview Loop" in artifact.content- assert "Availability Request" in artifact.content- assert "LOOP_BODY" in artifact.content- assert "AVAIL_BODY" in artifact.content---def test_unknown_candidate_errors(db: Path) -> None:- _seed_principal()- events = _run(9999)- assert events[-1].type == "error"- assert episodic.list_scheduled_actions() == []---def test_no_principal_schedules_nothing(db: Path) -> None:- cand_id = _seed_candidate()- events = _run(cand_id)- assert events[-1].type == "error"- assert episodic.list_scheduled_actions() == []diff --git a/packages/core/tests/unit/test_mcp_server.py b/packages/core/tests/unit/test_mcp_server.pyindex d00d9f7f..09ee0f36 100644--- a/packages/core/tests/unit/test_mcp_server.py+++ b/packages/core/tests/unit/test_mcp_server.py@@ -46,10 +46,6 @@ async def test_registered_tools() -> None:"search_knowledge","list_workflows","ask_executive",- "list_candidates",- "get_candidate",- "match_candidates",- "find_similar_candidates",}@@ -65,7 +61,6 @@ async def test_registered_resources() -> None:"oe://memory/decisions","oe://memory/initiatives","oe://memory/advice",- "oe://talent/engagements",}@@ -205,178 +200,6 @@ async def test_ask_executive_resolves_principal_and_calls_chat() -> None:assert chat.await_args.kwargs["person_id"] == 42-# ----------------------------------------------------------------------------# Talent / executive-search read-only tools + resource.-# ----------------------------------------------------------------------------class _Stage:- def __init__(self, value: str) -> None:- self.value = value---class _Candidate:- def __init__(- self,- cid: int,- name: str = "Jane Roe",- stage: str = "lead",- archived: bool = False,- ) -> None:- self.id = cid- self.engagement_id = 1- self.full_name = name- self.current_title = "VP Ops"- self.current_company = "Acme"- self.stage = _Stage(stage)- self.fit_score = None- self.archived = archived-- def model_dump(self, mode: str = "python") -> dict[str, Any]:- return {"id": self.id, "full_name": self.full_name}---async def test_talent_engagements_resource_serializes_rollup() -> None:- items = [_Dumpable({"engagement_id": 1, "role_title": "VP Drilling"})]- with patch(- "openexecutive.briefing.talent_digest.build_talent_brief_items",- return_value=items,- ):- out = await mcp_server.talent_engagements()- assert json.loads(out) == [{"engagement_id": 1, "role_title": "VP Drilling"}]---async def test_list_candidates_returns_briefs() -> None:- with (- patch("openexecutive.talent.store.get_engagement", return_value=object()),- patch(- "openexecutive.talent.store.list_candidates",- return_value=[_Candidate(7, "Jane Roe", "offer")],- ),- ):- out = await mcp_server.list_candidates(engagement_id=1)- data = json.loads(out)- assert data == [- {- "candidate_id": 7,- "engagement_id": 1,- "full_name": "Jane Roe",- "current_title": "VP Ops",- "current_company": "Acme",- "stage": "offer",- "fit_score": None,- }- ]---async def test_list_candidates_unknown_engagement() -> None:- with patch("openexecutive.talent.store.get_engagement", return_value=None):- out = await mcp_server.list_candidates(engagement_id=4242)- assert json.loads(out)["error"] == "not_found"---async def test_list_candidates_rejects_invalid_stage() -> None:- # Stage validation happens before any store call, so no engagement needed.- out = await mcp_server.list_candidates(engagement_id=1, stage="bogus")- assert "invalid stage" in json.loads(out)["error"]---async def test_get_candidate_found_and_missing() -> None:- with patch(- "openexecutive.talent.store.get_candidate", return_value=_Candidate(7)- ):- found = await mcp_server.get_candidate(7)- assert json.loads(found) == {"id": 7, "full_name": "Jane Roe"}-- with patch("openexecutive.talent.store.get_candidate", return_value=None):- missing = await mcp_server.get_candidate(9999)- assert json.loads(missing) == {"error": "not_found", "candidate_id": 9999}---async def test_get_candidate_hides_archived() -> None:- # A soft-deleted candidate must not be readable by id over the external- # surface, even though store.get_candidate would still return it.- with patch(- "openexecutive.talent.store.get_candidate",- return_value=_Candidate(7, archived=True),- ):- out = await mcp_server.get_candidate(7)- assert json.loads(out)["error"] == "not_found"---async def test_match_candidates_enriches_with_names() -> None:- mcp_server.set_store("STORE_SENTINEL")- try:- with (- patch("openexecutive.talent.store.get_engagement", return_value=object()),- patch(- "openexecutive.talent.graph.match_candidates_for_engagement",- return_value=[{"candidate_id": 7, "score": 0.9, "stage": "lead"}],- ),- patch(- "openexecutive.talent.store.get_candidate", return_value=_Candidate(7)- ),- ):- out = await mcp_server.match_candidates(engagement_id=1, limit=5)- match = json.loads(out)["matches"][0]- assert match["candidate_id"] == 7- assert match["full_name"] == "Jane Roe"- assert match["current_title"] == "VP Ops"- finally:- mcp_server.set_store(None)---async def test_match_candidates_unknown_engagement() -> None:- mcp_server.set_store("STORE_SENTINEL")- try:- with patch("openexecutive.talent.store.get_engagement", return_value=None):- out = await mcp_server.match_candidates(engagement_id=4242)- assert json.loads(out)["error"] == "not_found"- finally:- mcp_server.set_store(None)---async def test_find_similar_candidates_missing_candidate() -> None:- mcp_server.set_store("STORE_SENTINEL")- try:- with patch("openexecutive.talent.store.get_candidate", return_value=None):- out = await mcp_server.find_similar_candidates(candidate_id=9999)- assert json.loads(out)["error"] == "not_found"- finally:- mcp_server.set_store(None)---async def test_find_similar_candidates_enriches_with_names() -> None:- mcp_server.set_store("STORE_SENTINEL")- try:- # get_candidate is called twice: once to load the query candidate, then- # by _enrich_matches for each result — both return a named candidate.- with (- patch(- "openexecutive.talent.store.get_candidate",- return_value=_Candidate(7),- ),- patch(- "openexecutive.talent.graph.find_similar_candidates",- return_value=[{"candidate_id": 8, "score": 0.7, "stage": "lead"}],- ),- ):- out = await mcp_server.find_similar_candidates(candidate_id=7, limit=3)- match = json.loads(out)["matches"][0]- assert match["candidate_id"] == 8- assert match["full_name"] == "Jane Roe"- finally:- mcp_server.set_store(None)--# ---------------------------------------------------------------------------# Mount + auth.# ---------------------------------------------------------------------------diff --git a/packages/core/tests/unit/test_new_hire_onboarding_workflow.py b/packages/core/tests/unit/test_new_hire_onboarding_workflow.pydeleted file mode 100644index a19e337c..00000000--- a/packages/core/tests/unit/test_new_hire_onboarding_workflow.py+++ /dev/null@@ -1,205 +0,0 @@-"""Tests for the NewHireOnboardingWorkflow (placed → Person handoff)."""-from __future__ import annotations--import asyncio-from datetime import UTC, datetime, timedelta-from pathlib import Path-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage, OfferStatus-from openexecutive.workflows.new_hire_onboarding import (- NewHireOnboardingInput,- NewHireOnboardingWorkflow,-)--HIRE_EMAIL = "[email protected]"---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- """One shared episodic_memory.db for talent + people + scheduled_actions."""- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- return path---def _seed_placed_candidate(- stage: CandidateStage = CandidateStage.PLACED, email: str | None = HIRE_EMAIL-) -> int:- eid = talent_store.upsert_engagement(- role_title="VP Drilling", department="Drilling",- must_haves="cycle-tested upstream lead",- )- return talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", email=email, stage=stage,- )---def _seed_principal() -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email="[email protected]",- preferred_channel="email", # type: ignore[arg-type]- )---def _run(candidate_id: int, start_date: str = "") -> list:- workflow = NewHireOnboardingWorkflow()- inputs = NewHireOnboardingInput(candidate_id=candidate_id, start_date=start_date)- events: list = []-- async def _collect() -> None:- async for ev in workflow.run(inputs=inputs, store=MagicMock()):- events.append(ev)-- with patch(- "openexecutive.workflows.new_hire_onboarding.route_to_specialist",- AsyncMock(return_value="PLAN_BODY"),- ), patch("openexecutive.workflows.new_hire_onboarding.retrieve", return_value=""):- asyncio.run(_collect())- return events---def test_creates_person_and_schedules_checkins_to_principal(db: Path) -> None:- cand_id = _seed_placed_candidate()- principal_id = _seed_principal()-- events = _run(cand_id)- assert "error" not in [e.type for e in events]-- result = next(e for e in events if e.type == "result")- assert result.data["person_created"] is True-- # Person mapped from candidate + engagement; no authority scopes granted.- person = people_store.get_person(result.data["person_id"])- assert person is not None- assert person.full_name == "Dana Cole"- assert person.role == "VP Drilling"- assert person.email == HIRE_EMAIL- assert person.is_principal is False- assert person.authority_scope == []- # "Drilling" is free text that doesn't resolve to a department slug here.- assert person.department_slugs == []-- # All four check-ins (start = today, so day 7/30/60/90 are in the future),- # each assigned to the principal — never the hire.- assert result.data["scheduled_count"] == 4- pending = episodic.list_scheduled_actions(status="pending")- assert len(pending) == 4- for action in pending:- assert action.assigned_to_person_id == principal_id- assert action.kind == "ad_hoc"- assert action.channel_ref != HIRE_EMAIL- assert "Do NOT contact the new hire" in action.intent_text-- artifact = next(e for e in events if e.type == "artifact")- assert "PLAN_BODY" in artifact.content---def test_idempotent_rerun_updates_instead_of_duplicating(db: Path) -> None:- cand_id = _seed_placed_candidate()- _seed_principal()-- first = _run(cand_id)- second = _run(cand_id)- assert "error" not in [e.type for e in second]-- first_id = next(e for e in first if e.type == "result").data["person_id"]- second_result = next(e for e in second if e.type == "result")- assert second_result.data["person_id"] == first_id- assert second_result.data["person_created"] is False-- hires = [p for p in people_store.list_people() if p.full_name == "Dana Cole"]- assert len(hires) == 1---def test_matches_existing_person_by_name_when_no_email(db: Path) -> None:- cand_id = _seed_placed_candidate(email=None)- _seed_principal()- existing = people_store.upsert_person(full_name="Dana Cole", role="Consultant")-- events = _run(cand_id)- result = next(e for e in events if e.type == "result")- assert result.data["person_id"] == existing- assert result.data["person_created"] is False- person = people_store.get_person(existing)- assert person is not None and person.role == "VP Drilling"---def test_refuses_unplaced_candidate_without_accepted_offer(db: Path) -> None:- cand_id = _seed_placed_candidate(stage=CandidateStage.INTERVIEWED)- _seed_principal()-- events = _run(cand_id)- assert events[-1].type == "error"- assert "record the offer acceptance" in events[-1].message- assert all(p.full_name != "Dana Cole" for p in people_store.list_people())---def test_accepted_offer_qualifies_even_before_stage_moves(db: Path) -> None:- cand_id = _seed_placed_candidate(stage=CandidateStage.OFFER)- _seed_principal()- cand = talent_store.get_candidate(cand_id)- assert cand is not None- oid = talent_store.create_offer(- candidate_id=cand_id, engagement_id=cand.engagement_id, comp_summary="x"- )- talent_store.set_offer_status(oid, OfferStatus.EXTENDED)- talent_store.set_offer_status(oid, OfferStatus.ACCEPTED)-- events = _run(cand_id)- assert "error" not in [e.type for e in events]---def test_past_milestones_are_skipped(db: Path) -> None:- cand_id = _seed_placed_candidate()- _seed_principal()- # Started 45 days ago: day-7 and day-30 check-ins are in the past.- start = (datetime.now(UTC) - timedelta(days=45)).date().isoformat()-- events = _run(cand_id, start_date=start)- result = next(e for e in events if e.type == "result")- assert result.data["scheduled_count"] == 2 # day 60 + day 90 only---def test_bad_start_date_errors(db: Path) -> None:- cand_id = _seed_placed_candidate()- _seed_principal()- events = _run(cand_id, start_date="not-a-date")- assert events[-1].type == "error"- assert "ISO date" in events[-1].message---def test_rehire_into_new_department_replaces_stale_slugs(- db: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- """A re-hire whose engagement resolves to a real department must not keep- the old department_slugs (the engagement is the source of truth for the- new role, same as `role`)."""- from openexecutive.workflows import new_hire_onboarding as wf_module-- cand_id = _seed_placed_candidate()- _seed_principal()- existing = people_store.upsert_person(- full_name="Dana Cole", role="Sales Lead", email=HIRE_EMAIL,- department_slugs=["sales"],- )- monkeypatch.setattr(- wf_module, "_resolvable_department_slugs", lambda _eng: ["engineering"]- )-- events = _run(cand_id)- assert "error" not in [e.type for e in events]- person = people_store.get_person(existing)- assert person is not None- assert person.department_slugs == ["engineering"]- assert person.role == "VP Drilling"diff --git a/packages/core/tests/unit/test_offer_approval_workflow.py b/packages/core/tests/unit/test_offer_approval_workflow.pydeleted file mode 100644index 2515eff6..00000000--- a/packages/core/tests/unit/test_offer_approval_workflow.py+++ /dev/null@@ -1,178 +0,0 @@-"""Tests for the OfferApprovalWorkflow (close-the-hire-loop).--The workflow drafts the package, persists the Offer, DMs the HIRING_SIGNOFF-approver, and pauses on a WaitForHumanEvent gate. The candidate is never the-DM recipient — the seeded candidate has an email so that assertion is real.-"""-from __future__ import annotations--import asyncio-import json-from pathlib import Path-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.people.models import AuthorityScope-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage, OfferStatus-from openexecutive.workflows.offer_approval import (- OfferApprovalInput,- OfferApprovalWorkflow,-)-from openexecutive.workflows.wait_for_human import WaitForHumanEvent--CANDIDATE_EMAIL = "[email protected]"---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- """One shared episodic_memory.db for talent + people + scheduled_actions."""- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- return path---def _seed_candidate(stage: CandidateStage = CandidateStage.INTERVIEWED) -> int:- eid = talent_store.upsert_engagement(- role_title="VP Drilling", department="Drilling",- comp_band="280-340k base + 0.4-0.6% equity",- must_haves="cycle-tested upstream lead",- )- return talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", current_title="Drilling Director",- current_company="Permian Co", email=CANDIDATE_EMAIL, stage=stage,- )---def _seed_principal(*, email: str = "[email protected]") -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email=email,- preferred_channel="email", # type: ignore[arg-type]- )---def _seed_signoff_approver(*, slack: str = "U999") -> int:- pid = people_store.upsert_person(- full_name="Morgan Hale", role="Head of People", slack_user_id=slack,- preferred_channel="slack", # type: ignore[arg-type]- response_sla_hours=4,- )- people_store.set_authority_scope(pid, [AuthorityScope.HIRING_SIGNOFF])- return pid---def _run(candidate_id: int, *, dm_mock: AsyncMock | None = None) -> list:- workflow = OfferApprovalWorkflow()- inputs = OfferApprovalInput(candidate_id=candidate_id, comp_notes="top of band")- events: list = []- dm = dm_mock or AsyncMock(return_value=json.dumps({"status": "sent"}))-- async def _collect() -> None:- async for ev in workflow.run(inputs=inputs, store=MagicMock()):- events.append(ev)-- with patch(- "openexecutive.workflows.offer_approval.route_to_specialist",- AsyncMock(side_effect=["TERMS_BODY", "CLOSE_PLAN_BODY"]),- ), patch(- "openexecutive.workflows.offer_approval.retrieve", return_value=""- ), patch(- "openexecutive.orchestrator.schedule_tools.handle_message_person", dm,- ):- asyncio.run(_collect())- return events---def test_happy_path_pauses_on_gate_for_the_approver(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- approver_id = _seed_signoff_approver()- dm = AsyncMock(return_value=json.dumps({"status": "sent"}))-- events = _run(cand_id, dm_mock=dm)-- assert "error" not in [getattr(e, "type", None) for e in events]-- # The run ends on the gate, addressed to the delegated approver (not the- # principal, who is sorted after delegated humans by find_approvers).- gate = events[-1]- assert isinstance(gate, WaitForHumanEvent)- assert gate.person_id == approver_id- assert gate.expected_reply_shape == "approve_reject"- assert gate.context_summary.startswith("offer_id=")- assert gate.on_timeout == "escalate"-- # The offer row is persisted pending approval with the package attached.- offer = talent_store.get_open_offer_for_candidate(cand_id)- assert offer is not None- assert offer.status is OfferStatus.PENDING_APPROVAL- assert offer.comp_summary == "top of band"- assert "TERMS_BODY" in offer.package_md and "CLOSE_PLAN_BODY" in offer.package_md- assert gate.context_summary.startswith(f"offer_id={offer.id}")-- # Candidate advanced interviewed -> offer.- cand = talent_store.get_candidate(cand_id)- assert cand is not None and cand.stage is CandidateStage.OFFER-- # The sign-off DM went to the approver — never to the candidate's email.- dm.assert_awaited_once()- dm_input = dm.await_args.args[0]- assert dm_input["person_id"] == approver_id- assert CANDIDATE_EMAIL not in dm_input["text"]-- # result + artifact were yielded BEFORE the gate (the runner stops there).- types = [getattr(e, "type", "gate") for e in events]- assert types.index("result") < len(events) - 1- assert types.index("artifact") < len(events) - 1- result = next(e for e in events if getattr(e, "type", "") == "result")- assert result.data["offer_id"] == offer.id- assert result.data["approver_person_id"] == approver_id---def test_falls_back_to_principal_when_no_scoped_approver(db: Path) -> None:- cand_id = _seed_candidate()- principal_id = _seed_principal()-- events = _run(cand_id)- gate = events[-1]- assert isinstance(gate, WaitForHumanEvent)- assert gate.person_id == principal_id---def test_refuses_unscreened_candidate(db: Path) -> None:- cand_id = _seed_candidate(stage=CandidateStage.LEAD)- _seed_principal()-- events = _run(cand_id)- assert events[-1].type == "error"- assert "screen and interview" in events[-1].message- assert talent_store.list_offers(candidate_id=cand_id) == []---def test_refuses_when_open_offer_exists(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- cand = talent_store.get_candidate(cand_id)- assert cand is not None- talent_store.create_offer(- candidate_id=cand_id, engagement_id=cand.engagement_id, comp_summary="x"- )-- events = _run(cand_id)- assert events[-1].type == "error"- assert "already has an open offer" in events[-1].message---def test_errors_without_principal(db: Path) -> None:- cand_id = _seed_candidate()- events = _run(cand_id)- assert events[-1].type == "error"- assert "principal" in events[-1].message.lower()diff --git a/packages/core/tests/unit/test_onboarding_chat_tools.py b/packages/core/tests/unit/test_onboarding_chat_tools.pydeleted file mode 100644index b5804496..00000000--- a/packages/core/tests/unit/test_onboarding_chat_tools.py+++ /dev/null@@ -1,113 +0,0 @@-"""Tests for the staff-onboarding chat tools + their registration.--Verifies the tools are wired into the Executive's skill toolkit and that the-handlers create/list/advance plans and complete tasks against the store.-``start_onboarding`` (which runs the LLM workflow) is covered by the workflow-tests; here we only assert it's registered.-"""-from __future__ import annotations--import json-from pathlib import Path--import pytest--from openexecutive.orchestrator import onboarding_tools as tools-from openexecutive.staff_onboarding import store---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "onboarding.db"- monkeypatch.setattr(store, "DB_PATH", path)- store.initialize_db()- return path---def test_tools_registered_in_executive_toolkit() -> None:- from openexecutive.orchestrator.executive import (- _ALL_SKILL_HANDLERS,- _ALL_SKILL_TOOLS,- )-- names = {t["name"] for t in _ALL_SKILL_TOOLS}- expected = {- "list_onboarding_plans", "get_onboarding_plan", "list_onboarding_templates",- "create_onboarding_plan", "complete_onboarding_task",- "advance_onboarding_plan", "start_onboarding",- }- assert expected <= names- assert expected <= set(_ALL_SKILL_HANDLERS)---async def test_create_list_complete_advance_flow(db: Path) -> None:- created = json.loads(await tools.handle_create_onboarding_plan({- "full_name": "Priya Rao", "start_date": "2026-07-01", "role": "Fractional CFO",- }))- assert created["status"] == "ok"- plan_id = created["plan"]["id"]-- listed = json.loads(await tools.handle_list_onboarding_plans({}))- assert listed["status"] == "ok"- assert [p["plan_id"] for p in listed["plans"]] == [plan_id]-- # Add a task directly, then complete it via the tool.- task_id = store.add_task(plan_id=plan_id, title="Sign NDA")- completed = json.loads(await tools.handle_complete_onboarding_task({"task_id": task_id}))- assert completed["status"] == "ok"- assert completed["task"]["status"] == "done"-- got = json.loads(await tools.handle_get_onboarding_plan({"plan_id": plan_id}))- assert got["plan"]["completion_pct"] == 100-- adv = json.loads(await tools.handle_advance_onboarding_plan({"plan_id": plan_id}))- assert adv["new_phase"] == "week_1"---async def test_create_from_template_and_list_templates(db: Path) -> None:- from openexecutive.staff_onboarding.seed import seed_default_templates-- seed_default_templates()- templates = json.loads(await tools.handle_list_onboarding_templates({}))- names = {t["name"] for t in templates["templates"]}- assert {"generic", "engineering", "finance"} <= names-- created = json.loads(await tools.handle_create_onboarding_plan({- "full_name": "Dana", "start_date": "2026-07-01", "template_name": "generic",- }))- assert created["status"] == "ok"- generic = store.get_template("generic")- assert generic is not None- assert len(created["plan"]["tasks"]) == len(generic.task_specs)---async def test_handlers_validate_and_404(db: Path) -> None:- assert "error" in json.loads(await tools.handle_create_onboarding_plan({"role": "x"}))- assert json.loads(- await tools.handle_get_onboarding_plan({"plan_id": 9999})- )["status"] == "not_found"- assert json.loads(- await tools.handle_complete_onboarding_task({"task_id": 9999})- )["status"] == "not_found"- assert "error" in json.loads(- await tools.handle_create_onboarding_plan(- {"full_name": "X", "start_date": "2026-07-01", "template_name": "nope"}- )- )- # A non-integer person_id is an error, not a silently-unlinked plan.- assert "error" in json.loads(- await tools.handle_create_onboarding_plan(- {"full_name": "X", "start_date": "2026-07-01", "person_id": "not-an-int"}- )- )---def test_seed_is_idempotent(db: Path) -> None:- from openexecutive.staff_onboarding.seed import seed_default_templates-- first = seed_default_templates()- assert first >= 4- assert seed_default_templates() == 0 # already present, no re-insertdiff --git a/packages/core/tests/unit/test_onboarding_orchestration.py b/packages/core/tests/unit/test_onboarding_orchestration.pydeleted file mode 100644index 290ece66..00000000--- a/packages/core/tests/unit/test_onboarding_orchestration.py+++ /dev/null@@ -1,183 +0,0 @@-"""Tests for staff-onboarding stakeholder orchestration.--Covers the enqueue helpers (kickoff + milestone check-ins: idempotency,-past-milestone skip, person_id requirement), activate_plan firing all three-scheduler kinds, and the runner handlers (kickoff nudges, check-in messaging +-deterministic phase advance).-"""-from __future__ import annotations--from datetime import UTC, datetime-from pathlib import Path--import pytest--from openexecutive.memory import episodic-from openexecutive.orchestrator import schedule_tools-from openexecutive.scheduler import runner-from openexecutive.staff_onboarding import orchestration, service, store-from openexecutive.staff_onboarding.models import OnboardingPhase--_FUTURE = "2999-07-01" # all milestones in the future-_PAST = "2000-01-01" # all milestones in the past---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "shared.db"- monkeypatch.setattr(episodic, "DB_PATH", path)- monkeypatch.setattr(store, "DB_PATH", path)- episodic.initialize_db(path)- store.initialize_db(path)- return path---def _pending(kind: str) -> list:- return [a for a in episodic.list_scheduled_actions(status="pending") if a.kind == kind]---def test_enqueue_kickoff_idempotent(db: Path) -> None:- pid = store.create_plan(full_name="Priya Rao", start_date=_FUTURE, person_id=5)- assert orchestration.enqueue_kickoff(pid) is not None- assert orchestration.enqueue_kickoff(pid) is None # already enqueued- assert len(_pending("onboarding_kickoff")) == 1---def test_enqueue_checkins_future_and_idempotent(db: Path) -> None:- pid = store.create_plan(full_name="Priya Rao", start_date=_FUTURE, person_id=5)- ids = orchestration.enqueue_checkins(pid)- assert len(ids) == 4- assert orchestration.enqueue_checkins(pid) == [] # idempotent (return)- # Idempotent at the DB level too — no duplicate rows on the second call.- assert len(_pending("onboarding_checkin")) == 4- refs = {a.channel_ref for a in _pending("onboarding_checkin")}- assert refs == {f"{pid}:day_7", f"{pid}:day_30", f"{pid}:day_60", f"{pid}:day_90"}---def test_enqueue_checkins_skips_past_milestones(db: Path) -> None:- pid = store.create_plan(full_name="Old Hire", start_date=_PAST, person_id=5)- assert orchestration.enqueue_checkins(pid) == []---def test_enqueue_checkins_requires_person(db: Path) -> None:- pid = store.create_plan(full_name="No Person", start_date=_FUTURE) # person_id=None- assert orchestration.enqueue_checkins(pid) == []---def test_phase_for_milestone() -> None:- assert orchestration.phase_for_milestone("day_30") == OnboardingPhase.DAY_30- assert orchestration.phase_for_milestone("day_90") == OnboardingPhase.DAY_90- assert orchestration.phase_for_milestone("nope") is None---def test_activate_enqueues_ramp_kickoff_and_checkins(db: Path) -> None:- pid = store.create_plan(full_name="Priya Rao", start_date=_FUTURE, person_id=5)- store.update_plan(pid, ramp_segments=["d1", "d2"]) # so the ramp can enqueue- assert service.activate_plan(pid) is True- kinds = {a.kind for a in episodic.list_scheduled_actions(status="pending")}- assert {"onboarding_ramp", "onboarding_kickoff", "onboarding_checkin"} <= kinds---async def test_run_kickoff_sends_manager_and_buddy_nudges(- db: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- pid = store.create_plan(- full_name="Priya Rao", start_date=_FUTURE, role="CFO",- person_id=5, manager_person_id=7, buddy_person_id=9,- )- orchestration.enqueue_kickoff(pid)- action = _pending("onboarding_kickoff")[0]-- sent: list[dict] = []-- async def fake_msg(inp: dict) -> str:- sent.append(inp)- return "{}"-- monkeypatch.setattr(schedule_tools, "handle_message_person", fake_msg)- await runner._run_onboarding_kickoff(action, datetime.now(UTC))-- by_person = {m["person_id"]: m["text"] for m in sent}- assert set(by_person) == {7, 9} # manager + buddy, not the hire- assert "manager" in by_person[7].lower() # role-specific copy- assert "buddy" in by_person[9].lower()- # Action consumed.- assert _pending("onboarding_kickoff") == []---async def test_run_checkin_messages_and_advances_phase(- db: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- pid = store.create_plan(- full_name="Priya Rao", start_date=_FUTURE, role="CFO",- person_id=5, manager_person_id=7,- )- orchestration.enqueue_checkins(pid)- action = next(a for a in _pending("onboarding_checkin") if a.channel_ref.endswith(":day_30"))-- sent: list[dict] = []-- async def fake_msg(inp: dict) -> str:- sent.append(inp)- return "{}"-- monkeypatch.setattr(schedule_tools, "handle_message_person", fake_msg)- await runner._run_onboarding_checkin(action, datetime.now(UTC))-- by_person = {m["person_id"]: m["text"] for m in sent}- assert set(by_person) == {5, 7} # hire + manager- assert by_person[5] != by_person[7] # hire and manager get different copy- assert "30" in by_person[5] # day number surfaced- plan = store.get_plan(pid)- assert plan is not None- assert plan.current_phase == OnboardingPhase.DAY_30 # advanced---async def test_checkin_never_drags_phase_backwards(- db: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- pid = store.create_plan(full_name="X", start_date=_FUTURE, person_id=5)- store.update_plan(pid, current_phase=OnboardingPhase.DAY_60) # already past day_30- orchestration.enqueue_checkins(pid)- action = next(a for a in _pending("onboarding_checkin") if a.channel_ref.endswith(":day_30"))-- async def _swallow(inp: dict) -> str:- return "{}"-- monkeypatch.setattr(schedule_tools, "handle_message_person", _swallow)- await runner._run_onboarding_checkin(action, datetime.now(UTC))- plan = store.get_plan(pid)- assert plan is not None- assert plan.current_phase == OnboardingPhase.DAY_60 # unchanged (day_30 < day_60)---async def test_activate_chat_tool_enqueues_and_404(db: Path) -> None:- import json as _json-- from openexecutive.orchestrator import onboarding_tools-- pid = store.create_plan(full_name="Priya Rao", start_date=_FUTURE, person_id=5)- store.update_plan(pid, ramp_segments=["d1"])- res = _json.loads(await onboarding_tools.handle_activate_onboarding_plan({"plan_id": pid}))- assert res["status"] == "ok"- assert res["plan"]["status"] == "active"- kinds = {a.kind for a in episodic.list_scheduled_actions(status="pending")}- assert {"onboarding_ramp", "onboarding_kickoff", "onboarding_checkin"} <= kinds-- missing = _json.loads(- await onboarding_tools.handle_activate_onboarding_plan({"plan_id": 9999})- )- assert missing["status"] == "not_found"- # The tool is registered in the toolkit.- assert "activate_onboarding_plan" in onboarding_tools.ONBOARDING_TOOL_HANDLERS---async def test_send_team_notice_no_channel_returns_false(db: Path) -> None:- # No department / no channel configured → False, never raises.- assert await runner._send_team_notice("", "hi") is False- assert await runner._send_team_notice("nonexistent_dept", "hi") is Falsediff --git a/packages/core/tests/unit/test_onboarding_ramp_scheduler.py b/packages/core/tests/unit/test_onboarding_ramp_scheduler.pydeleted file mode 100644index 68ee4465..00000000--- a/packages/core/tests/unit/test_onboarding_ramp_scheduler.py+++ /dev/null@@ -1,145 +0,0 @@-"""Tests for the bounded onboarding ramp drip (ramp_scheduler + runner branch).--Covers business-day scheduling, enqueue eligibility, and the runner handler:-deliver the next segment, advance the index, chain while segments remain, and-self-terminate when exhausted.-"""-from __future__ import annotations--from datetime import UTC, datetime-from pathlib import Path--import pytest--from openexecutive.memory import episodic-from openexecutive.scheduler import runner-from openexecutive.staff_onboarding import service, store-from openexecutive.staff_onboarding.ramp_scheduler import enqueue_ramp, next_business_day---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- # episodic (scheduled_actions) and the onboarding store share one DB file.- path = tmp_path / "shared.db"- monkeypatch.setattr(episodic, "DB_PATH", path)- monkeypatch.setattr(store, "DB_PATH", path)- episodic.initialize_db(path)- store.initialize_db(path)- return path---def test_next_business_day_skips_weekend() -> None:- # 2026-01-02 is a Friday → next business day is Monday 2026-01-05.- friday = datetime(2026, 1, 2, 15, 0, tzinfo=UTC)- nxt = next_business_day(friday)- assert nxt.date().isoformat() == "2026-01-05"- assert nxt.weekday() < 5- # Thursday → Friday.- thursday = datetime(2026, 1, 1, 15, 0, tzinfo=UTC)- assert next_business_day(thursday).date().isoformat() == "2026-01-02"---def test_next_business_day_coerces_naive_to_utc() -> None:- naive = datetime(2026, 1, 1, 15, 0) # no tzinfo- result = next_business_day(naive)- assert result.tzinfo is not None # always tz-aware out- assert result.date().isoformat() == "2026-01-02"---def test_enqueue_ramp_eligibility(db: Path) -> None:- # No person_id → no enqueue.- no_person = store.create_plan(full_name="A", start_date="2026-07-01")- store.update_plan(no_person, ramp_segments=["d1"])- assert enqueue_ramp(no_person) is None-- # Person but no segments → no enqueue.- no_segs = store.create_plan(full_name="B", start_date="2026-07-01")- store.update_plan(no_segs, person_id=5)- assert enqueue_ramp(no_segs) is None-- # Person + segments → enqueued.- ok = store.create_plan(full_name="C", start_date="2026-07-01")- store.update_plan(ok, person_id=5, ramp_segments=["d1", "d2"])- assert enqueue_ramp(ok) is not None- # Idempotent: a second enqueue while one is pending is a no-op.- assert enqueue_ramp(ok) is None---def test_activate_is_idempotent(db: Path) -> None:- plan_id = store.create_plan(full_name="C", start_date="2026-07-01")- store.update_plan(plan_id, person_id=5, ramp_segments=["d1", "d2"])- assert service.activate_plan(plan_id) is True- assert service.activate_plan(plan_id) is True # double-activate- assert len(_pending_ramp_actions(plan_id)) == 1 # only one drip chain---async def test_no_assignee_does_not_burn_segment(- db: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- from openexecutive.memory.episodic import ScheduledAction-- plan_id = store.create_plan(full_name="C", start_date="2026-07-01")- store.update_plan(plan_id, person_id=5, ramp_segments=["d1", "d2"])- # An action row with no assignee must not claim/advance a segment.- action = ScheduledAction(- id=999, created_at="", run_at="", channel="__internal__",- channel_ref=str(plan_id), intent_text="", kind="onboarding_ramp",- assigned_to_person_id=None,- )- # mark_action_done would 404 on a non-existent row; stub it out.- monkeypatch.setattr(runner, "mark_action_done", lambda _id: None)- await runner._run_onboarding_ramp(action, datetime.now(UTC))- assert store.get_plan(plan_id).ramp_next_index == 0 # type: ignore[union-attr]---def _pending_ramp_actions(plan_id: int) -> list:- # Ramp rows use the __internal__ channel, which list_pending_scheduled_actions- # intentionally hides — query the full table and filter by status instead.- return [- a for a in episodic.list_scheduled_actions()- if a.kind == "onboarding_ramp"- and a.channel_ref == str(plan_id)- and a.status == "pending"- ]---async def test_drip_delivers_chains_and_terminates(- db: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- sent: list[tuple[int, str]] = []-- async def _fake_message_person(tool_input: dict) -> str:- sent.append((tool_input["person_id"], tool_input["text"]))- return "{}"-- from openexecutive.orchestrator import schedule_tools- monkeypatch.setattr(schedule_tools, "handle_message_person", _fake_message_person)-- plan_id = store.create_plan(full_name="Priya", start_date="2026-07-01")- store.update_plan(plan_id, person_id=42, ramp_segments=["Day one note", "Day two note"])-- assert service.activate_plan(plan_id) is True- actions = _pending_ramp_actions(plan_id)- assert len(actions) == 1-- # Fire #1 → delivers segment 1, advances index, chains the next.- await runner._run_onboarding_ramp(actions[0], datetime.now(UTC))- assert sent == [(42, "Day one note")]- assert store.get_plan(plan_id).ramp_next_index == 1 # type: ignore[union-attr]- actions = _pending_ramp_actions(plan_id)- assert len(actions) == 1 # one new pending occurrence chained-- # Fire #2 → delivers segment 2, exhausts the drip, no further chain.- await runner._run_onboarding_ramp(actions[0], datetime.now(UTC))- assert sent[-1] == (42, "Day two note")- assert store.get_plan(plan_id).ramp_next_index == 2 # type: ignore[union-attr]- assert _pending_ramp_actions(plan_id) == []-- # A stray fire after exhaustion is a no-op (claims nothing, no send/chain).- leftover_done = [- a for a in episodic.list_scheduled_actions() if a.kind == "onboarding_ramp"- ]- assert len(sent) == 2- assert len(leftover_done) >= 2 # both fired rows recordeddiff --git a/packages/core/tests/unit/test_onboarding_template_instantiate.py b/packages/core/tests/unit/test_onboarding_template_instantiate.pydeleted file mode 100644index 981b8208..00000000--- a/packages/core/tests/unit/test_onboarding_template_instantiate.py+++ /dev/null@@ -1,110 +0,0 @@-"""Tests for staff-onboarding instantiation + phase advance (service.py).--Covers due-date math (start_date + offset), owner-role resolution-(hire/manager/buddy → ids, unknown → unassigned), task ordering, and the-phase-advance walk that stops at the final phase.-"""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.staff_onboarding import service, store-from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingTemplate,- TaskSpec,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "onboarding.db"- monkeypatch.setattr(store, "DB_PATH", path)- store.initialize_db()- return path---def _template() -> OnboardingTemplate:- return OnboardingTemplate(- name="generic",- title="Generic Onboarding",- ramp_days=3,- task_specs=[- TaskSpec(title="Sign offer", phase=OnboardingPhase.PRE_START,- owner_role="hire", due_offset_days=-3),- TaskSpec(title="1:1 with manager", phase=OnboardingPhase.WEEK_1,- owner_role="manager", due_offset_days=1),- TaskSpec(title="Coffee with buddy", phase=OnboardingPhase.WEEK_1,- owner_role="buddy", due_offset_days=2),- TaskSpec(title="Compliance training", phase=OnboardingPhase.WEEK_1,- owner_role="hr", due_offset_days=4), # unknown→unassigned- ],- )---def test_instantiate_sets_due_dates_owners_and_order(db: Path) -> None:- plan_id = service.instantiate_plan(- full_name="Priya Rao",- start_date="2026-07-01",- role="CFO",- template=_template(),- person_id=100,- manager_person_id=200,- buddy_person_id=300,- )- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.template_name == "generic"- assert plan.status.value == "draft"- assert len(plan.tasks) == 4-- by_title = {t.title: t for t in plan.tasks}- assert by_title["Sign offer"].due_date == "2026-06-28" # -3 days- assert by_title["Sign offer"].owner_person_id == 100 # hire- assert by_title["1:1 with manager"].due_date == "2026-07-02" # +1- assert by_title["1:1 with manager"].owner_person_id == 200 # manager- assert by_title["Coffee with buddy"].owner_person_id == 300 # buddy- assert by_title["Compliance training"].owner_person_id is None # hr unresolved-- # Tasks keep template order via sort_order.- assert [t.title for t in plan.tasks] == [- "Sign offer", "1:1 with manager", "Coffee with buddy", "Compliance training",- ]---def test_instantiate_without_template_creates_bare_plan(db: Path) -> None:- plan_id = service.instantiate_plan(full_name="Sam", start_date="2026-07-01")- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.tasks == []- assert plan.template_name == ""---def test_instantiate_tolerates_bad_start_date(db: Path) -> None:- plan_id = service.instantiate_plan(- full_name="Sam", start_date="not-a-date", template=_template()- )- plan = store.get_plan(plan_id)- assert plan is not None- # Tasks still created, just with no due date.- assert len(plan.tasks) == 4- assert all(t.due_date is None for t in plan.tasks)---def test_advance_phase_walks_and_stops(db: Path) -> None:- plan_id = service.instantiate_plan(full_name="Sam", start_date="2026-07-01")- assert store.get_plan(plan_id).current_phase == OnboardingPhase.PRE_START # type: ignore[union-attr]-- assert service.advance_phase(plan_id) == OnboardingPhase.WEEK_1- assert service.advance_phase(plan_id) == OnboardingPhase.DAY_30- assert service.advance_phase(plan_id) == OnboardingPhase.DAY_60- assert service.advance_phase(plan_id) == OnboardingPhase.DAY_90- # Already at the final phase → no further advance.- assert service.advance_phase(plan_id) is None- assert store.get_plan(plan_id).current_phase == OnboardingPhase.DAY_90 # type: ignore[union-attr]---def test_advance_phase_missing_plan(db: Path) -> None:- assert service.advance_phase(99999) is Nonediff --git a/packages/core/tests/unit/test_reference_check_workflow.py b/packages/core/tests/unit/test_reference_check_workflow.pydeleted file mode 100644index ad6c4f3b..00000000--- a/packages/core/tests/unit/test_reference_check_workflow.py+++ /dev/null@@ -1,104 +0,0 @@-"""Tests for the ReferenceCheckWorkflow."""-from __future__ import annotations--import asyncio-from pathlib import Path-from unittest.mock import AsyncMock, MagicMock, patch--import pytest--from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.talent import store as talent_store-from openexecutive.workflows.reference_check import (- ReferenceCheckInput,- ReferenceCheckWorkflow,-)--CANDIDATE_EMAIL = "[email protected]"---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- return path---def _seed_candidate() -> int:- eid = talent_store.upsert_engagement(role_title="VP Drilling", department="Drilling")- return talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", email=CANDIDATE_EMAIL,- )---def _seed_principal() -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email="[email protected]",- preferred_channel="email",- )---def _run(candidate_id: int, reference_count: int = 2) -> list:- workflow = ReferenceCheckWorkflow()- inputs = ReferenceCheckInput(candidate_id=candidate_id, reference_count=reference_count)- events: list = []-- async def _collect() -> None:- async for ev in workflow.run(inputs=inputs, store=MagicMock()):- events.append(ev)-- with patch(- "openexecutive.workflows.reference_check.route_to_specialist",- new_callable=AsyncMock,- side_effect=["RUBRIC_BODY", "OUTREACH_BODY"],- ), patch("openexecutive.workflows.reference_check.retrieve", return_value=""):- asyncio.run(_collect())- return events---def test_schedules_one_reminder_to_principal(db: Path) -> None:- cand_id = _seed_candidate()- pid = _seed_principal()- events = _run(cand_id)- assert "error" not in [e.type for e in events]- assert next(e for e in events if e.type == "result").data["scheduled_count"] == 1-- actions = episodic.list_scheduled_actions()- assert len(actions) == 1- a = actions[0]- assert a.assigned_to_person_id == pid- assert a.channel_ref == "[email protected]"- assert a.channel_ref != CANDIDATE_EMAIL- assert "Do NOT contact the references directly" in a.intent_text- assert "RUBRIC_BODY" in a.intent_text- assert "OUTREACH_BODY" in a.intent_text---def test_artifact_has_rubric_and_outreach(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- artifact = next(e for e in _run(cand_id) if e.type == "artifact")- assert "Reference Rubric" in artifact.content- assert "Reference Outreach" in artifact.content- assert "RUBRIC_BODY" in artifact.content- assert "OUTREACH_BODY" in artifact.content---def test_unknown_candidate_errors(db: Path) -> None:- _seed_principal()- events = _run(9999)- assert events[-1].type == "error"- assert episodic.list_scheduled_actions() == []---def test_no_principal_schedules_nothing(db: Path) -> None:- cand_id = _seed_candidate()- events = _run(cand_id)- assert events[-1].type == "error"- assert episodic.list_scheduled_actions() == []diff --git a/packages/core/tests/unit/test_role_onboarding_workflow.py b/packages/core/tests/unit/test_role_onboarding_workflow.pydeleted file mode 100644index a37d8b15..00000000--- a/packages/core/tests/unit/test_role_onboarding_workflow.py+++ /dev/null@@ -1,160 +0,0 @@-"""Tests for the role_onboarding workflow.--Specialists are mocked (no API calls). Covers specialist resolution, section-assembly, ramp-segment parsing, plan write-back, and the no-context error path.-"""-from __future__ import annotations--from pathlib import Path-from typing import Any--import pytest--from openexecutive.staff_onboarding import store-from openexecutive.staff_onboarding.models import OnboardingTemplate-from openexecutive.staff_onboarding.specialists import resolve_specialist-from openexecutive.workflows import role_onboarding-from openexecutive.workflows.role_onboarding import (- RoleOnboardingInput,- RoleOnboardingWorkflow,- _split_ramp,-)---class _FakeStore:- """Duck-typed ChromaDBStore: reading-list query returns nothing."""-- def query(self, *a: Any, **k: Any) -> list[dict[str, Any]]:- return []---async def _fake_route(*, specialist_name: str, query: str, context: str = "",- retrieved_knowledge: str = "", **_: Any) -> str:- if "ramp drip" in query:- return "DAY 1: Read the handbook.\n\nDAY 2: Meet your manager.\n\nDAY 3: Ship a fix."- return f"Content from {specialist_name}."---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "onboarding.db"- monkeypatch.setattr(store, "DB_PATH", path)- store.initialize_db()- return path--[email protected](autouse=True)-def _mock_specialists(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(role_onboarding, "route_to_specialist", _fake_route)- monkeypatch.setattr(role_onboarding, "retrieve", lambda **k: "")- monkeypatch.setattr(role_onboarding, "_roster_block", lambda: "CURRENT TEAM:\n- Sam — CEO")-- class _EmptyProfile:- def is_empty(self) -> bool:- return True-- def to_prompt_block(self) -> str:- return ""-- monkeypatch.setattr(role_onboarding, "load_or_create_profile", lambda: _EmptyProfile())---async def _collect(workflow: RoleOnboardingWorkflow, inputs: RoleOnboardingInput) -> list[Any]:- return [e async for e in workflow.run(inputs, _FakeStore())] # type: ignore[arg-type]---async def test_adhoc_brief_assembles_all_sections(db: Path) -> None:- events = await _collect(- RoleOnboardingWorkflow(),- RoleOnboardingInput(full_name="Priya Rao", role="Fractional CFO",- function="finance", ramp_days=2),- )- artifact = next(e.content for e in events if e.type == "artifact")- for heading in (- "# Onboarding Brief: Priya Rao",- "## Company Landscape",- "## State of Your Function",- "## People Map",- "## 30 / 60 / 90 Day Plan",- "## Questions to Ask in Week One",- ):- assert heading in artifact-- result = next(e for e in events if e.type == "result")- assert result.data["specialist"] == "cfo" # finance → cfo- assert len(result.data["ramp_segments"]) == 2 # capped to ramp_days=2- assert events[-1].type == "done"---async def test_plan_backed_run_writes_brief_and_ramp(db: Path) -> None:- plan_id = store.create_plan(full_name="Dana Lee", start_date="2026-07-01", role="VP Eng")- events = await _collect(- RoleOnboardingWorkflow(), RoleOnboardingInput(plan_id=plan_id, function="engineering",- ramp_days=3),- )- assert any(e.type == "artifact" for e in events)-- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.brief_artifact.startswith("# Onboarding Brief: Dana Lee")- assert len(plan.ramp_segments) == 3- assert plan.ramp_next_index == 0- # engineering → cpo (no CTO specialist).- assert next(e for e in events if e.type == "result").data["specialist"] == "cpo"---async def test_ramp_days_none_falls_back_to_template(db: Path) -> None:- store.upsert_template(OnboardingTemplate(name="t", title="T", ramp_days=2))- plan_id = store.create_plan(- full_name="Dana", start_date="2026-07-01", template_name="t"- )- # ramp_days left at its default (None) → template's 2 is used.- await _collect(RoleOnboardingWorkflow(), RoleOnboardingInput(plan_id=plan_id))- plan = store.get_plan(plan_id)- assert plan is not None- assert len(plan.ramp_segments) == 2---async def test_ramp_rerun_with_zero_preserves_in_progress_drip(db: Path) -> None:- plan_id = store.create_plan(full_name="Dana", start_date="2026-07-01")- store.update_plan(plan_id, ramp_segments=["a", "b", "c"], ramp_next_index=2)- # Explicit ramp_days=0 → no drip generated, and the in-progress one is kept.- await _collect(- RoleOnboardingWorkflow(), RoleOnboardingInput(plan_id=plan_id, ramp_days=0)- )- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.ramp_segments == ["a", "b", "c"]- assert plan.ramp_next_index == 2- assert plan.brief_artifact.startswith("# Onboarding Brief") # brief still written---async def test_no_context_errors(db: Path) -> None:- events = await _collect(RoleOnboardingWorkflow(), RoleOnboardingInput())- assert events[-1].type == "error"- assert "plan_id or a full_name" in (events[-1].message or "")---def test_split_ramp_markers_and_fallback() -> None:- marked = "DAY 1: alpha\n\nDAY 2: beta\n\nDAY 3: gamma"- assert _split_ramp(marked, 3) == ["alpha", "beta", "gamma"]- # Over-production is capped to the requested count.- assert _split_ramp(marked, 2) == ["alpha", "beta"]- # Single-day drip with a marker is NOT mistaken for a parse failure: the- # marker is stripped and the (multi-paragraph) body is kept intact.- assert _split_ramp("DAY 1: Hello.\n\nRead this doc.", 1) == ["Hello.\n\nRead this doc."]- # No markers → paragraph fallback.- assert _split_ramp("para one\n\npara two", 5) == ["para one", "para two"]- assert _split_ramp("", 3) == []---def test_resolve_specialist_precedence() -> None:- assert resolve_specialist(function="finance") == "cfo"- assert resolve_specialist(function="sales") == "cmo"- assert resolve_specialist(role="Head of Legal") == "gc" # keyword in role text- assert resolve_specialist() == "cso" # fallbackdiff --git a/packages/core/tests/unit/test_scheduled_actions_store.py b/packages/core/tests/unit/test_scheduled_actions_store.pyindex 43e10cf3..cd761fc1 100644--- a/packages/core/tests/unit/test_scheduled_actions_store.py+++ b/packages/core/tests/unit/test_scheduled_actions_store.py@@ -7,6 +7,7 @@ from pathlib import Pathimport pytestfrom openexecutive.memory.episodic import (+ cancel_orphaned_talent_reminders,cancel_scheduled_action,claim_due_actions,count_pending_for_channel_ref,@@ -444,3 +445,147 @@ def test_list_pending_scheduled_actions_excludes_done(db: Path) -> None:)mark_action_done(aid, db_path=db)assert list_pending_scheduled_actions(db_path=db) == []+++# --------------------------------------------------------------------------- #+# One-shot sweep for reminders the removed talent / staff-onboarding+# workflows left on the principal's DM channel.+# --------------------------------------------------------------------------- #++# Literal intent texts as the deleted generators produced them (pre-removal+# commit d160d3d: workflows/candidate_outreach.py, interview_coordination.py,+# reference_check.py, new_hire_onboarding.py, talent/offers.py). The sweep+# must match THESE, not strings derived from its own patterns.+_ORPHAN_INTENTS = [+ "Outreach reminder 1/3 (Day 0) for the VP Operations search (Acme). Send the "+ "principal this ready-to-send draft for Jane Doe so they can review and send it "+ "themselves. Do NOT contact the candidate directly.\n\nHi Jane…",+ "Interview coordination for Jane Doe on the VP Operations search (Acme). Send the "+ "principal the proposed interview loop below and the ready-to-send availability "+ "request so they can line up the panel and send the request to the candidate.",+ "Reference checks (3) for Jane Doe on the VP Operations search (Acme). Send the "+ "principal the rubric below and the ready-to-send reference-outreach so they can "+ "line up and run the references themselves.",+ "Onboarding check-in (day 30) for Jane Doe, VP Operations at Acme. DM the "+ "principal the day-30 milestone questions from the onboarding plan so they can "+ "run the check-in themselves.",+ "Offer expiry reminder: the offer to Jane Doe for the VP Operations role "+ "(offer 12) expires in 3 days. DM the principal so they can check in with the "+ "candidate and either record a decision (accepted / declined / expired) or "+ "re-extend.",+]++# Principal-authored follow-ups that share the opening words — must survive.+_NEAR_MISS_INTENTS = [+ "Outreach reminder: chase the Series A investor list before Friday",+ "Interview coordination for the podcast guest — confirm the studio slot",+ "Reference checks (informal) on the new agency before we sign",+ "Onboarding check-in (day 1) with the new fractional CFO about access",+ "Offer expiry reminder: the vendor's discounted quote lapses Monday",+]+++def _insert_reminder(+ db: Path, text: str, *, status: str = "pending", kind: str = "ad_hoc",+ department: str = "", awaiting: bool = False,+) -> int:+ aid = insert_scheduled_action(+ run_at=_future(3600), channel="telegram", channel_ref="123",+ intent_text=text, kind=kind, department=department, db_path=db,+ )+ if status == "running":+ # Simulate a crash mid-dispatch: claimed (running) but never finished.+ import sqlite3+ with sqlite3.connect(db) as conn:+ conn.execute("UPDATE scheduled_actions SET status='running' WHERE id=?", (aid,))+ elif status == "done":+ mark_action_done(aid, db_path=db)+ if awaiting:+ import sqlite3+ with sqlite3.connect(db) as conn:+ conn.execute(+ "UPDATE scheduled_actions SET awaiting_response_since=? WHERE id=?",+ (_past(3600), aid),+ )+ return aid+++def _status(db: Path, aid: int) -> str:+ row = get_scheduled_action(aid, db)+ assert row is not None+ return row.status+++def test_orphan_sweep_cancels_the_five_generated_shapes_and_nothing_else(db: Path) -> None:+ orphans = [_insert_reminder(db, t) for t in _ORPHAN_INTENTS]+ near_misses = [_insert_reminder(db, t) for t in _NEAR_MISS_INTENTS]+ unrelated = _insert_reminder(db, "Follow up with the board candidate on the Q3 deck")+ delivered = _insert_reminder(db, _ORPHAN_INTENTS[0], status="done")+ # Same text, but a department-scoped or non-ad-hoc row is not a talent+ # reminder (those never set a department and were always ad_hoc).+ dept_scoped = _insert_reminder(db, _ORPHAN_INTENTS[0], department="hr")+ other_kind = _insert_reminder(db, _ORPHAN_INTENTS[0], kind="proactive_nudge")++ assert cancel_orphaned_talent_reminders(db) == len(_ORPHAN_INTENTS)++ for aid in orphans:+ row = get_scheduled_action(aid, db)+ assert row is not None and row.status == "cancelled"+ assert "feature removed" in row.last_error+ for aid in near_misses + [unrelated, dept_scoped, other_kind]:+ assert _status(db, aid) == "pending"+ assert _status(db, delivered) == "done"+++def test_orphan_sweep_includes_running_rows(db: Path) -> None:+ """A row left `running` by a crash mid-dispatch is reclaimed to `pending`+ by the scheduler AFTER this sweep runs at boot — so the sweep must take it+ too, or it comes back from the dead."""+ stuck = _insert_reminder(db, _ORPHAN_INTENTS[1], status="running")+ assert cancel_orphaned_talent_reminders(db) == 1+ assert _status(db, stuck) == "cancelled"+++def test_orphan_sweep_clears_awaiting_flag_on_delivered_reminders(db: Path) -> None:+ """Delivered talent reminders still flagged as awaiting a reply would keep+ feeding the nudge engine; the flag goes, the history row stays."""+ delivered = _insert_reminder(db, _ORPHAN_INTENTS[2], status="done", awaiting=True)+ keep = _insert_reminder(db, _NEAR_MISS_INTENTS[2], status="done", awaiting=True)+ assert cancel_orphaned_talent_reminders(db) == 0 # nothing pending to cancel+ swept = get_scheduled_action(delivered, db)+ assert swept is not None and swept.status == "done"+ assert swept.awaiting_response_since is None+ kept = get_scheduled_action(keep, db)+ assert kept is not None and kept.awaiting_response_since is not None+++def test_orphan_sweep_runs_once_per_db(db: Path) -> None:+ """The marker row bounds the sweep: a matching row inserted AFTER the first+ run is left alone, proving later boots do no work."""+ first = _insert_reminder(db, _ORPHAN_INTENTS[0])+ assert cancel_orphaned_talent_reminders(db) == 1++ late = _insert_reminder(db, _ORPHAN_INTENTS[0])+ assert cancel_orphaned_talent_reminders(db) == 0+ assert _status(db, late) == "pending"+ assert _status(db, first) == "cancelled"+++def test_orphan_sweep_marker_is_claimed_atomically(db: Path) -> None:+ """Two boots against one DB: the marker is claimed with INSERT OR IGNORE in+ the sweep's own transaction, so a pre-existing marker means a clean no-op —+ never an IntegrityError."""+ import sqlite3+ with sqlite3.connect(db) as conn:+ conn.execute(+ "INSERT INTO app_migrations (name, applied_at) VALUES (?, ?)",+ ("2026-09-cancel-talent-reminders", "2026-09-17T00:00:00+00:00"),+ )+ orphan = _insert_reminder(db, _ORPHAN_INTENTS[0])+ assert cancel_orphaned_talent_reminders(db) == 0+ assert _status(db, orphan) == "pending"+++def test_orphan_sweep_is_a_noop_on_a_clean_db(db: Path) -> None:+ assert cancel_orphaned_talent_reminders(db) == 0+ assert cancel_orphaned_talent_reminders(db) == 0diff --git a/packages/core/tests/unit/test_staff_onboarding_route.py b/packages/core/tests/unit/test_staff_onboarding_route.pydeleted file mode 100644index 27134d91..00000000--- a/packages/core/tests/unit/test_staff_onboarding_route.py+++ /dev/null@@ -1,118 +0,0 @@-"""HTTP-level tests for the staff-onboarding routes.--Exercises the FastAPI contract (status codes, 404/400 paths, template-instantiation through the route) that the store-level tests don't cover.-"""-from __future__ import annotations--from pathlib import Path--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient--from openexecutive.api.routes import staff_onboarding as route-from openexecutive.staff_onboarding import store---def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:- path = tmp_path / "onboarding.db"- monkeypatch.setattr(store, "DB_PATH", path)- store.initialize_db()- app = FastAPI()- app.include_router(route.router)- return TestClient(app)---def test_template_crud_via_http(client: TestClient) -> None:- body = {- "name": "eng_default",- "title": "Engineering Onboarding",- "department": "engineering",- "ramp_days": 5,- "task_specs": [- {"title": "Provision laptop", "phase": "pre_start",- "owner_role": "it", "due_offset_days": -2},- ],- "brief_sections": ["company_landscape"],- }- resp = client.put("/onboarding-templates/eng_default", json=body)- assert resp.status_code == 200- assert resp.json()["title"] == "Engineering Onboarding"-- # Name mismatch between path and body is a 400.- assert client.put("/onboarding-templates/other", json=body).status_code == 400-- assert client.get("/onboarding-templates/eng_default").status_code == 200- assert client.get("/onboarding-templates/missing").status_code == 404- assert {t["name"] for t in client.get("/onboarding-templates").json()} == {"eng_default"}-- # ramp_days cap (90) — the boundary value is accepted, one past it is a 422.- # Guards against the route/model constraint drifting apart again.- assert client.put(- "/onboarding-templates/eng_default", json={**body, "ramp_days": 90}- ).status_code == 200- assert client.put(- "/onboarding-templates/eng_default", json={**body, "ramp_days": 91}- ).status_code == 422---def test_plan_instantiation_and_tasks_via_http(client: TestClient) -> None:- client.put(- "/onboarding-templates/generic",- json={- "name": "generic",- "title": "Generic",- "task_specs": [- {"title": "1:1 with manager", "phase": "week_1",- "owner_role": "manager", "due_offset_days": 1},- ],- "brief_sections": [],- },- )-- # Create a plan from the template — task is instantiated with a due date.- resp = client.post(- "/onboarding-plans",- json={- "full_name": "Priya Rao",- "start_date": "2026-07-01",- "role": "CFO",- "template_name": "generic",- "manager_person_id": 200,- },- )- assert resp.status_code == 201- plan = resp.json()- plan_id = plan["id"]- assert plan["status"] == "draft"- assert len(plan["tasks"]) == 1- assert plan["tasks"][0]["due_date"] == "2026-07-02"- assert plan["tasks"][0]["owner_person_id"] == 200- task_id = plan["tasks"][0]["id"]-- # Unknown template → 404.- assert client.post(- "/onboarding-plans",- json={"full_name": "X", "start_date": "2026-07-01", "template_name": "nope"},- ).status_code == 404-- # Complete the task → plan completion rolls to 100%.- resp = client.post(f"/onboarding-tasks/{task_id}/status",- json={"status": "done", "completed_by_person_id": 200})- assert resp.status_code == 200- assert resp.json()["completed_at"] is not None- assert client.get(f"/onboarding-plans/{plan_id}").json()["completion_pct"] == 100-- # Advance phase pre_start → week_1.- assert client.post(f"/onboarding-plans/{plan_id}/advance").json()["current_phase"] == "week_1"-- # Archive hides it from the default list.- assert client.post(f"/onboarding-plans/{plan_id}/archive").status_code == 204- assert client.get("/onboarding-plans").json() == []-- # 404s on missing ids.- assert client.get("/onboarding-plans/99999").status_code == 404- assert client.post("/onboarding-tasks/99999/status",- json={"status": "done"}).status_code == 404diff --git a/packages/core/tests/unit/test_staff_onboarding_store.py b/packages/core/tests/unit/test_staff_onboarding_store.pydeleted file mode 100644index 704cfb28..00000000--- a/packages/core/tests/unit/test_staff_onboarding_store.py+++ /dev/null@@ -1,165 +0,0 @@-"""Tests for the staff-onboarding store (staff_onboarding/store.py).--Covers template round-trip (task specs + brief sections survive JSON), plan +-task CRUD, the done/undone completed_at stamping, and the completion_pct rollup-(skipped tasks excluded).-"""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.staff_onboarding import store-from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingStatus,- OnboardingTemplate,- TaskSpec,- TaskStatus,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "onboarding.db"- monkeypatch.setattr(store, "DB_PATH", path)- store.initialize_db()- return path---def test_template_round_trip(db: Path) -> None:- tmpl = OnboardingTemplate(- name="eng_default",- title="Engineering Onboarding",- department="engineering",- ramp_days=5,- checkin_cadence="day_7,day_30",- task_specs=[- TaskSpec(title="Provision laptop", category="it",- phase=OnboardingPhase.PRE_START, owner_role="it", due_offset_days=-2),- TaskSpec(title="Intro 1:1 with manager",- phase=OnboardingPhase.WEEK_1, owner_role="manager", due_offset_days=1),- ],- brief_sections=["company_landscape", "function_state"],- )- store.upsert_template(tmpl)-- got = store.get_template("eng_default")- assert got is not None- assert got.title == "Engineering Onboarding"- assert got.ramp_days == 5- assert len(got.task_specs) == 2- assert got.task_specs[0].owner_role == "it"- assert got.task_specs[0].due_offset_days == -2- assert got.brief_sections == ["company_landscape", "function_state"]- assert got.created_at and got.updated_at---def test_template_list_active_only_and_delete(db: Path) -> None:- store.upsert_template(OnboardingTemplate(name="a", title="A"))- store.upsert_template(OnboardingTemplate(name="b", title="B", is_active=False))-- active = store.list_templates(active_only=True)- assert [t.name for t in active] == ["a"]- assert {t.name for t in store.list_templates(active_only=False)} == {"a", "b"}-- assert store.delete_template("a") is True- assert store.get_template("a") is None- assert store.delete_template("missing") is False---def test_plan_and_task_crud_with_completion(db: Path) -> None:- plan_id = store.create_plan(full_name="Priya Rao", start_date="2026-07-01", role="CFO")- assert plan_id > 0-- t1 = store.add_task(plan_id=plan_id, title="Sign NDA", phase=OnboardingPhase.PRE_START)- t2 = store.add_task(plan_id=plan_id, title="Meet team", phase=OnboardingPhase.WEEK_1)- t3 = store.add_task(plan_id=plan_id, title="Optional reading", phase=OnboardingPhase.WEEK_1)-- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.full_name == "Priya Rao"- assert len(plan.tasks) == 3- assert plan.completion_pct == 0-- # Complete one of three counted tasks → 33%.- assert store.set_task_status(t1, TaskStatus.DONE, completed_by_person_id=9) is True- done_task = store.get_task(t1)- assert done_task is not None- assert done_task.completed_at is not None- assert done_task.completed_by_person_id == 9- assert store.get_plan(plan_id).completion_pct == 33 # type: ignore[union-attr]-- # Skipped tasks are excluded from the denominator: 1 done of 2 counted → 50%.- assert store.set_task_status(t3, TaskStatus.SKIPPED) is True- assert store.get_plan(plan_id).completion_pct == 50 # type: ignore[union-attr]-- # Reverting a done task clears completed_at and drops completion back to 0.- assert store.set_task_status(t1, TaskStatus.PENDING) is True- reverted = store.get_task(t1)- assert reverted is not None- assert reverted.completed_at is None- assert reverted.completed_by_person_id is None- assert store.get_plan(plan_id).completion_pct == 0 # type: ignore[union-attr]-- # list_plans carries completion_pct but not tasks.- assert store.set_task_status(t2, TaskStatus.DONE) is True- listed = store.list_plans()- assert len(listed) == 1- assert listed[0].completion_pct == 50- assert listed[0].tasks == []-- assert store.delete_task(t2) is True- assert store.get_task(t2) is None---def test_update_and_archive_plan(db: Path) -> None:- plan_id = store.create_plan(full_name="Sam Lee", start_date="2026-07-01")-- assert store.update_plan(- plan_id, person_id=42, manager_person_id=7, status=OnboardingStatus.ACTIVE- ) is True- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.person_id == 42- assert plan.manager_person_id == 7- assert plan.status == OnboardingStatus.ACTIVE-- # Empty patch is a no-op.- assert store.update_plan(plan_id) is False-- assert store.archive_plan(plan_id) is True- assert store.list_plans() == [] # archived hidden by default- archived = store.list_plans(include_archived=True)- assert len(archived) == 1- assert archived[0].status == OnboardingStatus.ARCHIVED- # Double-archive is a no-op.- assert store.archive_plan(plan_id) is False---def test_claim_next_ramp_segment(db: Path) -> None:- plan_id = store.create_plan(full_name="Dana", start_date="2026-07-01")- store.update_plan(plan_id, ramp_segments=["day1", "day2"], ramp_next_index=0)-- seg, has_more = store.claim_next_ramp_segment(plan_id)- assert (seg, has_more) == ("day1", True)- seg, has_more = store.claim_next_ramp_segment(plan_id)- assert (seg, has_more) == ("day2", False)- # Exhausted → nothing more, no re-chain.- assert store.claim_next_ramp_segment(plan_id) == (None, False)- # Missing/archived plan → nothing.- assert store.claim_next_ramp_segment(99999) == (None, False)- store.archive_plan(plan_id)- assert store.claim_next_ramp_segment(plan_id) == (None, False)---def test_reading_list_and_brief_persist(db: Path) -> None:- plan_id = store.create_plan(full_name="Dana", start_date="2026-07-01")- assert store.update_plan(- plan_id, brief_artifact="# Welcome\nbody", reading_list=["doc-a", "doc-b"]- ) is True- plan = store.get_plan(plan_id)- assert plan is not None- assert plan.brief_artifact.startswith("# Welcome")- assert plan.reading_list == ["doc-a", "doc-b"]diff --git a/packages/core/tests/unit/test_talent_digest.py b/packages/core/tests/unit/test_talent_digest.pydeleted file mode 100644index 1cc5b32f..00000000--- a/packages/core/tests/unit/test_talent_digest.py+++ /dev/null@@ -1,207 +0,0 @@-"""Tests for the shared talent briefing digest (briefing/talent_digest.py).--Covers the stage rollup math (needs-screening / offers-out / stalled), the-exclusion of terminal engagements, and the chat-digest text — the logic both-/today and the chat <briefing> block depend on.-"""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.briefing import talent_digest-from openexecutive.briefing.talent_digest import (- STALL_THRESHOLD_DAYS,- build_talent_brief_items,- format_talent_for_prompt,-)-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage, EngagementStatus---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---def _backdate_candidate(candidate_id: int, days: int) -> None:- """Force a candidate's updated_at to *days* in the past (for stall tests)."""- from datetime import UTC, datetime, timedelta-- ts = (datetime.now(UTC) - timedelta(days=days)).isoformat()- with talent_store._get_conn() as conn:- conn.execute(- "UPDATE candidates SET updated_at = ? WHERE id = ?", (ts, candidate_id)- )---def test_empty_db_returns_nothing(db: Path) -> None:- assert build_talent_brief_items() == []- assert format_talent_for_prompt() == ""---def test_rollup_counts(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="VP Drilling", department="Drilling")-- # Two leads (need screening), one offer out, one placed (terminal).- talent_store.upsert_candidate(engagement_id=eid, full_name="Lead A", stage=CandidateStage.LEAD)- talent_store.upsert_candidate(engagement_id=eid, full_name="Lead B", stage=CandidateStage.LEAD)- talent_store.upsert_candidate(engagement_id=eid, full_name="Offeree", stage=CandidateStage.OFFER)- talent_store.upsert_candidate(engagement_id=eid, full_name="Hired", stage=CandidateStage.PLACED)-- items = build_talent_brief_items()- assert len(items) == 1- item = items[0]- assert item.engagement_id == eid- assert item.department == "Drilling"- assert item.role_title == "VP Drilling"- assert item.candidate_count == 4- assert item.needs_screening == 2- assert item.offers_out == 1- assert item.stage_counts == {"lead": 2, "offer": 1, "placed": 1}- # Fresh candidates aren't stalled.- assert item.stalled_count == 0---def test_stalled_only_counts_active_stages(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="CFO", department="Finance")-- # An interviewed candidate gone cold past the threshold → stalled.- cold = talent_store.upsert_candidate(- engagement_id=eid, full_name="Cold Interview", stage=CandidateStage.INTERVIEWED- )- _backdate_candidate(cold, STALL_THRESHOLD_DAYS + 3)-- # A placed candidate that is also old must NOT count as stalled (terminal).- placed = talent_store.upsert_candidate(- engagement_id=eid, full_name="Old Hire", stage=CandidateStage.PLACED- )- _backdate_candidate(placed, STALL_THRESHOLD_DAYS + 30)-- # A fresh lead is active but not yet stalled.- talent_store.upsert_candidate(engagement_id=eid, full_name="Fresh Lead", stage=CandidateStage.LEAD)-- item = build_talent_brief_items()[0]- assert item.stalled_count == 1---def test_terminal_engagements_excluded(db: Path) -> None:- open_eid = talent_store.upsert_engagement(role_title="Open Role")- filled_eid = talent_store.upsert_engagement(role_title="Filled Role")- talent_store.set_engagement_status(filled_eid, EngagementStatus.FILLED)-- items = build_talent_brief_items()- ids = {i.engagement_id for i in items}- assert open_eid in ids- assert filled_eid not in ids---def test_format_for_prompt_text(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="VP Drilling", department="Drilling")- talent_store.upsert_candidate(engagement_id=eid, full_name="Lead A", stage=CandidateStage.LEAD)- talent_store.upsert_candidate(engagement_id=eid, full_name="Offeree", stage=CandidateStage.OFFER)-- text = format_talent_for_prompt()- assert f"[eng {eid}]" in text- # In-house line is "[eng N] <role> · <department> (<status>): ..." — no client.- assert "VP Drilling · Drilling (open)" in text- assert "Meridian" not in text- assert "2 candidates" in text- assert "1 need screening" in text- assert "1 offer out" in text---def test_format_for_prompt_omits_department_when_blank(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="CFO")- talent_store.upsert_candidate(engagement_id=eid, full_name="Lead A", stage=CandidateStage.LEAD)-- text = format_talent_for_prompt()- # No department → no " · " separator before the status.- assert f"[eng {eid}] CFO (open)" in text---def test_build_swallows_store_errors(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:- def _boom(**_: object) -> list:- raise RuntimeError("store down")-- monkeypatch.setattr(talent_digest, "_MAX_ENGAGEMENTS", 25)- monkeypatch.setattr(talent_store, "list_engagements", _boom)- # Must not raise — a talent hiccup can never break a brief.- assert build_talent_brief_items() == []- assert format_talent_for_prompt() == ""---# --------------------------------------------------------------------------- #-# Offers expiring soon-# --------------------------------------------------------------------------- #--def _seed_extended_offer(engagement_id: int, candidate_id: int, *, expires_in_hours: float) -> int:- from datetime import UTC, datetime, timedelta-- from openexecutive.talent.models import OfferStatus-- oid = talent_store.create_offer(- candidate_id=candidate_id, engagement_id=engagement_id, comp_summary="x"- )- expiry = (datetime.now(UTC) + timedelta(hours=expires_in_hours)).isoformat()- talent_store.set_offer_status(oid, OfferStatus.EXTENDED, expires_at=expiry)- return oid---def test_offers_expiring_soon_counts_window_and_past(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="VP Drilling")- near = talent_store.upsert_candidate(- engagement_id=eid, full_name="Near", stage=CandidateStage.OFFER- )- overdue = talent_store.upsert_candidate(- engagement_id=eid, full_name="Overdue", stage=CandidateStage.OFFER- )- far = talent_store.upsert_candidate(- engagement_id=eid, full_name="Far", stage=CandidateStage.OFFER- )- _seed_extended_offer(eid, near, expires_in_hours=24) # inside the 72h window- _seed_extended_offer(eid, overdue, expires_in_hours=-6) # past expiry, no decision- _seed_extended_offer(eid, far, expires_in_hours=24 * 10) # well outside-- items = build_talent_brief_items()- assert items[0].offers_expiring_soon == 2-- text = format_talent_for_prompt()- assert "2 offers expiring ≤3d" in text---def test_decided_offers_do_not_count_as_expiring(db: Path) -> None:- from openexecutive.talent.models import OfferStatus-- eid = talent_store.upsert_engagement(role_title="CFO")- cid = talent_store.upsert_candidate(- engagement_id=eid, full_name="Done", stage=CandidateStage.OFFER- )- oid = _seed_extended_offer(eid, cid, expires_in_hours=24)- talent_store.set_offer_status(oid, OfferStatus.ACCEPTED)-- items = build_talent_brief_items()- assert items[0].offers_expiring_soon == 0- assert "expiring" not in format_talent_for_prompt()---def test_expiring_offers_sort_first(db: Path) -> None:- # Engagement A: big pipeline, no expiring offer. Engagement B: one- # expiring offer. B must sort first — it's the most time-critical.- eid_a = talent_store.upsert_engagement(role_title="VP Sales")- for n in range(5):- talent_store.upsert_candidate(- engagement_id=eid_a, full_name=f"Lead {n}", stage=CandidateStage.LEAD- )- eid_b = talent_store.upsert_engagement(role_title="CFO")- cid_b = talent_store.upsert_candidate(- engagement_id=eid_b, full_name="Closer", stage=CandidateStage.OFFER- )- _seed_extended_offer(eid_b, cid_b, expires_in_hours=24)-- items = build_talent_brief_items()- assert items[0].engagement_id == eid_bdiff --git a/packages/core/tests/unit/test_talent_graph.py b/packages/core/tests/unit/test_talent_graph.pydeleted file mode 100644index 80f72103..00000000--- a/packages/core/tests/unit/test_talent_graph.py+++ /dev/null@@ -1,285 +0,0 @@-"""Tests for the talent graph (semantic candidate matching).--Uses an in-memory ranking fake store so there's no chromadb / embedding /-network dependency. The fake ranks by token overlap with the query, which is-enough to assert ordering, filtering, and the score mapping deterministically.-"""-from __future__ import annotations--import re-from pathlib import Path-from typing import Any--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient--from openexecutive.api.routes import talent as talent_route-from openexecutive.talent import graph as talent_graph-from openexecutive.talent import store as talent_store-from openexecutive.talent.graph import CANDIDATES_COLLECTION---def _tokens(text: str) -> set[str]:- return set(re.findall(r"[a-z0-9]+", text.lower()))---class RankingFakeStore:- """In-memory KnowledgeStore that ranks by query/doc token overlap."""-- def __init__(self) -> None:- self.collections: dict[str, list[dict[str, Any]]] = {}- self.add_calls = 0-- def add_documents(self, texts, metadatas, ids, collection) -> None:- self.add_calls += 1- col = self.collections.setdefault(collection, [])- for t, m, i in zip(texts, metadatas, ids, strict=False):- col[:] = [r for r in col if r["id"] != i]- col.append({"id": i, "text": t, "metadata": m})-- def delete_documents(self, collection, where) -> None:- col = self.collections.get(collection, [])- self.collections[collection] = [- r for r in col- if not all(r["metadata"].get(k) == v for k, v in where.items())- ]-- def query(self, query_text, collection, domain_filter=None, n_results=5):- col = self.collections.get(collection, [])- q = _tokens(query_text)- scored = []- for r in col:- overlap = len(q & _tokens(r["text"]))- distance = 1.0 - (overlap / len(q) if q else 0.0)- scored.append((distance, r))- scored.sort(key=lambda x: x[0])- return [- {"text": r["text"], "metadata": r["metadata"], "distance": d}- for d, r in scored[:n_results]- ]---class ExplodingStore:- """Raises on every op — to prove indexing is best-effort."""-- def add_documents(self, *a, **k):- raise RuntimeError("vector store down")-- def delete_documents(self, *a, **k):- raise RuntimeError("vector store down")-- def query(self, *a, **k):- raise RuntimeError("vector store down")---def test_score_clamps_both_ends() -> None:- from openexecutive.talent.graph import _score-- assert _score(0.0) == 1.0- assert _score(0.2) == 0.8- assert _score(1.5) == 0.0 # poor match clamps to 0- assert _score(-0.0001) == 1.0 # float artifact clamps to 1, not >1- assert _score(None) == 0.0---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---def _engagement(must_haves: str = "upstream drilling") -> int:- return talent_store.upsert_engagement(- role_title="VP Drilling", department="Drilling", must_haves=must_haves- )---# --------------------------------------------------------------------------- #-# Indexing-# --------------------------------------------------------------------------- #--def test_index_candidate_writes_doc_with_metadata(db: Path) -> None:- eid = _engagement()- cid = talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", current_title="Drilling Director"- )- store = RankingFakeStore()- talent_graph.index_candidate(talent_store.get_candidate(cid), store) # type: ignore[arg-type]- rows = store.collections[CANDIDATES_COLLECTION]- assert len(rows) == 1- assert rows[0]["metadata"]["candidate_id"] == cid- assert rows[0]["metadata"]["engagement_id"] == eid- assert rows[0]["metadata"]["stage"] == "lead"- assert "Dana Cole" in rows[0]["text"]---def test_index_candidate_archived_is_removed(db: Path) -> None:- eid = _engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- store = RankingFakeStore()- talent_graph.index_candidate(talent_store.get_candidate(cid), store) # type: ignore[arg-type]- assert store.collections[CANDIDATES_COLLECTION]-- talent_store.archive_candidate(cid)- talent_graph.index_candidate(talent_store.get_candidate(cid), store) # type: ignore[arg-type]- assert store.collections[CANDIDATES_COLLECTION] == []---def test_index_candidate_best_effort_swallows_errors(db: Path) -> None:- eid = _engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- # Must not raise even though the store explodes.- talent_graph.index_candidate(talent_store.get_candidate(cid), ExplodingStore()) # type: ignore[arg-type]---# --------------------------------------------------------------------------- #-# Matching-# --------------------------------------------------------------------------- #--def test_match_ranks_pool_by_must_haves(db: Path) -> None:- eid = _engagement(must_haves="offshore deepwater drilling subsea")- store = RankingFakeStore()- # Strong match on the must-haves vs. an unrelated finance profile.- strong = talent_store.upsert_candidate(- engagement_id=eid, full_name="Strong Fit",- current_title="Offshore Deepwater Drilling Lead", notes="subsea wells",- )- weak = talent_store.upsert_candidate(- engagement_id=eid, full_name="Weak Fit",- current_title="Corporate Treasury Analyst", notes="hedging cash",- )- for c in (strong, weak):- talent_graph.index_candidate(talent_store.get_candidate(c), store) # type: ignore[arg-type]-- eng = talent_store.get_engagement(eid)- matches = talent_graph.match_candidates_for_engagement(eng, store, limit=10) # type: ignore[arg-type]- assert [m["candidate_id"] for m in matches][0] == strong- assert matches[0]["score"] >= matches[-1]["score"]- assert all(0.0 <= m["score"] <= 1.0 for m in matches)---def test_match_respects_limit(db: Path) -> None:- eid = _engagement()- store = RankingFakeStore()- for i in range(5):- c = talent_store.upsert_candidate(- engagement_id=eid, full_name=f"Cand {i}", current_title="Driller"- )- talent_graph.index_candidate(talent_store.get_candidate(c), store) # type: ignore[arg-type]- eng = talent_store.get_engagement(eid)- assert len(talent_graph.match_candidates_for_engagement(eng, store, limit=2)) == 2 # type: ignore[arg-type]- assert talent_graph.match_candidates_for_engagement(eng, store, limit=0) == [] # type: ignore[arg-type]---def test_match_empty_must_haves_returns_empty(db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="")- store = RankingFakeStore()- eng = talent_store.get_engagement(eid)- assert talent_graph.match_candidates_for_engagement(eng, store) == [] # type: ignore[arg-type]---# --------------------------------------------------------------------------- #-# Similar-# --------------------------------------------------------------------------- #--def test_similar_excludes_self(db: Path) -> None:- eid = _engagement()- store = RankingFakeStore()- a = talent_store.upsert_candidate(- engagement_id=eid, full_name="Alpha Driller", current_title="Drilling Engineer"- )- b = talent_store.upsert_candidate(- engagement_id=eid, full_name="Beta Driller", current_title="Drilling Engineer"- )- for c in (a, b):- talent_graph.index_candidate(talent_store.get_candidate(c), store) # type: ignore[arg-type]-- cand_a = talent_store.get_candidate(a)- similar = talent_graph.find_similar_candidates(cand_a, store, limit=5) # type: ignore[arg-type]- ids = [m["candidate_id"] for m in similar]- assert a not in ids- assert b in ids---# --------------------------------------------------------------------------- #-# Reindex-# --------------------------------------------------------------------------- #--def test_reindex_all_upserts_active_drops_archived(db: Path) -> None:- eid = _engagement()- active = talent_store.upsert_candidate(engagement_id=eid, full_name="Active One")- gone = talent_store.upsert_candidate(engagement_id=eid, full_name="Gone One")- talent_store.archive_candidate(gone)-- store = RankingFakeStore()- # Pre-seed a stale archived doc to prove reindex removes it.- store.add_documents(- ["stale"], [{"candidate_id": gone, "engagement_id": eid, "stage": "lead"}],- [f"candidate-{gone}"], CANDIDATES_COLLECTION,- )- n = talent_graph.reindex_all(store)- assert n == 1- rows = store.collections[CANDIDATES_COLLECTION]- ids = [r["metadata"]["candidate_id"] for r in rows]- assert active in ids- assert gone not in ids---# --------------------------------------------------------------------------- #-# API endpoints-# --------------------------------------------------------------------------- #--def client(db: Path) -> TestClient:- app = FastAPI()- app.include_router(talent_route.router)- app.state.store = RankingFakeStore()- return TestClient(app)---def test_matches_endpoint(client: TestClient, db: Path) -> None:- eid = talent_store.upsert_engagement(- role_title="VP Drilling", must_haves="offshore deepwater drilling"- )- # Create via the API so the route indexes into app.state.store.- client.post("/candidates", json={- "engagement_id": eid, "full_name": "Strong Fit",- "current_title": "Offshore Deepwater Drilling Lead",- })- client.post("/candidates", json={- "engagement_id": eid, "full_name": "Weak Fit",- "current_title": "Treasury Analyst",- })- resp = client.get(f"/engagements/{eid}/matches?limit=5")- assert resp.status_code == 200- body = resp.json()- assert body and body[0]["candidate_id"] is not None- assert body[0]["score"] >= body[-1]["score"]---def test_matches_unknown_engagement_404(client: TestClient) -> None:- assert client.get("/engagements/9999/matches").status_code == 404---def test_similar_endpoint_excludes_self(client: TestClient, db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="VP Drilling")- a = client.post("/candidates", json={- "engagement_id": eid, "full_name": "Alpha", "current_title": "Drilling Engineer",- }).json()["id"]- client.post("/candidates", json={- "engagement_id": eid, "full_name": "Beta", "current_title": "Drilling Engineer",- })- resp = client.get(f"/candidates/{a}/similar?limit=5")- assert resp.status_code == 200- assert a not in [m["candidate_id"] for m in resp.json()]---def test_reindex_endpoint(client: TestClient, db: Path) -> None:- eid = talent_store.upsert_engagement(role_title="VP Drilling")- talent_store.upsert_candidate(engagement_id=eid, full_name="Direct Insert")- resp = client.post("/talent/reindex")- assert resp.status_code == 200- assert resp.json()["indexed"] == 1diff --git a/packages/core/tests/unit/test_talent_offer_tools.py b/packages/core/tests/unit/test_talent_offer_tools.pydeleted file mode 100644index b12eda04..00000000--- a/packages/core/tests/unit/test_talent_offer_tools.py+++ /dev/null@@ -1,350 +0,0 @@-"""Tests for the offer chat tools (list/create/extend/record_offer_decision)."""-from __future__ import annotations--import asyncio-import json-from pathlib import Path--import pytest--from openexecutive.memory import episodic-from openexecutive.orchestrator.talent_tools import (- TALENT_TOOL_HANDLERS,- handle_create_offer,- handle_extend_offer,- handle_list_offers,- handle_record_offer_decision,- handle_set_candidate_stage,-)-from openexecutive.people import store as people_store-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage, EngagementStatus, OfferStatus-from openexecutive.workflows import persistence as wf_persistence---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- """Shared episodic_memory.db; persistence.DB_PATH is a separate import-time- binding from episodic.DB_PATH, so it needs its own monkeypatch."""- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- monkeypatch.setattr(wf_persistence, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- wf_persistence.initialize_runs_db(path)- return path---def _seed_candidate(stage: CandidateStage = CandidateStage.INTERVIEWED) -> int:- eid = talent_store.upsert_engagement(role_title="VP Drilling", comp_band="300k")- return talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", email="[email protected]", stage=stage,- )---def _seed_principal() -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email="[email protected]",- preferred_channel="email", # type: ignore[arg-type]- )---def _create_offer(candidate_id: int) -> dict:- return json.loads(asyncio.run(handle_create_offer({- "candidate_id": candidate_id, "comp_summary": "base 300k, 0.5% equity",- })))---def test_all_offer_tools_registered() -> None:- for name in ("list_offers", "create_offer", "extend_offer", "record_offer_decision"):- assert name in TALENT_TOOL_HANDLERS---# --------------------------------------------------------------------------- #-# create_offer / list_offers-# --------------------------------------------------------------------------- #--def test_create_offer_happy_path(db: Path) -> None:- cand_id = _seed_candidate()- out = _create_offer(cand_id)- assert out["status"] == "ok"- assert out["offer"]["status"] == "draft"- assert out["offer"]["candidate_id"] == cand_id- assert "never sends offers" in out["presentation_hint"]---def test_create_offer_unknown_candidate(db: Path) -> None:- out = json.loads(asyncio.run(handle_create_offer({- "candidate_id": 999, "comp_summary": "x",- })))- assert out["status"] == "not_found"---def test_create_offer_rejects_duplicate_open_offer(db: Path) -> None:- cand_id = _seed_candidate()- _create_offer(cand_id)- out = json.loads(asyncio.run(handle_create_offer({- "candidate_id": cand_id, "comp_summary": "y",- })))- assert "already has an open offer" in out["error"]---def test_create_offer_length_cap(db: Path) -> None:- cand_id = _seed_candidate()- out = json.loads(asyncio.run(handle_create_offer({- "candidate_id": cand_id, "comp_summary": "x" * 8001,- })))- assert "too long" in out["error"]---def test_list_offers_filters_by_status(db: Path) -> None:- cand_id = _seed_candidate()- _create_offer(cand_id)- out = json.loads(asyncio.run(handle_list_offers({"status": "draft"})))- assert out["count"] == 1- out = json.loads(asyncio.run(handle_list_offers({"status": "extended"})))- assert out["count"] == 0- out = json.loads(asyncio.run(handle_list_offers({"status": "bogus"})))- assert "invalid status" in out["error"]---# --------------------------------------------------------------------------- #-# extend_offer-# --------------------------------------------------------------------------- #--def test_extend_offer_schedules_expiry_nudges_to_principal(db: Path) -> None:- cand_id = _seed_candidate()- principal_id = _seed_principal()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- out = json.loads(asyncio.run(handle_extend_offer({- "offer_id": offer_id, "expires_in_days": 7,- })))- assert out["status"] == "ok"- assert out["offer"]["status"] == "extended"- assert out["offer"]["expires_at"]- # No approval run exists — flagged, not blocked (principal's terminal).- assert out["approval_state"] == "none"- assert any("without a recorded HIRING_SIGNOFF" in w for w in out["warnings"])-- # T-3d and T-1d are future (7-day expiry), plus the T+12h past-expiry nudge.- assert out["nudges_scheduled"] == 3- pending = episodic.list_scheduled_actions(status="pending")- assert len(pending) == 3- for action in pending:- assert action.kind == "ad_hoc"- assert action.assigned_to_person_id == principal_id- assert "[email protected]" not in action.channel_ref---def test_extend_offer_short_expiry_skips_past_nudges(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- out = json.loads(asyncio.run(handle_extend_offer({- "offer_id": offer_id, "expires_in_days": 2,- })))- # T-3d is already past; only T-1d and T+12h get scheduled.- assert out["nudges_scheduled"] == 2---def test_extend_offer_blocked_by_recorded_rejection(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- from openexecutive.talent import offers as talent_offers- monkeypatch.setattr(- talent_offers, "find_offer_approval",- lambda _oid: {"run_id": "r1", "status": "resolved", "decision": "reject", "person_id": 2},- )- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id})))- assert "rejected" in out["error"]- offer = talent_store.get_offer(offer_id)- assert offer is not None and offer.status is OfferStatus.DRAFT---def test_extend_offer_stamps_recorded_approval(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- from openexecutive.talent import offers as talent_offers- monkeypatch.setattr(- talent_offers, "find_offer_approval",- lambda _oid: {"run_id": "r1", "status": "resolved", "decision": "approve", "person_id": 7},- )- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id})))- assert out["approval_state"] == "approved"- assert out["warnings"] == []- offer = talent_store.get_offer(offer_id)- assert offer is not None- assert offer.approval_run_id == "r1"- assert offer.approved_by_person_id == 7---def test_extend_offer_validates_inputs(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id, "expires_in_days": 0})))- assert "1-60" in out["error"]- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id, "expires_at": "nope"})))- assert "ISO" in out["error"]- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": 999})))- assert "not found" in out["error"]---def test_extend_offer_without_principal_still_extends_with_warning(db: Path) -> None:- cand_id = _seed_candidate()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id})))- assert out["status"] == "ok"- assert out["nudges_scheduled"] == 0- assert any("no expiry reminders" in w.lower() for w in out["warnings"])---# --------------------------------------------------------------------------- #-# record_offer_decision-# --------------------------------------------------------------------------- #--def _extended_offer(cand_id: int) -> int:- offer_id = _create_offer(cand_id)["offer"]["offer_id"]- json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id})))- return offer_id---def test_accepted_places_candidate_fills_engagement_and_cancels_nudges(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _extended_offer(cand_id)- assert len(episodic.list_scheduled_actions(status="pending")) == 3-- out = json.loads(asyncio.run(handle_record_offer_decision({- "offer_id": offer_id, "decision": "accepted",- })))- assert out["status"] == "ok"- assert out["offer"]["status"] == "accepted"- assert out["cancelled_nudges"] == 3- assert "new_hire_onboarding" in out["next_step"]-- cand = talent_store.get_candidate(cand_id)- assert cand is not None and cand.stage is CandidateStage.PLACED- eng = talent_store.get_engagement(cand.engagement_id)- assert eng is not None and eng.status is EngagementStatus.FILLED- assert episodic.list_scheduled_actions(status="pending") == []---def test_declined_leaves_candidate_stage_untouched(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _extended_offer(cand_id)-- out = json.loads(asyncio.run(handle_record_offer_decision({- "offer_id": offer_id, "decision": "declined", "note": "took a competing offer",- })))- assert out["status"] == "ok"- assert out["side_effects"] == []- assert "next_step" not in out- cand = talent_store.get_candidate(cand_id)- assert cand is not None and cand.stage is CandidateStage.INTERVIEWED---def test_decision_requires_legal_transition(db: Path) -> None:- cand_id = _seed_candidate()- offer_id = _create_offer(cand_id)["offer"]["offer_id"] # still draft-- out = json.loads(asyncio.run(handle_record_offer_decision({- "offer_id": offer_id, "decision": "accepted",- })))- assert "not a legal transition" in out["error"]- # Rescind, however, is legal straight from draft.- out = json.loads(asyncio.run(handle_record_offer_decision({- "offer_id": offer_id, "decision": "rescinded",- })))- assert out["status"] == "ok"---def test_decision_rejects_non_terminal_value(db: Path) -> None:- cand_id = _seed_candidate()- _seed_principal()- offer_id = _extended_offer(cand_id)- out = json.loads(asyncio.run(handle_record_offer_decision({- "offer_id": offer_id, "decision": "draft",- })))- assert "must be terminal" in out["error"]---# --------------------------------------------------------------------------- #-# set_candidate_stage suggestion-# --------------------------------------------------------------------------- #--def test_set_stage_placed_suggests_offer_and_onboarding(db: Path) -> None:- cand_id = _seed_candidate()- out = json.loads(asyncio.run(handle_set_candidate_stage({- "candidate_id": cand_id, "stage": "placed",- })))- assert out["status"] == "ok"- assert "record_offer_decision" in out["onboarding_suggestion"]- assert "new_hire_onboarding" in out["onboarding_suggestion"]- # And the suggestion stays read-only: no offer rows, stage is the only write.- assert talent_store.list_offers(candidate_id=cand_id) == []-- out = json.loads(asyncio.run(handle_set_candidate_stage({- "candidate_id": cand_id, "stage": "interviewed",- })))- assert "onboarding_suggestion" not in out---def test_recorded_rejection_survives_failed_run_noise(db: Path) -> None:- """find_offer_approval must not let failed runs push a recorded rejection- out of its scan window (it scans per gate-relevant status)."""- import json as _json-- from openexecutive.talent.offers import offer_approval_state- from openexecutive.workflows.wait_for_human import (- WaitForHumanEvent,- WaitForHumanResolution,- )-- cand_id = _seed_candidate()- offer_id = _create_offer(cand_id)["offer"]["offer_id"]-- gate_run = "gate-run-1"- wf_persistence.create_run(gate_run, "offer_approval", "gate", {})- wf_persistence.save_checkpoint(- run_id=gate_run,- state_json=WaitForHumanEvent(- person_id=1,- question="approve?",- context_summary=f"offer_id={offer_id} — offer approval for Dana Cole (VP Drilling)",- ).model_dump_json(),- awaiting_person_id=1,- awaiting_until=None,- )- wf_persistence.store_resolution(- gate_run,- _json.dumps(- WaitForHumanResolution(- run_id=gate_run, reply_text="no", source_channel="slack",- parsed_decision={"decision": "reject", "note": "comp too high"},- person_id=1,- ).model_dump()- ),- )- # Bury the resolved gate under a pile of newer failed offer_approval runs- # (more than one scan window's worth).- for n in range(250):- rid = f"failed-{n}"- wf_persistence.create_run(rid, "offer_approval", "boom", {})- wf_persistence.fail_run(rid, "exploded before the gate")-- assert offer_approval_state(offer_id) == "rejected"- out = json.loads(asyncio.run(handle_extend_offer({"offer_id": offer_id})))- assert "rejected" in out["error"]diff --git a/packages/core/tests/unit/test_talent_offers_route.py b/packages/core/tests/unit/test_talent_offers_route.pydeleted file mode 100644index fc917d9f..00000000--- a/packages/core/tests/unit/test_talent_offers_route.py+++ /dev/null@@ -1,178 +0,0 @@-"""HTTP-level tests for the /offers routes (close-the-hire-loop)."""-from __future__ import annotations--from pathlib import Path--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient--from openexecutive.api.routes import talent as talent_route-from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.talent import store as talent_store-from openexecutive.workflows import persistence as wf_persistence---class _NoopStore:- def add_documents(self, *a, **k) -> None: ...- def delete_documents(self, *a, **k) -> None: ...- def query(self, *a, **k): # noqa: ANN001, ANN201- return []---def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- monkeypatch.setattr(wf_persistence, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- wf_persistence.initialize_runs_db(path)-- app = FastAPI()- app.include_router(talent_route.router)- app.state.store = _NoopStore()- return TestClient(app)---def _seed_candidate(client: TestClient) -> int:- eng = client.post("/engagements", json={"role_title": "VP Drilling"})- assert eng.status_code == 201- cand = client.post(- "/candidates",- json={- "engagement_id": eng.json()["id"],- "full_name": "Dana Cole",- "stage": "interviewed",- },- )- assert cand.status_code == 201- return cand.json()["id"]---def _seed_principal() -> int:- return people_store.upsert_person(- full_name="Alex Rivera", is_principal=True, email="[email protected]",- preferred_channel="email", # type: ignore[arg-type]- )---def _create_offer(client: TestClient, candidate_id: int) -> int:- resp = client.post(- "/offers", json={"candidate_id": candidate_id, "comp_summary": "base 300k"}- )- assert resp.status_code == 201- return resp.json()["id"]---def test_offers_empty(client: TestClient) -> None:- assert client.get("/offers").json() == []---def test_create_get_list_offer(client: TestClient) -> None:- cand_id = _seed_candidate(client)- oid = _create_offer(client, cand_id)-- got = client.get(f"/offers/{oid}")- assert got.status_code == 200- assert got.json()["status"] == "draft"- assert got.json()["comp_summary"] == "base 300k"-- assert len(client.get("/offers").json()) == 1- assert client.get(f"/offers?candidate_id={cand_id}").json()[0]["id"] == oid- assert client.get("/offers?status=extended").json() == []---def test_create_offer_404_unknown_candidate(client: TestClient) -> None:- resp = client.post("/offers", json={"candidate_id": 999, "comp_summary": "x"})- assert resp.status_code == 404---def test_create_offer_409_when_open_offer_exists(client: TestClient) -> None:- cand_id = _seed_candidate(client)- _create_offer(client, cand_id)- resp = client.post("/offers", json={"candidate_id": cand_id, "comp_summary": "y"})- assert resp.status_code == 409---def test_patch_offer_terms_only_while_pre_extension(client: TestClient) -> None:- cand_id = _seed_candidate(client)- _seed_principal()- oid = _create_offer(client, cand_id)-- resp = client.patch(f"/offers/{oid}", json={"comp_summary": "base 320k"})- assert resp.status_code == 200- assert resp.json()["comp_summary"] == "base 320k"-- assert client.post(f"/offers/{oid}/extend", json={}).status_code == 200- resp = client.patch(f"/offers/{oid}", json={"comp_summary": "base 999k"})- assert resp.status_code == 409---def test_extend_then_decide_accepted(client: TestClient) -> None:- cand_id = _seed_candidate(client)- _seed_principal()- oid = _create_offer(client, cand_id)-- ext = client.post(f"/offers/{oid}/extend", json={"expires_in_days": 7})- assert ext.status_code == 200- body = ext.json()- assert body["offer"]["status"] == "extended"- assert body["nudges_scheduled"] == 3- assert body["approval_state"] == "none"- assert body["warnings"] # extended without recorded sign-off → flagged-- dec = client.post(f"/offers/{oid}/decision", json={"decision": "accepted"})- assert dec.status_code == 200- body = dec.json()- assert body["offer"]["status"] == "accepted"- assert body["cancelled_nudges"] == 3- assert any("placed" in s for s in body["side_effects"])- assert any("filled" in s for s in body["side_effects"])-- cand = client.get(f"/candidates/{cand_id}").json()- assert cand["stage"] == "placed"- eng = client.get(f"/engagements/{cand['engagement_id']}").json()- assert eng["status"] == "filled"---def test_extend_bad_expiry_is_400(client: TestClient) -> None:- cand_id = _seed_candidate(client)- _seed_principal()- oid = _create_offer(client, cand_id)- resp = client.post(f"/offers/{oid}/extend", json={"expires_at": "not-a-date"})- assert resp.status_code == 400---def test_extend_wrong_status_is_409(client: TestClient) -> None:- cand_id = _seed_candidate(client)- _seed_principal()- oid = _create_offer(client, cand_id)- client.post(f"/offers/{oid}/extend", json={})- resp = client.post(f"/offers/{oid}/extend", json={})- assert resp.status_code == 409---def test_decision_illegal_transition_is_409(client: TestClient) -> None:- cand_id = _seed_candidate(client)- oid = _create_offer(client, cand_id) # still draft- resp = client.post(f"/offers/{oid}/decision", json={"decision": "accepted"})- assert resp.status_code == 409---def test_decision_unknown_offer_is_404(client: TestClient) -> None:- resp = client.post("/offers/999/decision", json={"decision": "accepted"})- assert resp.status_code == 404---def test_archive_offer(client: TestClient) -> None:- cand_id = _seed_candidate(client)- oid = _create_offer(client, cand_id)- assert client.post(f"/offers/{oid}/archive").status_code == 204- assert client.get("/offers").json() == []- assert client.get("/offers?include_archived=true").json()[0]["id"] == oid- assert client.post("/offers/999/archive").status_code == 404diff --git a/packages/core/tests/unit/test_talent_offers_store.py b/packages/core/tests/unit/test_talent_offers_store.pydeleted file mode 100644index 997937ae..00000000--- a/packages/core/tests/unit/test_talent_offers_store.py+++ /dev/null@@ -1,224 +0,0 @@-"""Tests for the offers table in the talent store (close-the-hire-loop)."""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.talent import store as talent_store-from openexecutive.talent.models import (- TERMINAL_OFFER_STATUSES,- OfferStatus,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---def _seed_candidate(role_title: str = "VP Drilling") -> int:- eid = talent_store.upsert_engagement(role_title=role_title)- return talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")---def _make_offer(candidate_id: int, **kwargs) -> int:- cand = talent_store.get_candidate(candidate_id)- assert cand is not None- return talent_store.create_offer(- candidate_id=candidate_id,- engagement_id=cand.engagement_id,- comp_summary="base 300k, 0.5% equity",- **kwargs,- )---# --------------------------------------------------------------------------- #-# Create / read-# --------------------------------------------------------------------------- #--def test_create_and_get_offer(db: Path) -> None:- cid = _seed_candidate()- oid = _make_offer(cid, note="strong finalist")-- offer = talent_store.get_offer(oid)- assert offer is not None- assert offer.candidate_id == cid- assert offer.status is OfferStatus.DRAFT- assert offer.comp_summary == "base 300k, 0.5% equity"- assert offer.note == "strong finalist"- assert offer.created_at and offer.updated_at- assert offer.expires_at is None- assert offer.nudge_action_ids == []---def test_one_open_offer_per_candidate(db: Path) -> None:- cid = _seed_candidate()- _make_offer(cid)- with pytest.raises(ValueError, match="already has an open offer"):- _make_offer(cid)---def test_terminal_offer_frees_the_slot(db: Path) -> None:- cid = _seed_candidate()- first = _make_offer(cid)- talent_store.set_offer_status(first, OfferStatus.EXTENDED)- talent_store.set_offer_status(first, OfferStatus.DECLINED)- # A decided offer is history — a new one can be created.- second = _make_offer(cid)- assert second != first- assert talent_store.get_open_offer_for_candidate(cid).id == second # type: ignore[union-attr]---def test_create_rejects_non_insert_statuses(db: Path) -> None:- cid = _seed_candidate()- with pytest.raises(ValueError, match="draft/pending_approval"):- _make_offer(cid, status=OfferStatus.EXTENDED)---def test_get_open_offer_ignores_archived(db: Path) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)- assert talent_store.get_open_offer_for_candidate(cid) is not None- talent_store.archive_offer(oid)- assert talent_store.get_open_offer_for_candidate(cid) is None---def test_list_offers_filters(db: Path) -> None:- cid_a = _seed_candidate("VP Drilling")- cid_b = _seed_candidate("CFO")- oid_a = _make_offer(cid_a)- _make_offer(cid_b)-- assert len(talent_store.list_offers()) == 2- assert [o.id for o in talent_store.list_offers(candidate_id=cid_a)] == [oid_a]- talent_store.set_offer_status(oid_a, OfferStatus.EXTENDED)- extended = talent_store.list_offers(status=OfferStatus.EXTENDED)- assert [o.id for o in extended] == [oid_a]-- cand_b = talent_store.get_candidate(cid_b)- assert cand_b is not None- by_eng = talent_store.list_offers(engagement_id=cand_b.engagement_id)- assert len(by_eng) == 1---# --------------------------------------------------------------------------- #-# Transition matrix-# --------------------------------------------------------------------------- #--def test_legal_forward_path_stamps_timestamps(db: Path) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)-- assert talent_store.set_offer_status(oid, OfferStatus.PENDING_APPROVAL)- assert talent_store.set_offer_status(- oid, OfferStatus.EXTENDED, expires_at="2030-01-01T00:00:00+00:00",- nudge_action_ids=[11, 12],- )- offer = talent_store.get_offer(oid)- assert offer is not None- assert offer.extended_at != ""- assert offer.expires_at == "2030-01-01T00:00:00+00:00"- assert offer.nudge_action_ids == [11, 12]- assert offer.decided_at == ""-- assert talent_store.set_offer_status(oid, OfferStatus.ACCEPTED)- offer = talent_store.get_offer(oid)- assert offer is not None- assert offer.decided_at != ""---def test_pending_can_fall_back_to_draft(db: Path) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)- talent_store.set_offer_status(oid, OfferStatus.PENDING_APPROVAL)- assert talent_store.set_offer_status(oid, OfferStatus.DRAFT)--[email protected]("bad_target", [- OfferStatus.ACCEPTED, OfferStatus.DECLINED, OfferStatus.EXPIRED,-])-def test_draft_cannot_jump_to_terminal_decisions(db: Path, bad_target: OfferStatus) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)- assert not talent_store.set_offer_status(oid, bad_target)- offer = talent_store.get_offer(oid)- assert offer is not None and offer.status is OfferStatus.DRAFT---def test_rescind_works_from_every_open_status(db: Path) -> None:- for setup in (- [],- [OfferStatus.PENDING_APPROVAL],- [OfferStatus.PENDING_APPROVAL, OfferStatus.EXTENDED],- ):- cid = _seed_candidate()- oid = _make_offer(cid)- for step in setup:- assert talent_store.set_offer_status(oid, step)- assert talent_store.set_offer_status(oid, OfferStatus.RESCINDED)--[email protected]("terminal", sorted(TERMINAL_OFFER_STATUSES))-def test_terminal_statuses_are_immutable(db: Path, terminal: OfferStatus) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)- talent_store.set_offer_status(oid, OfferStatus.EXTENDED)- assert talent_store.set_offer_status(oid, terminal)- for target in OfferStatus:- assert not talent_store.set_offer_status(oid, target), (- f"{terminal.value} -> {target.value} should be illegal"- )---def test_set_status_unknown_or_archived_offer(db: Path) -> None:- assert not talent_store.set_offer_status(999, OfferStatus.EXTENDED)- cid = _seed_candidate()- oid = _make_offer(cid)- talent_store.archive_offer(oid)- assert not talent_store.set_offer_status(oid, OfferStatus.EXTENDED)---# --------------------------------------------------------------------------- #-# Terms editing-# --------------------------------------------------------------------------- #--def test_update_terms_only_pre_extension(db: Path) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)-- assert talent_store.update_offer_terms(oid, comp_summary="base 320k", package_md="# Pkg")- offer = talent_store.get_offer(oid)- assert offer is not None- assert offer.comp_summary == "base 320k"- assert offer.package_md == "# Pkg"-- talent_store.set_offer_status(oid, OfferStatus.EXTENDED)- assert not talent_store.update_offer_terms(oid, comp_summary="base 999k")- offer = talent_store.get_offer(oid)- assert offer is not None and offer.comp_summary == "base 320k"---def test_update_terms_with_no_fields_is_noop(db: Path) -> None:- cid = _seed_candidate()- oid = _make_offer(cid)- assert not talent_store.update_offer_terms(oid)---def test_db_level_backstop_blocks_concurrent_second_open_offer(db: Path) -> None:- """The partial unique index catches a create that races past the SELECT guard."""- import sqlite3-- cid = _seed_candidate()- _make_offer(cid)- # Bypass create_offer's SELECT guard to simulate the losing racer's INSERT.- with pytest.raises(sqlite3.IntegrityError), talent_store._get_conn() as conn:- conn.execute(- "INSERT INTO offers (candidate_id, engagement_id, status, comp_summary,"- " package_md, note, created_at, updated_at)"- " VALUES (?, ?, 'draft', '', '', '', '2026-01-01', '2026-01-01')",- (cid, talent_store.get_candidate(cid).engagement_id), # type: ignore[union-attr]- )diff --git a/packages/core/tests/unit/test_talent_onboarding_suggest.py b/packages/core/tests/unit/test_talent_onboarding_suggest.pydeleted file mode 100644index 3f7f031f..00000000--- a/packages/core/tests/unit/test_talent_onboarding_suggest.py+++ /dev/null@@ -1,49 +0,0 @@-"""The talent → onboarding suggest-on-placed hook.--Moving a candidate to `placed` via the chat tool surfaces an onboarding-suggestion; other stages do not. No auto-fire, no candidate messaging.-"""-from __future__ import annotations--import json-from pathlib import Path--import pytest--from openexecutive.orchestrator import talent_tools-from openexecutive.talent import store as talent_store---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---def _candidate(db: Path) -> int:- eid = talent_store.upsert_engagement(role_title="VP Engineering", department="product")- return talent_store.upsert_candidate(engagement_id=eid, full_name="Priya Rao")---async def test_placed_surfaces_onboarding_suggestion(db: Path) -> None:- cid = _candidate(db)- res = json.loads(await talent_tools.handle_set_candidate_stage(- {"candidate_id": cid, "stage": "placed"}- ))- assert res["status"] == "ok"- assert "onboarding_suggestion" in res- assert "Priya Rao" in res["onboarding_suggestion"]- assert "create_onboarding_plan" in res["onboarding_suggestion"]---async def test_non_placed_stage_has_no_suggestion(db: Path) -> None:- cid = _candidate(db)- for stage in ("screened", "interviewed", "offer", "rejected"):- res = json.loads(await talent_tools.handle_set_candidate_stage(- {"candidate_id": cid, "stage": stage}- ))- assert "onboarding_suggestion" not in resdiff --git a/packages/core/tests/unit/test_talent_reminders.py b/packages/core/tests/unit/test_talent_reminders.pydeleted file mode 100644index 1295ca42..00000000--- a/packages/core/tests/unit/test_talent_reminders.py+++ /dev/null@@ -1,160 +0,0 @@-"""Tests for the shared talent reminder helpers."""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.memory import episodic-from openexecutive.people import store as people_store-from openexecutive.people.models import Person-from openexecutive.talent import reminders as reminders_mod-from openexecutive.talent import store as talent_store-from openexecutive.talent.reminders import (- ReminderContext,- company_name,- principal_channel,- resolve_reminder_context,- schedule_reminder,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "shared.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- monkeypatch.setattr(people_store, "DB_PATH", path)- monkeypatch.setattr(episodic, "DB_PATH", path)- episodic.initialize_db(path)- people_store.initialize_db(path)- talent_store.initialize_db(path)- return path---def _seed_candidate() -> int:- eid = talent_store.upsert_engagement(role_title="VP Drilling", department="Drilling")- return talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")---# --------------------------------------------------------------------------- #-# company_name-# --------------------------------------------------------------------------- #--def test_company_name_uses_profile(monkeypatch: pytest.MonkeyPatch) -> None:- from openexecutive.onboarding import profile_builder-- class _Profile:- name = "Acme Energy"-- monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: _Profile())- assert company_name() == "Acme Energy"---def test_company_name_falls_back_when_unnamed(monkeypatch: pytest.MonkeyPatch) -> None:- from openexecutive.onboarding import profile_builder-- class _Profile:- name = ""-- monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: _Profile())- assert company_name() == "the company"---# --------------------------------------------------------------------------- #-# principal_channel-# --------------------------------------------------------------------------- #--def test_principal_channel_resolution() -> None:- assert principal_channel(- Person(full_name="A", email="[email protected]", preferred_channel="email")- ) == ("email", "[email protected]")- # slack → slack_dm- assert principal_channel(- Person(full_name="A", slack_user_id="U123", preferred_channel="slack")- ) == ("slack_dm", "U123")- # "any" → priority order (email first)- assert principal_channel(- Person(full_name="A", email="[email protected]", slack_user_id="U1", preferred_channel="any")- ) == ("email", "[email protected]")- # preferred channel without its ref → fall back- assert principal_channel(- Person(full_name="A", slack_user_id="U1", preferred_channel="telegram")- ) == ("slack_dm", "U1")- # no usable channel- assert principal_channel(Person(full_name="A", preferred_channel="any")) is None---# --------------------------------------------------------------------------- #-# resolve_reminder_context-# --------------------------------------------------------------------------- #--def test_resolve_context_success(db: Path, monkeypatch: pytest.MonkeyPatch) -> None:- cand_id = _seed_candidate()- people_store.upsert_person(- full_name="Alex", is_principal=True, email="[email protected]", preferred_channel="email"- )- # In-house model: the reminder context carries the COMPANY name (from the- # profile), not an external client. Control the profile so the assertion is- # deterministic.- from openexecutive.onboarding import profile_builder-- class _Profile:- name = "Meridian Petroleum"-- monkeypatch.setattr(profile_builder, "load_or_create_profile", lambda: _Profile())-- ctx = resolve_reminder_context(cand_id)- assert isinstance(ctx, ReminderContext)- assert ctx.candidate.id == cand_id- assert ctx.engagement.role_title == "VP Drilling"- assert ctx.company_name == "Meridian Petroleum"- assert ctx.channel == "email"- assert ctx.channel_ref == "[email protected]"---def test_resolve_context_unknown_candidate(db: Path) -> None:- assert resolve_reminder_context(9999) == "Candidate 9999 not found."---def test_resolve_context_no_principal(db: Path) -> None:- cand_id = _seed_candidate()- assert resolve_reminder_context(cand_id) == "No principal configured to receive reminders."---def test_resolve_context_principal_without_channel(db: Path) -> None:- cand_id = _seed_candidate()- people_store.upsert_person(full_name="Alex", is_principal=True, preferred_channel="any")- msg = resolve_reminder_context(cand_id)- assert isinstance(msg, str)- assert "no reachable channel" in msg---# --------------------------------------------------------------------------- #-# schedule_reminder-# --------------------------------------------------------------------------- #--def test_schedule_reminder_targets_principal(db: Path) -> None:- from datetime import UTC, datetime-- cand_id = _seed_candidate()- pid = people_store.upsert_person(- full_name="Alex", is_principal=True, email="[email protected]", preferred_channel="email"- )- ctx = resolve_reminder_context(cand_id)- assert isinstance(ctx, ReminderContext)- aid = schedule_reminder(ctx=ctx, run_at=datetime.now(UTC), intent_text="ping")- assert aid > 0- actions = episodic.list_scheduled_actions()- assert len(actions) == 1- assert actions[0].assigned_to_person_id == pid- assert actions[0].channel == "email"- assert actions[0].channel_ref == "[email protected]"- assert actions[0].intent_text == "ping"---def test_channel_map_only_emits_valid_scheduled_channels() -> None:- # Every mapped scheduled channel must be accepted by insert_scheduled_action.- from openexecutive.memory.episodic import _VALID_SCHEDULED_CHANNELS-- for sched in reminders_mod._PEOPLE_TO_SCHEDULED_CHANNEL.values():- assert sched in _VALID_SCHEDULED_CHANNELSdiff --git a/packages/core/tests/unit/test_talent_route.py b/packages/core/tests/unit/test_talent_route.pydeleted file mode 100644index ca11b7a4..00000000--- a/packages/core/tests/unit/test_talent_route.py+++ /dev/null@@ -1,181 +0,0 @@-"""HTTP-level tests for /engagements, /candidates routes (in-house hiring)."""-from __future__ import annotations--from pathlib import Path--import pytest-from fastapi import FastAPI-from fastapi.testclient import TestClient--from openexecutive.api.routes import talent as talent_route-from openexecutive.talent import store as talent_store---class _NoopStore:- """No-op KnowledgeStore stand-in so candidate mutations can index without- constructing a real ChromaDB (these tests don't assert on the index)."""-- def add_documents(self, *a, **k) -> None: ...- def delete_documents(self, *a, **k) -> None: ...- def query(self, *a, **k): # noqa: ANN001, ANN201- return []---def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()-- app = FastAPI()- app.include_router(talent_route.router)- app.state.store = _NoopStore()- return TestClient(app)---def _make_engagement(- client: TestClient,- *,- role_title: str = "VP Drilling",- department: str = "Drilling",-) -> int:- resp = client.post(- "/engagements",- json={- "role_title": role_title,- "department": department,- "must_haves": "10+ yrs upstream, cycle-tested",- },- )- assert resp.status_code == 201- return resp.json()["id"]---# --------------------------------------------------------------------------- #-# Engagements-# --------------------------------------------------------------------------- #--def test_engagements_empty(client: TestClient) -> None:- assert client.get("/engagements").json() == []---def test_engagement_create_stores_department(client: TestClient) -> None:- # In-house hiring: only role_title is required; department is a free-text- # in-house grouping (no external client to resolve).- resp = client.post(- "/engagements", json={"role_title": "CFO", "department": "Finance"}- )- assert resp.status_code == 201- body = resp.json()- assert body["role_title"] == "CFO"- assert body["department"] == "Finance"- assert body["status"] == "open"- assert "client_id" not in body---def test_engagement_crud_and_listing(client: TestClient) -> None:- eid = _make_engagement(client)- client.post("/engagements", json={"role_title": "CFO", "department": "Finance"})-- assert len(client.get("/engagements").json()) == 2-- patched = client.patch(f"/engagements/{eid}", json={"status": "filled"})- assert patched.status_code == 200- assert patched.json()["status"] == "filled"- assert patched.json()["role_title"] == "VP Drilling" # unchanged- assert patched.json()["department"] == "Drilling" # unchanged---def test_engagement_get_unknown_404(client: TestClient) -> None:- assert client.get("/engagements/9999").status_code == 404---def test_engagement_archive(client: TestClient) -> None:- eid = _make_engagement(client)- assert client.post(f"/engagements/{eid}/archive").status_code == 204- assert client.get("/engagements").json() == []---# --------------------------------------------------------------------------- #-# Candidates-# --------------------------------------------------------------------------- #--def test_candidate_requires_existing_engagement(client: TestClient) -> None:- resp = client.post(- "/candidates", json={"engagement_id": 9999, "full_name": "Ghost"}- )- assert resp.status_code == 404---def test_candidate_crud_stage_and_filters(client: TestClient) -> None:- eid = _make_engagement(client)- create = client.post(- "/candidates",- json={- "engagement_id": eid,- "full_name": "Dana Cole",- "current_title": "Drilling Director",- },- )- assert create.status_code == 201- cand_id = create.json()["id"]- assert create.json()["stage"] == "lead"- assert create.json()["fit_score"] is None-- # Advance stage via the dedicated endpoint.- staged = client.post(f"/candidates/{cand_id}/stage", json={"stage": "interviewed"})- assert staged.status_code == 200- assert staged.json()["stage"] == "interviewed"-- # Filter by engagement + stage.- by_stage = client.get(f"/candidates?engagement_id={eid}&stage=interviewed").json()- assert len(by_stage) == 1- assert by_stage[0]["id"] == cand_id-- # Patch leaves stage untouched.- patched = client.patch(f"/candidates/{cand_id}", json={"location": "Midland, TX"})- assert patched.json()["location"] == "Midland, TX"- assert patched.json()["stage"] == "interviewed"-- assert client.post(f"/candidates/{cand_id}/archive").status_code == 204- assert client.get(f"/candidates?engagement_id={eid}").json() == []---def test_candidate_patch_can_clear_nullable_email(client: TestClient) -> None:- eid = _make_engagement(client)- create = client.post(- "/candidates",- json={"engagement_id": eid, "full_name": "Dana", "email": "[email protected]"},- )- cand_id = create.json()["id"]- assert create.json()["email"] == "[email protected]"-- # Explicit null clears the field; an omitted field would keep it.- cleared = client.patch(f"/candidates/{cand_id}", json={"email": None})- assert cleared.status_code == 200- assert cleared.json()["email"] is None-- # Omitting email on a later patch must preserve the (now-null) value and- # not resurrect the old one.- other = client.patch(f"/candidates/{cand_id}", json={"location": "Midland"})- assert other.json()["email"] is None---def test_candidate_patch_ignores_stage_field(client: TestClient) -> None:- eid = _make_engagement(client)- create = client.post("/candidates", json={"engagement_id": eid, "full_name": "Dana"})- cand_id = create.json()["id"]- # `stage` is not part of CandidatePatch; sending it must not change stage- # (the dedicated /stage endpoint is the only way to move the pipeline).- resp = client.patch(f"/candidates/{cand_id}", json={"stage": "placed", "notes": "x"})- assert resp.status_code == 200- assert resp.json()["stage"] == "lead"- assert resp.json()["notes"] == "x"---def test_candidate_bad_stage_value_422(client: TestClient) -> None:- eid = _make_engagement(client)- create = client.post("/candidates", json={"engagement_id": eid, "full_name": "Dana"})- cand_id = create.json()["id"]- resp = client.post(f"/candidates/{cand_id}/stage", json={"stage": "not_a_stage"})- assert resp.status_code == 422diff --git a/packages/core/tests/unit/test_talent_store.py b/packages/core/tests/unit/test_talent_store.pydeleted file mode 100644index c9514371..00000000--- a/packages/core/tests/unit/test_talent_store.py+++ /dev/null@@ -1,216 +0,0 @@-"""Store-level tests for the talent / executive-search core."""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage, EngagementStatus---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---def _seed_engagement(- must_haves: str = "10+ yrs upstream", department: str = "Drilling"-) -> int:- return talent_store.upsert_engagement(- role_title="VP Drilling", department=department, must_haves=must_haves- )---def test_initialize_db_idempotent(db: Path) -> None:- talent_store.initialize_db()- talent_store.initialize_db()- assert talent_store.list_engagements() == []---def test_initialize_db_resets_legacy_clients_schema(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- # A legacy DB carrying a `clients` table (the old external-client model) is- # detected and the talent tables are dropped + rebuilt in the in-house shape.- import sqlite3-- path = tmp_path / "legacy.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- conn = sqlite3.connect(str(path))- conn.executescript(- "CREATE TABLE clients (id INTEGER PRIMARY KEY, name TEXT);"- "CREATE TABLE engagements (id INTEGER PRIMARY KEY, client_id INTEGER, role_title TEXT);"- "INSERT INTO clients (name) VALUES ('Legacy Co');"- )- conn.commit()- conn.close()-- talent_store.initialize_db()-- with sqlite3.connect(str(path)) as check:- tables = {- r[0]- for r in check.execute(- "SELECT name FROM sqlite_master WHERE type='table'"- ).fetchall()- }- # Legacy clients table is gone; engagements has the new `department` col.- assert "clients" not in tables- cols = {r[1] for r in check.execute("PRAGMA table_info(engagements)").fetchall()}- assert "department" in cols- assert "client_id" not in cols-- # And it's empty (rebuilt fresh, no carry-over rows).- assert talent_store.list_engagements() == []---def test_engagement_crud_and_filter(db: Path) -> None:- eid = _seed_engagement()- eng = talent_store.get_engagement(eid)- assert eng is not None- assert eng.role_title == "VP Drilling"- assert eng.department == "Drilling"- assert eng.status == EngagementStatus.OPEN-- # A second engagement to verify listing returns both.- talent_store.upsert_engagement(role_title="CFO", department="Finance")-- engagements = talent_store.list_engagements()- assert len(engagements) == 2- assert {e.role_title for e in engagements} == {"VP Drilling", "CFO"}---def test_engagement_update_preserves_department(db: Path) -> None:- eid = _seed_engagement()- talent_store.upsert_engagement(- role_title="VP Drilling & Completions",- department="Drilling",- engagement_id=eid,- )- eng = talent_store.get_engagement(eid)- assert eng is not None- assert eng.role_title == "VP Drilling & Completions"- assert eng.department == "Drilling"---def test_engagement_status_transition(db: Path) -> None:- eid = _seed_engagement()- assert talent_store.set_engagement_status(eid, EngagementStatus.FILLED) is True- assert talent_store.get_engagement(eid).status == EngagementStatus.FILLED # type: ignore[union-attr]---def test_engagement_archive_excluded_by_default(db: Path) -> None:- eid = _seed_engagement()- assert talent_store.archive_engagement(eid) is True- assert talent_store.list_engagements() == []- assert len(talent_store.list_engagements(include_archived=True)) == 1- assert talent_store.archive_engagement(9999) is False---def test_candidate_crud_and_filters(db: Path) -> None:- eid = _seed_engagement()- cand_id = talent_store.upsert_candidate(- engagement_id=eid, full_name="Dana Cole", current_title="Drilling Director"- )- cand = talent_store.get_candidate(cand_id)- assert cand is not None- assert cand.full_name == "Dana Cole"- assert cand.stage == CandidateStage.LEAD- assert cand.fit_score is None-- talent_store.upsert_candidate(- engagement_id=eid, full_name="Sam Reyes", stage=CandidateStage.INTERVIEWED- )- assert len(talent_store.list_candidates(engagement_id=eid)) == 2- interviewed = talent_store.list_candidates(- engagement_id=eid, stage=CandidateStage.INTERVIEWED- )- assert len(interviewed) == 1- assert interviewed[0].full_name == "Sam Reyes"---def test_set_candidate_stage(db: Path) -> None:- eid = _seed_engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- assert talent_store.set_candidate_stage(cid, CandidateStage.OFFER) is True- assert talent_store.get_candidate(cid).stage == CandidateStage.OFFER # type: ignore[union-attr]---def test_record_screening_persists_and_advances_lead(db: Path) -> None:- eid = _seed_engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- ok = talent_store.record_screening(cid, fit_score=82, summary="Strong cycle-tested fit.")- assert ok is True- cand = talent_store.get_candidate(cid)- assert cand is not None- assert cand.fit_score == 82- assert cand.screening_summary == "Strong cycle-tested fit."- assert cand.stage == CandidateStage.SCREENED # advanced from lead---def test_record_screening_does_not_drag_back_advanced_candidate(db: Path) -> None:- eid = _seed_engagement()- cid = talent_store.upsert_candidate(- engagement_id=eid, full_name="Sam Reyes", stage=CandidateStage.INTERVIEWED- )- talent_store.record_screening(cid, fit_score=70, summary="Re-screen.")- # Stays interviewed — a re-screen must not reset an advanced candidate.- assert talent_store.get_candidate(cid).stage == CandidateStage.INTERVIEWED # type: ignore[union-attr]---def test_record_screening_rejects_out_of_range(db: Path) -> None:- eid = _seed_engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- with pytest.raises(ValueError):- talent_store.record_screening(cid, fit_score=150, summary="bad")---def test_record_screening_unknown_candidate_returns_false(db: Path) -> None:- assert (- talent_store.record_screening(9999, fit_score=50, summary="x") is False- )---def test_record_screening_skips_archived_candidate(db: Path) -> None:- eid = _seed_engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- talent_store.archive_candidate(cid)- # A screen landing after the candidate was archived must be a no-op.- assert talent_store.record_screening(cid, fit_score=88, summary="late") is False- cand = talent_store.list_candidates(- engagement_id=eid, include_archived=True- )[0]- assert cand.fit_score is None- assert cand.screening_summary == ""---def test_archive_candidate(db: Path) -> None:- eid = _seed_engagement()- cid = talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- assert talent_store.archive_candidate(cid) is True- assert talent_store.list_candidates(engagement_id=eid) == []- assert len(talent_store.list_candidates(engagement_id=eid, include_archived=True)) == 1---def test_archive_engagement_is_soft_and_keeps_candidates(db: Path) -> None:- # Archiving an engagement does not remove its candidate rows; soft-delete is- # independent per entity (matches people semantics).- eid = _seed_engagement()- talent_store.upsert_candidate(engagement_id=eid, full_name="Dana Cole")- talent_store.archive_engagement(eid)- # Engagement still resolvable directly; candidate rows untouched.- assert talent_store.get_engagement(eid) is not None- assert len(talent_store.list_candidates(engagement_id=eid)) == 1---def test_reads_on_missing_db_return_empty(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- # Before initialize_db / before any file exists, reads degrade to empty- # rather than raising — mirrors people.store behaviour.- monkeypatch.setattr(talent_store, "DB_PATH", tmp_path / "nope.db")- assert talent_store.list_engagements() == []- assert talent_store.list_candidates() == []- assert talent_store.get_engagement(1) is Nonediff --git a/packages/core/tests/unit/test_talent_tools.py b/packages/core/tests/unit/test_talent_tools.pydeleted file mode 100644index bd9c1c1f..00000000--- a/packages/core/tests/unit/test_talent_tools.py+++ /dev/null@@ -1,347 +0,0 @@-"""Unit tests for openexecutive.orchestrator.talent_tools.--These chat tools let the Executive read the live talent pipeline and trigger the-talent workflows. The read/light-write handlers are covered here end to end; the-``start_talent_workflow`` happy path needs the Anthropic API + vector store, so-only its validation/error branches (which never reach the model) are exercised.-"""-from __future__ import annotations--import asyncio-import json-from collections.abc import Awaitable, Callable-from pathlib import Path-from typing import Any--import pytest--from openexecutive.orchestrator.talent_tools import (- TALENT_TOOL_HANDLERS,- TALENT_TOOLS,- handle_create_candidate,- handle_create_engagement,- handle_get_candidate,- handle_list_candidates,- handle_list_engagements,- handle_match_candidates,- handle_set_candidate_stage,- handle_start_talent_workflow,-)-from openexecutive.talent import graph as talent_graph-from openexecutive.talent import store as talent_store-from openexecutive.talent.models import CandidateStage--[email protected](autouse=True)-def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "talent.db"- monkeypatch.setattr(talent_store, "DB_PATH", path)- talent_store.initialize_db()- return path---def _call(fn: Callable[[dict[str, Any]], Awaitable[str]], payload: dict[str, Any]) -> dict[str, Any]:- return json.loads(asyncio.run(fn(payload)))---def _seed() -> int:- """Seed one engagement (a role we're hiring for) and return its id."""- return talent_store.upsert_engagement(role_title="VP Drilling", department="Drilling")---# --------------------------------------------------------------------------- #-# list_engagements-# --------------------------------------------------------------------------- #---def test_list_engagements_rolls_up_pipeline() -> None:- eid = _seed()- talent_store.upsert_candidate(engagement_id=eid, full_name="Lead A", stage=CandidateStage.LEAD)- talent_store.upsert_candidate(engagement_id=eid, full_name="Offeree", stage=CandidateStage.OFFER)-- out = _call(handle_list_engagements, {})- assert out["count"] == 1- eng = out["engagements"][0]- assert eng["engagement_id"] == eid- assert eng["candidate_count"] == 2- assert eng["needs_screening"] == 1- assert eng["offers_out"] == 1---def test_list_engagements_empty() -> None:- out = _call(handle_list_engagements, {})- assert out == {"engagements": [], "count": 0}---# --------------------------------------------------------------------------- #-# list_candidates-# --------------------------------------------------------------------------- #---def test_list_candidates_happy_and_stage_filter() -> None:- eid = _seed()- talent_store.upsert_candidate(engagement_id=eid, full_name="Lead A", stage=CandidateStage.LEAD)- talent_store.upsert_candidate(engagement_id=eid, full_name="Offeree", stage=CandidateStage.OFFER)-- everyone = _call(handle_list_candidates, {"engagement_id": eid})- assert everyone["count"] == 2-- only_offer = _call(handle_list_candidates, {"engagement_id": eid, "stage": "offer"})- assert only_offer["count"] == 1- assert only_offer["candidates"][0]["full_name"] == "Offeree"---def test_list_candidates_bad_engagement_id() -> None:- out = _call(handle_list_candidates, {})- assert "error" in out---def test_list_candidates_invalid_stage() -> None:- eid = _seed()- out = _call(handle_list_candidates, {"engagement_id": eid, "stage": "bogus"})- assert "error" in out- assert "invalid stage" in out["error"]---# --------------------------------------------------------------------------- #-# get_candidate-# --------------------------------------------------------------------------- #---def test_get_candidate_found_and_missing() -> None:- eid = _seed()- cand_id = talent_store.upsert_candidate(engagement_id=eid, full_name="Jane Roe")-- found = _call(handle_get_candidate, {"candidate_id": cand_id})- assert found["candidate"]["full_name"] == "Jane Roe"-- missing = _call(handle_get_candidate, {"candidate_id": 9999})- assert missing["status"] == "not_found"---def test_get_candidate_bad_input() -> None:- out = _call(handle_get_candidate, {"candidate_id": "not-an-int"})- assert "error" in out---# --------------------------------------------------------------------------- #-# set_candidate_stage-# --------------------------------------------------------------------------- #---def test_set_candidate_stage_happy() -> None:- eid = _seed()- cand_id = talent_store.upsert_candidate(engagement_id=eid, full_name="Jane Roe")-- out = _call(handle_set_candidate_stage, {"candidate_id": cand_id, "stage": "interviewed"})- assert out["status"] == "ok"- assert out["stage"] == "interviewed"- assert talent_store.get_candidate(cand_id).stage == CandidateStage.INTERVIEWED # type: ignore[union-attr]---def test_set_candidate_stage_not_found() -> None:- out = _call(handle_set_candidate_stage, {"candidate_id": 9999, "stage": "offer"})- assert out["status"] == "not_found"---def test_set_candidate_stage_invalid_stage() -> None:- eid = _seed()- cand_id = talent_store.upsert_candidate(engagement_id=eid, full_name="Jane Roe")- out = _call(handle_set_candidate_stage, {"candidate_id": cand_id, "stage": "promoted"})- assert "error" in out---# --------------------------------------------------------------------------- #-# match_candidates (error branches that don't hit the vector store)-# --------------------------------------------------------------------------- #---def test_match_candidates_bad_input() -> None:- out = _call(handle_match_candidates, {})- assert "error" in out---def test_match_candidates_unknown_engagement() -> None:- out = _call(handle_match_candidates, {"engagement_id": 4242})- assert out["status"] == "not_found"---# --------------------------------------------------------------------------- #-# start_talent_workflow (validation branches only)-# --------------------------------------------------------------------------- #---def test_start_talent_workflow_unknown_workflow() -> None:- out = _call(handle_start_talent_workflow, {"workflow": "not_a_workflow", "inputs": {}})- assert "error" in out---def test_start_talent_workflow_inputs_must_be_object() -> None:- out = _call(handle_start_talent_workflow, {"workflow": "candidate_screen", "inputs": "nope"})- assert "error" in out- assert "inputs must be an object" in out["error"]---def test_start_talent_workflow_invalid_inputs_for_workflow() -> None:- # candidate_screen requires engagement_id + candidate_id; an empty object- # must fail validation before any model/vector-store call.- out = _call(handle_start_talent_workflow, {"workflow": "candidate_screen", "inputs": {}})- assert "error" in out- assert "invalid inputs" in out["error"]---# --------------------------------------------------------------------------- #-# Registry / contract-# --------------------------------------------------------------------------- #---def test_create_tools_registered() -> None:- names = {t["name"] for t in TALENT_TOOLS}- for name in (- "create_engagement",- "create_candidate",- ):- assert name in names- assert name in TALENT_TOOL_HANDLERS- # The external-client tools are gone (in-house hiring model).- assert "list_clients" not in names- assert "create_client" not in names- assert "list_clients" not in TALENT_TOOL_HANDLERS- assert "create_client" not in TALENT_TOOL_HANDLERS---# --------------------------------------------------------------------------- #-# create_engagement-# --------------------------------------------------------------------------- #---def test_create_engagement_happy() -> None:- # role_title is the only required field now; department is optional in-house- # grouping and there is no external client to resolve.- out = _call(- handle_create_engagement,- {- "role_title": "VP Completions",- "department": "Completions",- "location": "Midland, TX",- },- )- assert out["status"] == "ok"- eng = out["engagement"]- assert eng["role_title"] == "VP Completions"- assert eng["department"] == "Completions"- assert eng["location"] == "Midland, TX"- assert eng["status"] == "open"- assert "client_id" not in eng- # Persisted and reloadable.- assert talent_store.get_engagement(eng["id"]) is not None---def test_create_engagement_defaults_department_to_empty() -> None:- out = _call(handle_create_engagement, {"role_title": "VP Ops"})- assert out["status"] == "ok"- assert out["engagement"]["department"] == ""---def test_create_engagement_requires_role_title() -> None:- out = _call(handle_create_engagement, {"role_title": ""})- assert "error" in out- assert "role_title is required" in out["error"]---def test_create_engagement_invalid_status() -> None:- out = _call(- handle_create_engagement,- {"role_title": "VP Ops", "status": "bogus"},- )- assert "error" in out- assert "invalid status" in out["error"]---# --------------------------------------------------------------------------- #-# create_candidate-# --------------------------------------------------------------------------- #---def _stub_store(monkeypatch: pytest.MonkeyPatch) -> None:- """Avoid constructing a real ChromaDB/embedding stack in create_candidate."""- from openexecutive.knowledge import store as knowledge_store-- monkeypatch.setattr(knowledge_store, "ChromaDBStore", lambda **kwargs: object())---def test_create_candidate_happy_and_indexes(monkeypatch: pytest.MonkeyPatch) -> None:- eid = _seed()- _stub_store(monkeypatch)- indexed: list[int] = []- # Stub indexing so the test never builds a real vector store; assert the- # handler still asks the graph to index the new candidate.- monkeypatch.setattr(- talent_graph, "index_candidate", lambda cand, store: indexed.append(cand.id)- )-- out = _call(- handle_create_candidate,- {- "engagement_id": eid,- "full_name": "Dana Wells",- "current_title": "Drilling Superintendent",- "email": " ",- "stage": "screened",- },- )- assert out["status"] == "ok"- cand = out["candidate"]- assert cand["full_name"] == "Dana Wells"- assert cand["engagement_id"] == eid- assert cand["stage"] == "screened"- # Blank email normalized to null, not stored as " ".- assert cand["email"] is None- # Persisted and handed to the indexer exactly once.- assert talent_store.get_candidate(cand["id"]) is not None- assert indexed == [cand["id"]]---def test_create_candidate_unknown_engagement(monkeypatch: pytest.MonkeyPatch) -> None:- called: list[int] = []- monkeypatch.setattr(- talent_graph, "index_candidate", lambda cand, store: called.append(cand.id)- )- out = _call(handle_create_candidate, {"engagement_id": 4242, "full_name": "Nobody"})- assert out["status"] == "not_found"- assert out["engagement_id"] == 4242- # No write, so nothing indexed.- assert called == []---def test_create_candidate_requires_full_name() -> None:- eid = _seed()- out = _call(handle_create_candidate, {"engagement_id": eid, "full_name": ""})- assert "error" in out- assert "full_name is required" in out["error"]---def test_create_rejects_oversized_text() -> None:- # Chat is just another caller; it must not be able to persist unbounded text- # the /talent HTTP route would reject (here a >200-char role_title).- out = _call(handle_create_engagement, {"role_title": "X" * 201})- assert "error" in out- assert "too long" in out["error"]- # And nothing was written.- assert _call(handle_list_engagements, {})["count"] == 0---def test_create_candidate_indexing_failure_does_not_break_write(- monkeypatch: pytest.MonkeyPatch,-) -> None:- eid = _seed()- _stub_store(monkeypatch)-- def _boom(cand: Any, store: Any) -> None:- raise RuntimeError("vector store down")-- monkeypatch.setattr(talent_graph, "index_candidate", _boom)- out = _call(handle_create_candidate, {"engagement_id": eid, "full_name": "Resilient Rita"})- # The candidate is still created even though indexing blew up.- assert out["status"] == "ok"- assert talent_store.get_candidate(out["candidate"]["id"]) is not Nonediff --git a/packages/core/tests/unit/test_today_onboarding_digest.py b/packages/core/tests/unit/test_today_onboarding_digest.pydeleted file mode 100644index c6eaa5c9..00000000--- a/packages/core/tests/unit/test_today_onboarding_digest.py+++ /dev/null@@ -1,81 +0,0 @@-"""Tests for the staff-onboarding briefing digest (briefing/onboarding_digest.py).--Covers the active-plan rollup, overdue-task counting, exclusion of-completed/archived plans, and the chat-digest text.-"""-from __future__ import annotations--from pathlib import Path--import pytest--from openexecutive.briefing.onboarding_digest import (- build_onboarding_brief_items,- format_onboarding_for_prompt,-)-from openexecutive.staff_onboarding import store-from openexecutive.staff_onboarding.models import (- OnboardingPhase,- OnboardingStatus,- TaskStatus,-)---def db(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:- path = tmp_path / "onboarding.db"- monkeypatch.setattr(store, "DB_PATH", path)- store.initialize_db()- return path---def test_empty_digest(db: Path) -> None:- assert build_onboarding_brief_items() == []- assert format_onboarding_for_prompt() == ""---def test_rollup_counts_open_and_overdue(db: Path) -> None:- plan_id = store.create_plan(full_name="Priya Rao", start_date="2026-07-01",- role="CFO", status=OnboardingStatus.ACTIVE)- store.add_task(plan_id=plan_id, title="Past due", phase=OnboardingPhase.WEEK_1,- due_date="2020-01-01") # overdue + open- store.add_task(plan_id=plan_id, title="Future", phase=OnboardingPhase.DAY_30,- due_date="2999-01-01") # open, not overdue- done = store.add_task(plan_id=plan_id, title="Done already")- store.set_task_status(done, TaskStatus.DONE)-- items = build_onboarding_brief_items()- assert len(items) == 1- item = items[0]- assert item.full_name == "Priya Rao"- assert item.open_tasks == 2- assert item.overdue_tasks == 1-- text = format_onboarding_for_prompt()- assert f"[plan {plan_id}]" in text- assert "1 overdue" in text---def test_day_label_counts_start_as_day_one(db: Path) -> None:- from datetime import UTC, datetime, timedelta-- yesterday = (datetime.now(UTC).date() - timedelta(days=1)).isoformat()- plan_id = store.create_plan(full_name="Started Yesterday", start_date=yesterday,- status=OnboardingStatus.ACTIVE)- text = format_onboarding_for_prompt()- # Start date is day 1, so a hire who started yesterday is on day 2.- assert "day 2" in text- assert f"[plan {plan_id}]" in text---def test_completed_and_archived_excluded(db: Path) -> None:- active = store.create_plan(full_name="Active", start_date="2026-07-01",- status=OnboardingStatus.ACTIVE)- store.create_plan(full_name="Done", start_date="2026-07-01",- status=OnboardingStatus.COMPLETED)- archived = store.create_plan(full_name="Gone", start_date="2026-07-01",- status=OnboardingStatus.ACTIVE)- store.archive_plan(archived)-- ids = {i.plan_id for i in build_onboarding_brief_items()}- assert ids == {active}diff --git a/packages/core/tests/unit/test_today_route.py b/packages/core/tests/unit/test_today_route.pyindex 695ae3ae..ccd4d343 100644--- a/packages/core/tests/unit/test_today_route.py+++ b/packages/core/tests/unit/test_today_route.py@@ -1373,42 +1373,15 @@ def test_teammate_slice_is_only_their_routed_action(assert captured["proposals"] == ["Dan action"]-def test_today_includes_active_searches(- tmp_path: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- """An open engagement with candidates surfaces in the /today `talent` list."""- from openexecutive.talent import store as talent_store- from openexecutive.talent.models import CandidateStage-- db = tmp_path / "today.db"- _setup_isolated_db(db, monkeypatch)- monkeypatch.setattr(talent_store, "DB_PATH", db)- talent_store.initialize_db(db)-- eid = talent_store.upsert_engagement(- role_title="VP Drilling", department="Drilling", db_path=db- )- talent_store.upsert_candidate(- engagement_id=eid, full_name="Lead A", stage=CandidateStage.LEAD, db_path=db- )- talent_store.upsert_candidate(- engagement_id=eid, full_name="Offeree", stage=CandidateStage.OFFER, db_path=db- )-- resp = _make_client().get("/today")- assert resp.status_code == 200- talent = resp.json()["talent"]- assert len(talent) == 1- assert talent[0]["role_title"] == "VP Drilling"- assert talent[0]["needs_screening"] == 1- assert talent[0]["offers_out"] == 1---def test_today_talent_empty_when_no_searches(client: TestClient) -> None:- """No talent data ⇒ an empty `talent` list, never a crash."""+def test_today_has_no_talent_or_onboarding_fields(client: TestClient) -> None:+ """The talent and staff-onboarding verticals were removed, so /today must+ no longer carry their rollups. Pins the response-shape change so a revert+ or a stray re-add is caught here rather than by the UI."""resp = client.get("/today")assert resp.status_code == 200- assert resp.json()["talent"] == []+ body = resp.json()+ assert "talent" not in body+ assert "onboarding" not in body# --------------------------------------------------------------------------- #diff --git a/packages/ui/src/app/architecture/page.tsx b/packages/ui/src/app/architecture/page.tsxindex d0431e56..6efb7718 100644--- a/packages/ui/src/app/architecture/page.tsx+++ b/packages/ui/src/app/architecture/page.tsx@@ -32,8 +32,6 @@ const SECTIONS = [{ id: 'api', label: 'API Reference', sub: 'The FastAPI HTTP surface — endpoints grouped by router.' },{ id: 'mcp_server', label: 'MCP Server', sub: 'Open Executive exposed as an MCP server — company context as resources and the specialist council as tools, over Streamable-HTTP at /mcp for external agents.' },{ id: 'user_guide', label: 'User Guide Surface', sub: "The /guide page — plain-language, per-feature overviews served from static prebuilt JSON, sharing this page's loader and renderer but separate from this technical reference." },- { id: 'talent', label: 'Talent / Executive Search', sub: 'The in-house hiring vertical: engagements (searches), candidates, the ChromaDB matching graph, and the draft-and-approve recruiting workflows — surfaced in the /talent UI.' },- { id: 'staff_onboarding', label: 'Staff Onboarding', sub: 'Role-tailored onboarding for new hires: reusable templates, per-hire plans with phased task checklists, the role_onboarding brief workflow, a bounded ramp drip, and chat + /today integration.' },{ id: 'clients', label: 'Client Companies (Slots)', sub: 'Multi-client mode for fractional executives: named save files of the full company context, one active at a time, with save-back switching and per-client MCP tool configs.' },];diff --git a/packages/ui/src/app/clients/page.tsx b/packages/ui/src/app/clients/page.tsxindex 768827d8..716067cd 100644--- a/packages/ui/src/app/clients/page.tsx+++ b/packages/ui/src/app/clients/page.tsx@@ -241,7 +241,7 @@ export default function ClientsPage() {<p className="mt-1 text-sm text-fg-muted">Run several client companies from one Open Executive — one active at atime. Switching saves the current client's full state (chat,- schedule, onboarding plans, documents, MCP tools) to its slot and+ schedule, documents, MCP tools) to its slot andrestores the target.</p>diff --git a/packages/ui/src/app/guide/page.tsx b/packages/ui/src/app/guide/page.tsxindex 55bf99da..8ce25f96 100644--- a/packages/ui/src/app/guide/page.tsx+++ b/packages/ui/src/app/guide/page.tsx@@ -18,8 +18,6 @@ const SECTIONS = [{ id: 'watchlist', label: 'Watch List', sub: 'External monitors — stock tickers, RSS feeds, status pages, web queries — that raise alerts.' },{ id: 'departments', label: 'Departments', sub: 'Org units, each with goals, an authority level, and a specialist behind it.' },{ id: 'people', label: 'People', sub: 'Your roster — who the Executive coordinates with, their SLAs, channels, and approval scopes.' },- { id: 'talent', label: 'Talent', sub: 'Candidate searches and hiring — engagements, pipeline stages, scoring, and offers.' },- { id: 'staff_onboarding', label: 'Staff onboarding', sub: 'Templated ramp-up plans for new hires — tasks, phases, check-ins, and welcome briefs.' },{ id: 'company_profile', label: 'Company Profile & Onboarding', sub: "Your company's identity and strategy — set up once, edited any time." },{ id: 'knowledge', label: 'Knowledge base', sub: 'Upload company documents so the Executive can ground its answers in your context.' },{ id: 'skills', label: 'Skills', sub: 'Reusable how-to procedures the Executive can pull up — checklists, playbooks, templates.' },diff --git a/packages/ui/src/app/jobs/[name]/page.tsx b/packages/ui/src/app/jobs/[name]/page.tsxindex d266242b..696f3ad4 100644--- a/packages/ui/src/app/jobs/[name]/page.tsx+++ b/packages/ui/src/app/jobs/[name]/page.tsx@@ -5,14 +5,10 @@ import { useParams, useSearchParams } from "next/navigation";import Link from "next/link";import WorkflowRunner from "@/components/WorkflowRunner";import {- Candidate,- Engagement,WorkflowInputFieldSchema,WorkflowMeta,getWorkflow,getWorkflowSample,- listCandidates,- listEngagements,} from "@/lib/api";type FormState = Record<string, string>;@@ -84,11 +80,6 @@ export default function JobDetailPage() {// re-render and silently overwrites the user's in-progress edits.const initializedForWorkflowRef = useRef<string | null>(null);const prefillRaw = searchParams?.get("prefill") ?? null;- // Talent pickers: when a workflow exposes a `candidate_id` / `engagement_id`- // field, fetch the roster so the user picks from a dropdown instead of typing- // a raw id. Best-effort — on failure the field falls back to a text input.- const [candidates, setCandidates] = useState<Candidate[]>([]);- const [engagements, setEngagements] = useState<Engagement[]>([]);useEffect(() => {if (!name) return;@@ -136,27 +127,6 @@ export default function JobDetailPage() {// eslint-disable-next-line react-hooks/exhaustive-deps}, [name]);- // Populate the talent pickers once the workflow's fields are known. The- // cancelled guard prevents a stale/duplicate fetch (StrictMode double-invoke,- // re-render) from overwriting state or setting it after unmount.- useEffect(() => {- const props = workflow?.input_schema.properties ?? {};- let cancelled = false;- if ("candidate_id" in props) {- listCandidates()- .then((c) => !cancelled && setCandidates(c))- .catch(() => !cancelled && setCandidates([]));- }- if ("engagement_id" in props) {- listEngagements()- .then((e) => !cancelled && setEngagements(e))- .catch(() => !cancelled && setEngagements([]));- }- return () => {- cancelled = true;- };- }, [workflow]);-const handleLoadSample = useCallback(async () => {if (!name) return;try {@@ -292,20 +262,6 @@ export default function JobDetailPage() {const isRequired = required.has(fieldName);const multiline = isMultiline(fieldName, schema);const inputId = `field-${fieldName}`;- // Talent pickers replace the raw-id text input when a roster- // is available; otherwise fall through to the normal input.- const pickerItems =- fieldName === "candidate_id" && candidates.length- ? candidates.map((c) => ({- value: String(c.id),- label: `${c.full_name}${c.current_title ? ` — ${c.current_title}` : ""} (#${c.id})`,- }))- : fieldName === "engagement_id" && engagements.length- ? engagements.map((e) => ({- value: String(e.id),- label: `${e.role_title} (#${e.id})`,- }))- : null;const hasExample =Array.isArray(schema.examples) &&schema.examples.length > 0 &&@@ -339,22 +295,7 @@ export default function JobDetailPage() {{schema.description}</p>)}- {pickerItems ? (- <select- id={inputId}- value={form[fieldName] ?? ""}- onChange={(e) => handleChange(fieldName, e.target.value)}- required={isRequired}- className="w-full rounded-md bg-surface/60 border border-line focus:border-indigo-500 focus:outline-none text-sm text-fg px-3 py-2"- >- <option value="">Select…</option>- {pickerItems.map((opt) => (- <option key={opt.value} value={opt.value}>- {opt.label}- </option>- ))}- </select>- ) : multiline ? (+ {multiline ? (<textareaid={inputId}value={form[fieldName] ?? ""}diff --git a/packages/ui/src/app/staff-onboarding/[id]/page.tsx b/packages/ui/src/app/staff-onboarding/[id]/page.tsxdeleted file mode 100644index a22076f5..00000000--- a/packages/ui/src/app/staff-onboarding/[id]/page.tsx+++ /dev/null@@ -1,241 +0,0 @@-"use client";--import Link from "next/link";-import { useParams } from "next/navigation";-import { useCallback, useEffect, useState } from "react";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";--import {- OnboardingPlan,- OnboardingTask,- activateOnboardingPlan,- advanceOnboardingPlan,- getOnboardingPlan,- setOnboardingTaskStatus,-} from "@/lib/api";-import { PHASE_LABEL, PHASE_ORDER, STATUS_META } from "@/components/onboarding/meta";--export default function OnboardingPlanDetailPage() {- const params = useParams();- const planId = Number(params.id);-- const [plan, setPlan] = useState<OnboardingPlan | null>(null);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [busy, setBusy] = useState(false);-- const load = useCallback(() => {- setLoading(true);- getOnboardingPlan(planId)- .then(setPlan)- .catch((err) => setError(err instanceof Error ? err.message : "Failed to load"))- .finally(() => setLoading(false));- }, [planId]);-- useEffect(() => {- if (!Number.isNaN(planId)) load();- }, [planId, load]);-- async function runAction(fn: () => Promise<unknown>) {- setBusy(true);- setError(null);- try {- await fn();- load();- } catch (err) {- setError(err instanceof Error ? err.message : "Action failed");- } finally {- setBusy(false);- }- }-- async function toggleTask(task: OnboardingTask) {- if (task.id == null) return;- const next = task.status === "done" ? "pending" : "done";- await runAction(() => setOnboardingTaskStatus(task.id as number, next));- }-- if (loading) {- return <div className="p-6 text-sm text-fg-muted">Loading…</div>;- }- if (error && !plan) {- return (- <div className="p-6">- <Link href="/staff-onboarding" className="text-indigo-300 hover:text-indigo-200 text-sm">- ← Back- </Link>- <p className="mt-4 text-sm text-rose-300">{error}</p>- </div>- );- }- if (!plan) return null;-- const meta = STATUS_META[plan.status] ?? STATUS_META.draft;- const tasksByPhase = PHASE_ORDER.map((phase) => ({- phase,- tasks: plan.tasks.filter((t) => t.phase === phase),- })).filter((g) => g.tasks.length > 0);-- return (- <div className="flex flex-col h-full bg-surface">- <main className="flex-1 overflow-y-auto">- <div className="max-w-4xl mx-auto px-6 py-6">- <Link- href="/staff-onboarding"- className="text-indigo-300 hover:text-indigo-200 text-sm"- >- ← All plans- </Link>-- <div className="mt-3 flex items-start justify-between gap-4 flex-wrap">- <div>- <h1 className="text-xl font-semibold text-fg">- {plan.full_name}- {plan.role && <span className="text-fg-muted"> — {plan.role}</span>}- </h1>- <div className="mt-1 flex items-center gap-2 text-sm">- <span className={`px-2 py-0.5 text-[11px] rounded-full border ${meta.cls}`}>- {meta.label}- </span>- <span className="text-fg-subtle">- {PHASE_LABEL[plan.current_phase] ?? plan.current_phase}- </span>- <span className="text-fg-subtle">· starts {plan.start_date}</span>- <span className="text-fg-subtle">· {plan.completion_pct}% complete</span>- </div>- </div>- <div className="flex items-center gap-2">- {plan.status === "draft" && (- <button- onClick={() => runAction(() => activateOnboardingPlan(planId))}- disabled={busy}- className="px-3 py-1.5 text-sm rounded-lg bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white"- >- Activate- </button>- )}- <button- onClick={() => runAction(() => advanceOnboardingPlan(planId))}- disabled={busy}- className="px-3 py-1.5 text-sm rounded-lg bg-surface-input border border-line hover:border-indigo-500 disabled:opacity-50"- >- Advance phase- </button>- </div>- </div>-- {error && (- <div className="mt-4 p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">- {error}- </div>- )}-- {/* Tasks */}- <section className="mt-6">- <h2 className="text-sm font-semibold text-fg-muted uppercase tracking-wide mb-3">- Checklist- </h2>- {tasksByPhase.length === 0 && (- <p className="text-sm text-fg-subtle">No tasks on this plan.</p>- )}- <div className="space-y-4">- {tasksByPhase.map(({ phase, tasks }) => (- <div key={phase}>- <div className="text-[11px] font-semibold text-fg-subtle uppercase tracking-wide mb-1.5">- {PHASE_LABEL[phase]}- </div>- <div className="space-y-1.5">- {tasks.map((t) => (- <label- key={t.id}- className="flex items-center gap-3 rounded-lg border border-line bg-surface-elevated px-3 py-2 cursor-pointer"- >- <input- type="checkbox"- checked={t.status === "done"}- onChange={() => toggleTask(t)}- disabled={busy || t.status === "skipped"}- className="accent-emerald-500"- />- <span- className={`text-sm flex-1 ${- t.status === "done"- ? "line-through text-fg-subtle"- : "text-fg"- }`}- >- {t.title}- </span>- {t.due_date && (- <span className="text-[11px] text-fg-subtle tabular-nums">- due {t.due_date}- </span>- )}- {t.status === "skipped" && (- <span className="text-[11px] text-fg-subtle">skipped</span>- )}- </label>- ))}- </div>- </div>- ))}- </div>- </section>-- {/* Reading list */}- {plan.reading_list.length > 0 && (- <section className="mt-6">- <h2 className="text-sm font-semibold text-fg-muted uppercase tracking-wide mb-2">- Suggested reading- </h2>- <ul className="list-disc list-inside text-sm text-fg-muted space-y-0.5">- {plan.reading_list.map((r) => (- <li key={r}>{r}</li>- ))}- </ul>- </section>- )}-- {/* Ramp */}- {plan.ramp_segments.length > 0 && (- <section className="mt-6">- <h2 className="text-sm font-semibold text-fg-muted uppercase tracking-wide mb-2">- Ramp drip- </h2>- <p className="text-sm text-fg-muted">- {plan.ramp_segments.length} daily message- {plan.ramp_segments.length === 1 ? "" : "s"} ·{" "}- {plan.ramp_next_index} sent- </p>- </section>- )}-- {/* Welcome brief */}- <section className="mt-6">- <h2 className="text-sm font-semibold text-fg-muted uppercase tracking-wide mb-2">- Welcome brief- </h2>- {plan.brief_artifact ? (- <div- className="prose prose-invert prose-sm max-w-none rounded-lg border border-line bg-surface/40 p-6- prose-headings:text-fg prose-headings:font-semibold- prose-p:text-fg prose-p:leading-relaxed- prose-li:text-fg prose-strong:text-fg"- >- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {plan.brief_artifact}- </ReactMarkdown>- </div>- ) : (- <p className="text-sm text-fg-subtle">- No brief generated yet — ask the Executive to “start onboarding for{" "}- {plan.full_name}” in chat to generate the role-tailored welcome brief.- </p>- )}- </section>- </div>- </main>- </div>- );-}diff --git a/packages/ui/src/app/staff-onboarding/page.tsx b/packages/ui/src/app/staff-onboarding/page.tsxdeleted file mode 100644index 8f3ea26b..00000000--- a/packages/ui/src/app/staff-onboarding/page.tsx+++ /dev/null@@ -1,228 +0,0 @@-"use client";--import Link from "next/link";-import { useEffect, useMemo, useState } from "react";--import {- OnboardingPlan,- OnboardingTemplate,- createOnboardingPlan,- listOnboardingPlans,- listOnboardingTemplates,-} from "@/lib/api";-import { PHASE_LABEL, STATUS_META, STATUS_ORDER } from "@/components/onboarding/meta";--function ProgressBar({ pct }: { pct: number }) {- return (- <div className="h-1.5 w-full rounded-full bg-surface-input overflow-hidden">- <div- className="h-full rounded-full bg-emerald-500/70"- style={{ width: `${Math.max(0, Math.min(100, pct))}%` }}- />- </div>- );-}--export default function StaffOnboardingPage() {- const [plans, setPlans] = useState<OnboardingPlan[]>([]);- const [templates, setTemplates] = useState<OnboardingTemplate[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [showCreate, setShowCreate] = useState(false);- const [saving, setSaving] = useState(false);-- const [fullName, setFullName] = useState("");- const [startDate, setStartDate] = useState("");- const [role, setRole] = useState("");- const [templateName, setTemplateName] = useState("");-- function load() {- setLoading(true);- Promise.all([listOnboardingPlans(), listOnboardingTemplates()])- .then(([p, t]) => {- setPlans(p);- setTemplates(t);- })- .catch((err) => setError(err instanceof Error ? err.message : "Failed to load"))- .finally(() => setLoading(false));- }-- useEffect(() => {- load();- }, []);-- const sorted = useMemo(- () =>- [...plans].sort(- (a, b) =>- (STATUS_ORDER[a.status] ?? 9) - (STATUS_ORDER[b.status] ?? 9) ||- a.completion_pct - b.completion_pct,- ),- [plans],- );-- async function handleCreate(e: React.FormEvent) {- e.preventDefault();- if (!fullName.trim() || !startDate) return;- setSaving(true);- setError(null);- try {- await createOnboardingPlan({- full_name: fullName.trim(),- start_date: startDate,- role: role.trim() || undefined,- template_name: templateName || undefined,- });- setFullName("");- setStartDate("");- setRole("");- setTemplateName("");- setShowCreate(false);- load();- } catch (err) {- setError(err instanceof Error ? err.message : "Failed to create plan");- } finally {- setSaving(false);- }- }-- return (- <div className="flex flex-col h-full bg-surface">- <main className="flex-1 overflow-y-auto">- <div className="max-w-5xl mx-auto px-6 py-6">- <div className="flex items-baseline justify-between mb-6 gap-4 flex-wrap">- <div>- <h1 className="text-xl font-semibold text-fg">Staff Onboarding</h1>- <p className="text-sm text-fg-muted mt-0.5">- Onboarding plans for new hires — progress, tasks, and the generated- welcome brief.- </p>- </div>- <button- onClick={() => setShowCreate((s) => !s)}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium"- >- {showCreate ? "Cancel" : "New plan"}- </button>- </div>-- {showCreate && (- <form- onSubmit={handleCreate}- className="mb-6 rounded-xl border border-line bg-surface-elevated p-4 grid gap-3 sm:grid-cols-2"- >- <label className="flex flex-col gap-1 text-sm">- <span className="text-fg-muted">Full name *</span>- <input- value={fullName}- onChange={(e) => setFullName(e.target.value)}- required- className="px-3 py-2 rounded-lg bg-surface-input border border-line focus:outline-none focus:border-indigo-500"- />- </label>- <label className="flex flex-col gap-1 text-sm">- <span className="text-fg-muted">Start date *</span>- <input- type="date"- value={startDate}- onChange={(e) => setStartDate(e.target.value)}- required- className="px-3 py-2 rounded-lg bg-surface-input border border-line focus:outline-none focus:border-indigo-500"- />- </label>- <label className="flex flex-col gap-1 text-sm">- <span className="text-fg-muted">Role</span>- <input- value={role}- onChange={(e) => setRole(e.target.value)}- placeholder="e.g. Fractional CFO"- className="px-3 py-2 rounded-lg bg-surface-input border border-line focus:outline-none focus:border-indigo-500"- />- </label>- <label className="flex flex-col gap-1 text-sm">- <span className="text-fg-muted">Template</span>- <select- value={templateName}- onChange={(e) => setTemplateName(e.target.value)}- className="px-3 py-2 rounded-lg bg-surface-input border border-line focus:outline-none focus:border-indigo-500"- >- <option value="">No template (blank plan)</option>- {templates.map((t) => (- <option key={t.name} value={t.name}>- {t.title}- </option>- ))}- </select>- </label>- <div className="sm:col-span-2 flex justify-end">- <button- type="submit"- disabled={saving || !fullName.trim() || !startDate}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white font-medium"- >- {saving ? "Creating…" : "Create plan"}- </button>- </div>- </form>- )}-- {loading && <p className="text-fg-muted text-sm">Loading…</p>}- {error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">- {error}- </div>- )}- {!loading && !error && plans.length === 0 && (- <div className="rounded-xl border border-line bg-surface-elevated p-8 text-center">- <p className="text-fg-muted text-sm">- No onboarding plans yet. Create one above, or ask the Executive to- onboard a new hire in chat.- </p>- </div>- )}-- <div className="space-y-3">- {sorted.map((plan) => {- const meta = STATUS_META[plan.status] ?? STATUS_META.draft;- return (- <Link- key={plan.id}- href={`/staff-onboarding/${plan.id}`}- className="block rounded-xl border border-line bg-surface-elevated p-4 hover:border-indigo-500/50 transition-colors"- >- <div className="flex items-center justify-between gap-3 mb-2 flex-wrap">- <div className="min-w-0">- <span className="font-medium text-fg">{plan.full_name}</span>- {plan.role && (- <span className="text-sm text-fg-muted"> — {plan.role}</span>- )}- </div>- <div className="flex items-center gap-2">- <span- className={`px-2 py-0.5 text-[11px] rounded-full border ${meta.cls}`}- >- {meta.label}- </span>- <span className="text-[11px] text-fg-subtle">- {PHASE_LABEL[plan.current_phase] ?? plan.current_phase}- </span>- </div>- </div>- <div className="flex items-center gap-3">- <ProgressBar pct={plan.completion_pct} />- <span className="text-xs text-fg-subtle tabular-nums w-10 text-right">- {plan.completion_pct}%- </span>- </div>- <div className="mt-1.5 text-[11px] text-fg-subtle">- Starts {plan.start_date}- </div>- </Link>- );- })}- </div>- </div>- </main>- </div>- );-}diff --git a/packages/ui/src/app/talent/candidates/[id]/page.tsx b/packages/ui/src/app/talent/candidates/[id]/page.tsxdeleted file mode 100644index 7e6e051c..00000000--- a/packages/ui/src/app/talent/candidates/[id]/page.tsx+++ /dev/null@@ -1,326 +0,0 @@-"use client";--import Link from "next/link";-import { useParams, useRouter } from "next/navigation";-import { useCallback, useEffect, useMemo, useState } from "react";--import {- Candidate,- CandidateMatch,- CandidateStage,- CANDIDATE_STAGES,- archiveCandidate,- getCandidate,- listCandidates,- setCandidateStage,- similarCandidates,- updateCandidate,-} from "@/lib/api";-import { OfferPanel } from "@/components/talent/OfferPanel";-import { StageBadge } from "@/components/talent/StageBadge";-import { STAGE_META, fitScoreColor } from "@/components/talent/stages";-import { workflowLink } from "@/components/talent/workflowLink";--const EDIT_FIELDS: [keyof Candidate, string][] = [- ["full_name", "Full name"],- ["current_title", "Current title"],- ["current_company", "Current company"],- ["location", "Location"],- ["email", "Email"],- ["linkedin_url", "LinkedIn URL"],- ["source", "Source"],- ["notes", "Notes"],-];--export default function CandidateDetailPage() {- const params = useParams<{ id: string }>();- const router = useRouter();- const candidateId = params?.id ? Number(params.id) : null;-- const [candidate, setCandidate] = useState<Candidate | null>(null);- const [similar, setSimilar] = useState<CandidateMatch[]>([]);- const [nameById, setNameById] = useState<Map<number, Candidate>>(new Map());- const [error, setError] = useState<string | null>(null);- const [loading, setLoading] = useState(true);- const [editing, setEditing] = useState(false);- const [editForm, setEditForm] = useState<Record<string, string>>({});- const [saving, setSaving] = useState(false);- const [stageBusy, setStageBusy] = useState(false);-- const load = useCallback(() => {- if (candidateId == null) return;- getCandidate(candidateId)- .then((c) => {- setCandidate(c);- setEditForm({- full_name: c.full_name,- current_title: c.current_title,- current_company: c.current_company,- location: c.location,- email: c.email ?? "",- linkedin_url: c.linkedin_url ?? "",- source: c.source,- notes: c.notes,- });- })- .catch((e) => setError(e instanceof Error ? e.message : "Failed to load"))- .finally(() => setLoading(false));- similarCandidates(candidateId).then(setSimilar).catch(() => setSimilar([]));- listCandidates()- .then((all) => setNameById(new Map(all.map((c) => [c.id, c]))))- .catch(() => setNameById(new Map()));- }, [candidateId]);-- useEffect(() => {- load();- }, [load]);-- const workflowActions = useMemo(() => {- if (!candidate) return [];- const cid = String(candidate.id);- const eid = String(candidate.engagement_id);- return [- { label: "Screen", href: workflowLink("candidate_screen", { engagement_id: eid, candidate_id: cid }) },- { label: "Outreach", href: workflowLink("candidate_outreach", { candidate_id: cid }) },- { label: "Interviews", href: workflowLink("interview_coordination", { candidate_id: cid }) },- { label: "References", href: workflowLink("reference_check", { candidate_id: cid }) },- { label: "Offer", href: workflowLink("offer_approval", { candidate_id: cid }) },- { label: "Onboarding", href: workflowLink("new_hire_onboarding", { candidate_id: cid }) },- ];- }, [candidate]);-- async function saveEdits() {- if (candidateId == null) return;- setSaving(true);- try {- const updated = await updateCandidate(candidateId, {- full_name: editForm.full_name,- current_title: editForm.current_title,- current_company: editForm.current_company,- location: editForm.location,- email: editForm.email || null,- linkedin_url: editForm.linkedin_url || null,- source: editForm.source,- notes: editForm.notes,- });- setCandidate(updated);- setEditing(false);- } catch (e) {- setError(e instanceof Error ? e.message : "Failed to save");- } finally {- setSaving(false);- }- }-- async function moveStage(stage: CandidateStage) {- if (candidateId == null || !candidate || candidate.stage === stage) return;- setStageBusy(true);- try {- setCandidate(await setCandidateStage(candidateId, stage));- } catch (e) {- setError(e instanceof Error ? e.message : "Failed to move stage");- } finally {- setStageBusy(false);- }- }-- async function handleArchive() {- if (candidateId == null || !candidate) return;- try {- await archiveCandidate(candidateId);- router.push(`/talent/engagements/${candidate.engagement_id}`);- } catch (e) {- setError(e instanceof Error ? e.message : "Failed to archive");- }- }-- if (loading) return <div className="p-6 text-fg-muted text-sm">Loading…</div>;- if (error && !candidate) {- return (- <div className="p-6">- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">- {error}- </div>- </div>- );- }- if (!candidate) return <div className="p-6 text-fg-muted text-sm">Candidate not found.</div>;-- const subtitle = [candidate.current_title, candidate.current_company].filter(Boolean).join(" · ");-- return (- <div className="flex flex-col h-full bg-surface">- <main className="flex-1 overflow-y-auto">- <div className="max-w-4xl mx-auto px-6 py-6">- <Link- href={`/talent/engagements/${candidate.engagement_id}`}- className="text-xs text-fg-muted hover:text-fg"- >- ← Engagement- </Link>-- <div className="flex items-start justify-between mt-2 mb-6 gap-4">- <div className="min-w-0">- <h1 className="text-xl font-semibold text-fg flex items-center gap-2">- {candidate.full_name}- <StageBadge stage={candidate.stage} />- </h1>- {subtitle && <p className="text-sm text-fg-muted mt-0.5">{subtitle}</p>}- </div>- <div className="flex items-center gap-3 shrink-0">- <div className="text-right">- <div className={`text-2xl font-bold tabular-nums ${fitScoreColor(candidate.fit_score)}`}>- {candidate.fit_score ?? "—"}- </div>- <div className="text-[10px] text-fg-subtle uppercase">Fit score</div>- </div>- <button- onClick={() => setEditing((v) => !v)}- className="px-3 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay text-fg"- >- {editing ? "Cancel" : "Edit"}- </button>- <button- onClick={handleArchive}- className="px-3 py-2 text-sm rounded-lg border border-rose-500/40 text-rose-300 hover:bg-rose-500/10"- >- Archive- </button>- </div>- </div>-- {error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">- {error}- </div>- )}-- {/* Stage control */}- <div className="mb-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-2">- Pipeline stage- </div>- <div className="flex flex-wrap gap-2">- {CANDIDATE_STAGES.map((stage) => {- const active = candidate.stage === stage;- return (- <button- key={stage}- disabled={stageBusy || active}- onClick={() => moveStage(stage)}- className={`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors disabled:opacity-100 ${- active- ? "bg-indigo-600/30 border-indigo-500/50 text-indigo-200"- : "bg-surface-input border-line text-fg-muted hover:border-indigo-500/40 disabled:opacity-50"- }`}- >- {STAGE_META[stage].label}- </button>- );- })}- </div>- </div>-- {/* Offer lifecycle */}- <OfferPanel candidate={candidate} onChanged={load} />-- {/* Run workflows */}- <div className="mb-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-2">- Run a workflow- </div>- <div className="flex flex-wrap gap-2">- {workflowActions.map((a) => (- <Link- key={a.label}- href={a.href}- className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-medium"- >- {a.label}- </Link>- ))}- </div>- </div>-- {editing && (- <div className="rounded-xl border border-line bg-surface-elevated p-4 mb-6 space-y-3">- {EDIT_FIELDS.map(([key, label]) => (- <label key={key} className="block">- <span className="text-xs text-fg-muted">{label}</span>- {key === "notes" ? (- <textarea- value={editForm[key] ?? ""}- onChange={(e) => setEditForm((f) => ({ ...f, [key]: e.target.value }))}- rows={3}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- ) : (- <input- value={editForm[key] ?? ""}- onChange={(e) => setEditForm((f) => ({ ...f, [key]: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- )}- </label>- ))}- <button- disabled={saving || !editForm.full_name?.trim()}- onClick={saveEdits}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 font-medium"- >- {saving ? "Saving…" : "Save"}- </button>- </div>- )}-- {/* Screening summary */}- {candidate.screening_summary && (- <div className="mb-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-1">- Screening summary- </div>- <p className="text-sm text-fg-muted whitespace-pre-wrap">{candidate.screening_summary}</p>- </div>- )}-- {candidate.notes && !editing && (- <div className="mb-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-1">Notes</div>- <p className="text-sm text-fg-muted whitespace-pre-wrap">{candidate.notes}</p>- </div>- )}-- {/* Similar candidates */}- <div className="border-t border-line pt-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-2">- Similar candidates- </div>- {similar.length === 0 ? (- <p className="text-sm text-fg-subtle">No similar candidates indexed yet.</p>- ) : (- <div className="space-y-2">- {similar.map((m) => {- const cand = nameById.get(m.candidate_id);- return (- <Link- key={m.candidate_id}- href={`/talent/candidates/${m.candidate_id}`}- className="flex items-center justify-between rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-3 group"- >- <span className="text-sm text-fg group-hover:text-indigo-300 truncate">- {cand ? cand.full_name : `Candidate #${m.candidate_id}`}- </span>- <span className={`text-sm font-semibold tabular-nums ${fitScoreColor(Math.round(m.score * 100))}`}>- {Math.round(m.score * 100)}%- </span>- </Link>- );- })}- </div>- )}- </div>- </div>- </main>- </div>- );-}diff --git a/packages/ui/src/app/talent/engagements/[id]/page.tsx b/packages/ui/src/app/talent/engagements/[id]/page.tsxdeleted file mode 100644index be1f3aad..00000000--- a/packages/ui/src/app/talent/engagements/[id]/page.tsx+++ /dev/null@@ -1,438 +0,0 @@-"use client";--import Link from "next/link";-import { useParams, useRouter } from "next/navigation";-import { useCallback, useEffect, useMemo, useState } from "react";--import {- Candidate,- CandidateMatch,- Engagement,- ENGAGEMENT_STATUSES,- EngagementStatus,- archiveEngagement,- createCandidate,- getEngagement,- listCandidates,- matchCandidatesForEngagement,- updateEngagement,-} from "@/lib/api";-import { CandidateCard } from "@/components/talent/CandidateCard";-import { StatusBadge } from "@/components/talent/StageBadge";-import { fitScoreColor } from "@/components/talent/stages";--function AddCandidateModal({- engagementId,- onCreated,- onClose,-}: {- engagementId: number;- onCreated: (c: Candidate) => void;- onClose: () => void;-}) {- const [form, setForm] = useState({- full_name: "",- current_title: "",- current_company: "",- location: "",- email: "",- linkedin_url: "",- source: "",- });- const [saving, setSaving] = useState(false);- const [err, setErr] = useState<string | null>(null);-- async function submit() {- setSaving(true);- setErr(null);- try {- const c = await createCandidate({- engagement_id: engagementId,- full_name: form.full_name.trim(),- current_title: form.current_title.trim(),- current_company: form.current_company.trim(),- location: form.location.trim(),- email: form.email.trim() || null,- linkedin_url: form.linkedin_url.trim() || null,- source: form.source.trim(),- });- onCreated(c);- } catch (e) {- setErr(e instanceof Error ? e.message : "Failed to create");- setSaving(false);- }- }-- const fields: [keyof typeof form, string, string][] = [- ["full_name", "Full name *", "Dana Cole"],- ["current_title", "Current title", "Drilling Director"],- ["current_company", "Current company", "Permian Co"],- ["location", "Location", "Midland, TX"],- ["email", "Email", "[email protected]"],- ["linkedin_url", "LinkedIn URL", "https://linkedin.com/in/…"],- ["source", "Source", "referral"],- ];-- return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60" onClick={onClose}>- <div- className="w-full max-w-lg bg-surface border border-line rounded-2xl shadow-2xl p-6 mx-4 max-h-[90vh] overflow-y-auto"- onClick={(e) => e.stopPropagation()}- >- <h2 className="text-lg font-semibold text-fg mb-4">Add candidate</h2>- <div className="space-y-3">- {fields.map(([key, label, placeholder]) => (- <label key={key} className="block">- <span className="text-xs text-fg-muted">{label}</span>- <input- value={form[key]}- onChange={(e) => setForm((f) => ({ ...f, [key]: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- placeholder={placeholder}- />- </label>- ))}- </div>- {err && <p className="text-xs text-rose-300 mt-3">{err}</p>}- <div className="flex gap-2 mt-5">- <button- disabled={saving || !form.full_name.trim()}- onClick={submit}- className="flex-1 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 font-medium"- >- {saving ? "Adding…" : "Add candidate"}- </button>- <button- disabled={saving}- onClick={onClose}- className="px-4 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >- Cancel- </button>- </div>- </div>- </div>- );-}--export default function EngagementDetailPage() {- const params = useParams<{ id: string }>();- const router = useRouter();- const engagementId = params?.id ? Number(params.id) : null;-- const [engagement, setEngagement] = useState<Engagement | null>(null);- const [allCandidates, setAllCandidates] = useState<Candidate[]>([]);- const [matches, setMatches] = useState<CandidateMatch[] | null>(null);- const [matchError, setMatchError] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);- const [loading, setLoading] = useState(true);- const [editing, setEditing] = useState(false);- const [editForm, setEditForm] = useState<{- role_title: string;- department: string;- status: EngagementStatus;- location: string;- comp_band: string;- must_haves: string;- description: string;- }>({ role_title: "", department: "", status: "open", location: "", comp_band: "", must_haves: "", description: "" });- const [saving, setSaving] = useState(false);- const [showAddCandidate, setShowAddCandidate] = useState(false);-- const load = useCallback(() => {- if (engagementId == null) return;- getEngagement(engagementId)- .then(async (e) => {- setEngagement(e);- setEditForm({- role_title: e.role_title,- department: e.department,- status: e.status,- location: e.location,- comp_band: e.comp_band,- must_haves: e.must_haves,- description: e.description,- });- setAllCandidates(await listCandidates());- })- .catch((err) => setError(err instanceof Error ? err.message : "Failed to load"))- .finally(() => setLoading(false));- }, [engagementId]);-- useEffect(() => {- load();- }, [load]);-- const engagementCandidates = useMemo(- () => allCandidates.filter((c) => c.engagement_id === engagementId),- [allCandidates, engagementId],- );- const nameById = useMemo(() => {- const m = new Map<number, Candidate>();- for (const c of allCandidates) m.set(c.id, c);- return m;- }, [allCandidates]);-- async function saveEdits() {- if (engagementId == null) return;- setSaving(true);- try {- const updated = await updateEngagement(engagementId, editForm);- setEngagement(updated);- setEditing(false);- } catch (e) {- setError(e instanceof Error ? e.message : "Failed to save");- } finally {- setSaving(false);- }- }-- async function handleArchive() {- if (engagementId == null || !engagement) return;- try {- await archiveEngagement(engagementId);- router.push("/talent/searches");- } catch (e) {- setError(e instanceof Error ? e.message : "Failed to archive");- }- }-- async function loadMatches() {- if (engagementId == null) return;- setMatchError(null);- try {- setMatches(await matchCandidatesForEngagement(engagementId));- } catch (e) {- setMatchError(e instanceof Error ? e.message : "Failed to load matches");- }- }-- if (loading) return <div className="p-6 text-fg-muted text-sm">Loading…</div>;- if (error) {- return (- <div className="p-6">- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm">- {error}- </div>- </div>- );- }- if (!engagement) return <div className="p-6 text-fg-muted text-sm">Engagement not found.</div>;-- return (- <div className="flex flex-col h-full bg-surface">- {showAddCandidate && engagementId != null && (- <AddCandidateModal- engagementId={engagementId}- onCreated={(c) => {- setAllCandidates((prev) => [...prev, c]);- setShowAddCandidate(false);- }}- onClose={() => setShowAddCandidate(false)}- />- )}- <main className="flex-1 overflow-y-auto">- <div className="max-w-4xl mx-auto px-6 py-6">- <Link- href="/talent/searches"- className="text-xs text-fg-muted hover:text-fg"- >- ← Searches- </Link>-- <div className="flex items-start justify-between mt-2 mb-6 gap-4">- <div className="min-w-0">- <h1 className="text-xl font-semibold text-fg flex items-center gap-2">- {engagement.role_title}- <StatusBadge status={engagement.status} />- </h1>- <p className="text-sm text-fg-muted mt-0.5">- {[engagement.department, engagement.location, engagement.comp_band]- .filter(Boolean)- .join(" · ") || "—"}- </p>- </div>- <div className="flex gap-2 shrink-0">- <button- onClick={() => setEditing((v) => !v)}- className="px-3 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay text-fg"- >- {editing ? "Cancel" : "Edit"}- </button>- <button- onClick={handleArchive}- className="px-3 py-2 text-sm rounded-lg border border-rose-500/40 text-rose-300 hover:bg-rose-500/10"- >- Archive- </button>- </div>- </div>-- {editing && (- <div className="rounded-xl border border-line bg-surface-elevated p-4 mb-6 space-y-3">- <div className="grid grid-cols-2 gap-3">- <label className="block">- <span className="text-xs text-fg-muted">Role title</span>- <input- value={editForm.role_title}- onChange={(e) => setEditForm((f) => ({ ...f, role_title: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- <label className="block">- <span className="text-xs text-fg-muted">Department</span>- <input- value={editForm.department}- onChange={(e) => setEditForm((f) => ({ ...f, department: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- </div>- <div className="grid grid-cols-3 gap-3">- <label className="block">- <span className="text-xs text-fg-muted">Status</span>- <select- value={editForm.status}- onChange={(e) =>- setEditForm((f) => ({ ...f, status: e.target.value as EngagementStatus }))- }- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- >- {ENGAGEMENT_STATUSES.map((s) => (- <option key={s} value={s}>- {s}- </option>- ))}- </select>- </label>- <label className="block">- <span className="text-xs text-fg-muted">Location</span>- <input- value={editForm.location}- onChange={(e) => setEditForm((f) => ({ ...f, location: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- <label className="block">- <span className="text-xs text-fg-muted">Comp band</span>- <input- value={editForm.comp_band}- onChange={(e) => setEditForm((f) => ({ ...f, comp_band: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- </div>- <label className="block">- <span className="text-xs text-fg-muted">Must-haves</span>- <textarea- value={editForm.must_haves}- onChange={(e) => setEditForm((f) => ({ ...f, must_haves: e.target.value }))}- rows={3}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- <label className="block">- <span className="text-xs text-fg-muted">Description</span>- <textarea- value={editForm.description}- onChange={(e) => setEditForm((f) => ({ ...f, description: e.target.value }))}- rows={3}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- <button- disabled={saving}- onClick={saveEdits}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 font-medium"- >- {saving ? "Saving…" : "Save"}- </button>- </div>- )}-- {engagement.must_haves && !editing && (- <div className="mb-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-1">- Must-haves- </div>- <p className="text-sm text-fg-muted whitespace-pre-wrap">{engagement.must_haves}</p>- </div>- )}-- {/* Candidates */}- <div className="flex items-center justify-between mb-3">- <h2 className="text-sm font-semibold text-fg">- Candidates ({engagementCandidates.length})- </h2>- <button- onClick={() => setShowAddCandidate(true)}- className="px-3 py-1.5 text-xs rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium"- >- + Add candidate- </button>- </div>- {engagementCandidates.length === 0 ? (- <p className="text-sm text-fg-subtle mb-6">No candidates yet.</p>- ) : (- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 mb-6">- {engagementCandidates.map((c) => (- <CandidateCard key={c.id} candidate={c} />- ))}- </div>- )}-- {/* Talent-graph matches */}- <div className="flex items-center justify-between mb-3 border-t border-line pt-6">- <div>- <h2 className="text-sm font-semibold text-fg">Suggested matches</h2>- <p className="text-xs text-fg-muted mt-0.5">- Best-fit candidates across the whole pool, ranked against this role.- </p>- </div>- <button- onClick={loadMatches}- className="px-3 py-1.5 text-xs rounded-lg border border-line hover:bg-surface-overlay text-fg"- >- {matches ? "Refresh" : "Find matches"}- </button>- </div>- {matchError && <p className="text-sm text-rose-300">{matchError}</p>}- {matches && matches.length === 0 && (- <p className="text-sm text-fg-subtle">No matches found (try Reindex on the pipeline).</p>- )}- {matches && matches.length > 0 && (- <div className="space-y-2">- {matches.map((m) => {- const cand = nameById.get(m.candidate_id);- return (- <Link- key={m.candidate_id}- href={`/talent/candidates/${m.candidate_id}`}- className="flex items-center justify-between rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-3 group"- >- <div className="min-w-0">- <div className="text-sm font-semibold text-fg group-hover:text-indigo-300 truncate">- {cand ? cand.full_name : `Candidate #${m.candidate_id}`}- </div>- <div className="text-xs text-fg-muted truncate">- {cand?.current_title || m.stage}- </div>- </div>- <div- className={`text-sm font-semibold tabular-nums ${fitScoreColor(- Math.round(m.score * 100),- )}`}- title="Match score"- >- {Math.round(m.score * 100)}%- </div>- </Link>- );- })}- </div>- )}- </div>- </main>- </div>- );-}diff --git a/packages/ui/src/app/talent/page.tsx b/packages/ui/src/app/talent/page.tsxdeleted file mode 100644index 19ad8252..00000000--- a/packages/ui/src/app/talent/page.tsx+++ /dev/null@@ -1,147 +0,0 @@-"use client";--import Link from "next/link";-import { useEffect, useMemo, useState } from "react";--import {- Candidate,- Engagement,- listCandidates,- listEngagements,-} from "@/lib/api";-import { CandidateCard } from "@/components/talent/CandidateCard";-import { STAGE_META, PIPELINE_STAGES } from "@/components/talent/stages";--export default function TalentPage() {- const [candidates, setCandidates] = useState<Candidate[]>([]);- const [engagements, setEngagements] = useState<Engagement[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [engagementFilter, setEngagementFilter] = useState<string>("");-- useEffect(() => {- Promise.all([listCandidates(), listEngagements()])- .then(([c, e]) => {- setCandidates(c);- setEngagements(e);- })- .catch((err) => setError(err instanceof Error ? err.message : "Failed to load"))- .finally(() => setLoading(false));- }, []);-- const filtered = useMemo(() => {- if (!engagementFilter) return candidates;- const id = Number(engagementFilter);- return candidates.filter((c) => c.engagement_id === id);- }, [candidates, engagementFilter]);-- const byStage = useMemo(() => {- const map: Record<string, Candidate[]> = {};- for (const c of filtered) (map[c.stage] ??= []).push(c);- return map;- }, [filtered]);-- const rejected = byStage["rejected"] ?? [];-- return (- <div className="flex flex-col h-full bg-surface">- <main className="flex-1 overflow-y-auto">- <div className="max-w-7xl mx-auto px-6 py-6">- <div className="flex items-baseline justify-between mb-6 gap-4 flex-wrap">- <div>- <h1 className="text-xl font-semibold text-fg">Talent Pipeline</h1>- <p className="text-sm text-fg-muted mt-0.5">- Candidates across all searches, by stage. Manage open roles under{" "}- <Link href="/talent/searches" className="text-indigo-300 hover:text-indigo-200">- Searches- </Link>- .- </p>- </div>- <div className="flex items-center gap-2">- <select- value={engagementFilter}- onChange={(e) => setEngagementFilter(e.target.value)}- className="px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- >- <option value="">All engagements</option>- {engagements.map((e) => (- <option key={e.id} value={String(e.id)}>- {e.role_title}- </option>- ))}- </select>- <Link- href="/talent/searches"- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium"- >- Searches →- </Link>- </div>- </div>-- {loading && <p className="text-fg-muted text-sm">Loading…</p>}- {error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">- {error}- </div>- )}- {!loading && !error && candidates.length === 0 && (- <div className="rounded-xl border border-line bg-surface-elevated p-8 text-center">- <p className="text-fg-muted text-sm mb-3">No candidates yet.</p>- <Link- href="/talent/searches"- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white"- >- Open a search →- </Link>- </div>- )}-- {!loading && !error && candidates.length > 0 && (- <>- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">- {PIPELINE_STAGES.map((stage) => {- const items = byStage[stage] ?? [];- return (- <div key={stage} className="flex flex-col">- <div className="flex items-center justify-between mb-2 px-1">- <span className="text-xs font-semibold text-fg-muted uppercase tracking-wide">- {STAGE_META[stage].label}- </span>- <span className="text-xs text-fg-subtle tabular-nums">{items.length}</span>- </div>- <div className="space-y-2">- {items.map((c) => (- <CandidateCard key={c.id} candidate={c} />- ))}- {items.length === 0 && (- <div className="rounded-xl border border-dashed border-line p-4 text-center text-[11px] text-fg-subtle">- None- </div>- )}- </div>- </div>- );- })}- </div>-- {rejected.length > 0 && (- <div className="mt-8">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-2">- Rejected ({rejected.length})- </div>- <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3">- {rejected.map((c) => (- <CandidateCard key={c.id} candidate={c} />- ))}- </div>- </div>- )}- </>- )}- </div>- </main>- </div>- );-}diff --git a/packages/ui/src/app/talent/searches/page.tsx b/packages/ui/src/app/talent/searches/page.tsxdeleted file mode 100644index 63f55f64..00000000--- a/packages/ui/src/app/talent/searches/page.tsx+++ /dev/null@@ -1,251 +0,0 @@-"use client";--import Link from "next/link";-import { useEffect, useState } from "react";--import {- Engagement,- EngagementStatus,- createEngagement,- listEngagements,- reindexTalent,-} from "@/lib/api";-import { StatusBadge } from "@/components/talent/StageBadge";--function AddSearchModal({- onCreated,- onClose,-}: {- onCreated: (e: Engagement) => void;- onClose: () => void;-}) {- const [form, setForm] = useState({- role_title: "",- department: "",- location: "",- comp_band: "",- must_haves: "",- description: "",- });- const [saving, setSaving] = useState(false);- const [err, setErr] = useState<string | null>(null);-- async function submit() {- setSaving(true);- setErr(null);- try {- const e = await createEngagement({- role_title: form.role_title.trim(),- department: form.department.trim(),- location: form.location.trim(),- comp_band: form.comp_band.trim(),- must_haves: form.must_haves.trim(),- description: form.description.trim(),- });- onCreated(e);- } catch (e) {- setErr(e instanceof Error ? e.message : "Failed to create");- setSaving(false);- }- }-- return (- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60" onClick={onClose}>- <div- className="w-full max-w-lg bg-surface border border-line rounded-2xl shadow-2xl p-6 mx-4 max-h-[90vh] overflow-y-auto"- onClick={(e) => e.stopPropagation()}- >- <h2 className="text-lg font-semibold text-fg mb-4">New search</h2>- <div className="space-y-3">- <label className="block">- <span className="text-xs text-fg-muted">Role title *</span>- <input- value={form.role_title}- onChange={(e) => setForm((f) => ({ ...f, role_title: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- placeholder="VP Drilling"- />- </label>- <div className="grid grid-cols-2 gap-3">- <label className="block">- <span className="text-xs text-fg-muted">Department</span>- <input- value={form.department}- onChange={(e) => setForm((f) => ({ ...f, department: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- placeholder="Drilling"- />- </label>- <label className="block">- <span className="text-xs text-fg-muted">Location</span>- <input- value={form.location}- onChange={(e) => setForm((f) => ({ ...f, location: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- placeholder="Midland, TX"- />- </label>- </div>- <label className="block">- <span className="text-xs text-fg-muted">Comp band</span>- <input- value={form.comp_band}- onChange={(e) => setForm((f) => ({ ...f, comp_band: e.target.value }))}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- placeholder="$300-350K + equity"- />- </label>- <label className="block">- <span className="text-xs text-fg-muted">Must-haves</span>- <textarea- value={form.must_haves}- onChange={(e) => setForm((f) => ({ ...f, must_haves: e.target.value }))}- rows={3}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- placeholder="10+ yrs upstream, cycle-tested, HSE track record"- />- </label>- <label className="block">- <span className="text-xs text-fg-muted">Description</span>- <textarea- value={form.description}- onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}- rows={3}- className="mt-1 w-full px-3 py-2 rounded-lg bg-surface-input border border-line text-sm focus:outline-none focus:border-indigo-500"- />- </label>- </div>- {err && <p className="text-xs text-rose-300 mt-3">{err}</p>}- <div className="flex gap-2 mt-5">- <button- disabled={saving || !form.role_title.trim()}- onClick={submit}- className="flex-1 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white disabled:opacity-50 font-medium"- >- {saving ? "Creating…" : "Create search"}- </button>- <button- disabled={saving}- onClick={onClose}- className="px-4 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay disabled:opacity-50"- >- Cancel- </button>- </div>- </div>- </div>- );-}--export default function SearchesPage() {- const [engagements, setEngagements] = useState<Engagement[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [showAdd, setShowAdd] = useState(false);- const [reindexMsg, setReindexMsg] = useState<string | null>(null);-- useEffect(() => {- listEngagements()- .then(setEngagements)- .catch((err) => setError(err instanceof Error ? err.message : "Failed to load"))- .finally(() => setLoading(false));- }, []);-- // Repair action: rebuild the candidate match index from the database. Normal- // create/edit/stage/archive already auto-index — this is only for when the- // vector index drifts out of sync (e.g. it was wiped or an index write failed).- async function handleReindex() {- setReindexMsg("Reindexing…");- try {- const { indexed } = await reindexTalent();- setReindexMsg(`Reindexed ${indexed} candidate(s).`);- } catch (e) {- setReindexMsg(e instanceof Error ? e.message : "Reindex failed");- }- }-- return (- <div className="flex flex-col h-full bg-surface">- {showAdd && (- <AddSearchModal- onCreated={(e) => {- setEngagements((prev) => [...prev, e]);- setShowAdd(false);- }}- onClose={() => setShowAdd(false)}- />- )}- <main className="flex-1 overflow-y-auto">- <div className="max-w-4xl mx-auto px-6 py-6">- <Link href="/talent" className="text-xs text-fg-muted hover:text-fg">- ← Talent pipeline- </Link>-- <div className="flex items-baseline justify-between mt-2 mb-6 gap-4">- <div>- <h1 className="text-xl font-semibold text-fg">Searches</h1>- <p className="text-sm text-fg-muted mt-0.5">- Open roles we're hiring for in this company.- </p>- </div>- <div className="flex items-center gap-2">- <button- onClick={handleReindex}- className="px-3 py-2 text-sm rounded-lg border border-line hover:bg-surface-overlay text-fg"- title="Rebuild the talent-match index from the database (repair tool)"- >- Reindex- </button>- <button- onClick={() => setShowAdd(true)}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white font-medium"- >- + New search- </button>- </div>- </div>-- {reindexMsg && <div className="mb-4 text-xs text-fg-muted">{reindexMsg}</div>}- {loading && <p className="text-fg-muted text-sm">Loading…</p>}- {error && (- <div className="p-3 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-sm mb-4">- {error}- </div>- )}- {!loading && !error && engagements.length === 0 && (- <div className="rounded-xl border border-line bg-surface-elevated p-8 text-center">- <p className="text-fg-muted text-sm mb-3">No searches yet.</p>- <button- onClick={() => setShowAdd(true)}- className="px-4 py-2 text-sm rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white"- >- Open your first search →- </button>- </div>- )}- {!loading && !error && engagements.length > 0 && (- <div className="space-y-2">- {engagements.map((e) => (- <Link- key={e.id}- href={`/talent/engagements/${e.id}`}- className="flex items-center justify-between rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-3 group"- >- <div>- <div className="text-sm font-semibold text-fg group-hover:text-indigo-300">- {e.role_title}- </div>- <div className="text-xs text-fg-muted mt-0.5">- {[e.department, e.location, e.comp_band].filter(Boolean).join(" · ") || "—"}- </div>- </div>- <StatusBadge status={e.status as EngagementStatus} />- </Link>- ))}- </div>- )}- </div>- </main>- </div>- );-}diff --git a/packages/ui/src/components/Briefing.tsx b/packages/ui/src/components/Briefing.tsxindex cd40554e..f96c9720 100644--- a/packages/ui/src/components/Briefing.tsx+++ b/packages/ui/src/components/Briefing.tsx@@ -13,15 +13,12 @@ import {rejectDecision,reopenAlert,reviewAlerts,- type CandidateStage,type DepartmentBriefItem,type HandledItem,type InFlightItem,- type OnboardingBriefItem,type PersonBriefItem,type ClientCockpitCard,type ProposalItem,- type TalentBriefItem,type Today,} from "@/lib/api";import { clientCountsSummary, renewalBadge } from "@/lib/practice";@@ -36,9 +33,7 @@ import {type HandledRow,} from "@/lib/handled";import InfoTip from "./InfoTip";-import { phaseLabel } from "./onboarding/meta";import { SectionHeading } from "./memories/shared";-import { PIPELINE_STAGES, STAGE_META, STATUS_META } from "./talent/stages";// Future-relative label for a pending run time ("in 8h"). Past/blank →// "soon" (the caller renders "overdue" separately via the backend flag).@@ -450,8 +445,6 @@ const SECTION_IDS = {monitoring: "sec-monitoring",departments: "sec-departments",people: "sec-people",- talent: "sec-talent",- onboarding: "sec-onboarding",practice: "sec-practice",} as const;@@ -480,7 +473,6 @@ function briefingStats(args: {deptAtRisk: number;inFlight: number;monitoring: number;- searchesNeedingAttention: number;}): StatPill[] {const pills: StatPill[] = [];const peopleTargets = [SECTION_IDS.people];@@ -498,12 +490,6 @@ function briefingStats(args: {pills.push({ label: `${args.deptAtRisk} dept${args.deptAtRisk === 1 ? "" : "s"} at risk`, tone: "amber", targetIds: [SECTION_IDS.departments] });if (args.inFlight > 0)pills.push({ label: `${args.inFlight} in flight`, tone: "sky", targetIds: [SECTION_IDS.inFlight] });- if (args.searchesNeedingAttention > 0)- pills.push({- label: `${args.searchesNeedingAttention} search${args.searchesNeedingAttention === 1 ? "" : "es"} to move`,- tone: "indigo",- targetIds: [SECTION_IDS.talent],- });// Passive watchlist signals — quietest pill, last, so it never crowds the// action-oriented ones but the lane is still reachable in one click.if (args.monitoring > 0)@@ -1105,189 +1091,6 @@ function InFlightPanel({ inFlight, id }: { inFlight: InFlightItem[]; id?: string);}-// Seed prompt for handing a search off into chat — mirrors the proposal-// "Discuss" flow so the Executive picks up with the right engagement in mind.-function buildTalentSeed(t: TalentBriefItem): string {- return (- `Let's review the ${t.role_title} search. ` +- `Where do we stand across the pipeline, and what's the next move? ` +- `(engagement ${t.engagement_id})`- );-}--// One open search as a compact card: role • department • status, the pipeline-// rollup, and attention badges (offers out / stalled / to screen). Click-to--// discuss seeds chat; a quiet link opens the full engagement page.-function TalentCard({- item,- onContinue,-}: {- item: TalentBriefItem;- onContinue?: (p: string) => void;-}) {- const status = STATUS_META[item.status as keyof typeof STATUS_META];- const badges: { label: string; pill: string }[] = [];- const expiringSoon = item.offers_expiring_soon ?? 0;- // Red (rejected) pill — an offer about to lapse undecided is the most- // time-critical signal a search can carry, so it leads the badge row.- if (expiringSoon > 0)- badges.push({ label: `${expiringSoon} offer${expiringSoon === 1 ? "" : "s"} expiring`, pill: STAGE_META.rejected.pill });- if (item.offers_out > 0)- badges.push({ label: `${item.offers_out} offer${item.offers_out === 1 ? "" : "s"} out`, pill: STAGE_META.offer.pill });- // Amber (warning), not the red `rejected` pill — a stalled candidate is still- // in play and needs a nudge, not one that was cut from the pipeline.- if (item.stalled_count > 0)- badges.push({ label: `${item.stalled_count} stalled`, pill: STATUS_META.on_hold.pill });- if (item.needs_screening > 0)- badges.push({ label: `${item.needs_screening} to screen`, pill: STAGE_META.lead.pill });-- const header = (- <div className="flex items-start justify-between gap-2">- <div className="min-w-0">- <div className="text-xs font-medium text-fg truncate" title={item.department ? `${item.role_title} — ${item.department}` : item.role_title}>- {item.role_title}- </div>- {item.department && (- <div className="text-[11px] text-fg-muted truncate">{item.department}</div>- )}- </div>- {status && (- <span className={`flex-shrink-0 inline-flex items-center rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${status.pill}`}>- {status.label}- </span>- )}- </div>- );-- return (- <div className="group py-3 pl-2 border-l-2 border-transparent hover:bg-surface-overlay/30 transition-colors">- {onContinue ? (- <button- type="button"- onClick={() => onContinue(buildTalentSeed(item))}- className="block w-full text-left cursor-pointer focus:outline-none focus:ring-1 focus:ring-indigo-500/40 rounded"- >- {header}- </button>- ) : (- <Link href={`/talent/engagements/${item.engagement_id}`} className="block">- {header}- </Link>- )}- <div className="mt-1.5 flex flex-wrap items-center gap-1">- {PIPELINE_STAGES.map((stage: CandidateStage) => {- const n = item.stage_counts[stage] ?? 0;- if (n === 0) return null;- return (- <span- key={stage}- className={`inline-flex items-center rounded border px-1.5 py-0.5 text-[10px] ${STAGE_META[stage].pill}`}- title={`${n} ${STAGE_META[stage].label}`}- >- {STAGE_META[stage].label} {n}- </span>- );- })}- {item.candidate_count === 0 && (- <span className="text-[10px] text-fg-subtle">No candidates yet</span>- )}- </div>- {badges.length > 0 && (- <div className="mt-1 flex flex-wrap gap-1">- {badges.map((b) => (- <span key={b.label} className={`inline-flex items-center rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${b.pill}`}>- {b.label}- </span>- ))}- </div>- )}- </div>- );-}--// Executive Search — active engagements rolled up by pipeline stage. Ambient-// awareness card in the right column; clicking a search hands off to chat.-// Takes its anchor `id` as a prop (set by the caller).-function TalentPanel({- talent,- onContinue,- id,-}: {- talent: TalentBriefItem[];- onContinue?: (p: string) => void;- id?: string;-}) {- if (talent.length === 0) return null;- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center justify-between gap-2 mb-1">- <div className="flex items-center gap-1.5">- <SectionHeading title="Executive search" count={talent.length} icon="search" />- <InfoTip align="left">- Active searches and where each stands across the pipeline. Click a- search to pick it up in chat — review fit, screen a candidate, or- move the next step.- </InfoTip>- </div>- <Link href="/talent" className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300">View all</Link>- </div>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {talent.map((t) => (- <TalentCard key={`talent-${t.engagement_id}`} item={t} onContinue={onContinue} />- ))}- </div>- </section>- );-}--function buildOnboardingSeed(o: OnboardingBriefItem): string {- const role = o.role ? ` (${o.role})` : "";- return `How is ${o.full_name}${role}'s onboarding going? Walk me through where their plan stands and anything overdue.`;-}--function OnboardingCard({- item,- onContinue,-}: {- item: OnboardingBriefItem;- onContinue?: (p: string) => void;-}) {- const startLabel =- item.days_to_start == null- ? ""- : item.days_to_start > 0- ? `starts in ${item.days_to_start}d`- : item.days_to_start < 0- ? `day ${Math.abs(item.days_to_start) + 1}`- : "starts today";- return (- <div className="py-2 first:pt-0 last:pb-0">- <button- onClick={() => onContinue?.(buildOnboardingSeed(item))}- className="w-full text-left group"- >- <div className="flex items-center justify-between gap-2">- <span className="text-sm text-fg group-hover:text-indigo-300 truncate">- {item.full_name}- {item.role && <span className="text-fg-muted"> — {item.role}</span>}- </span>- <span className="text-xs text-fg-subtle tabular-nums flex-shrink-0">- {item.completion_pct}%- </span>- </div>- <div className="mt-1 flex items-center gap-2 text-[11px] text-fg-subtle">- <span>{phaseLabel(item.current_phase)}</span>- {item.overdue_tasks > 0 && (- <span className="text-rose-300">{item.overdue_tasks} overdue</span>- )}- {item.open_tasks > 0 && <span>{item.open_tasks} open</span>}- {startLabel && <span>· {startLabel}</span>}- </div>- </button>- </div>- );-}-// Multi-client practice mode only: rollup cards for PARKED client slots so// the operator sees the whole practice from the active client's brief. The// backend sends [] for single-company installs (0-1 slots), so this renders@@ -1348,42 +1151,6 @@ function PracticeClientsPanel({);}-function OnboardingPanel({- onboarding,- onContinue,- id,-}: {- onboarding: OnboardingBriefItem[];- onContinue?: (p: string) => void;- id?: string;-}) {- if (onboarding.length === 0) return null;- return (- <section id={id} className="rounded-xl border border-line bg-surface-elevated p-4">- <div className="flex items-center justify-between gap-2 mb-1">- <div className="flex items-center gap-1.5">- <SectionHeading title="Staff onboarding" count={onboarding.length} icon="users" />- <InfoTip align="left">- New hires currently ramping. Click one to pick it up in chat — check- progress, mark tasks done, or move their plan forward.- </InfoTip>- </div>- <Link- href="/staff-onboarding"- className="flex-shrink-0 text-xs text-indigo-400 hover:text-indigo-300"- >- View all- </Link>- </div>- <div className="max-h-[32rem] overflow-y-auto pr-1 divide-y divide-line">- {onboarding.map((o) => (- <OnboardingCard key={`onboarding-${o.plan_id}`} item={o} onContinue={onContinue} />- ))}- </div>- </section>- );-}-// A single passive monitoring signal as a compact rail row: headline +// optional body excerpt, click-to-discuss, and a small dismiss affordance.// Full ProposalCard is too wide for the rail, so this is the slimmed-down@@ -1920,16 +1687,6 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:).length;const peopleNeedReply = (today?.people ?? []).filter((p) => p.status === "needs_reply").length;const peopleOverdue = (today?.people ?? []).filter((p) => p.overdue).length;- // Only searches with an actionable signal earn an attention pill — mirrors the- // narrative's `notable_searches` filter. The Executive-search card still shows- // every active search; the pill is just the one-second "what needs a move" read.- const searchesNeedingAttention = (today?.talent ?? []).filter(- (t) =>- (t.offers_expiring_soon ?? 0) > 0 ||- t.offers_out > 0 ||- t.stalled_count > 0 ||- t.needs_screening > 0,- ).length;const statPills: StatPill[] = today? briefingStats({needsYou: mineProposals.length,@@ -1939,7 +1696,6 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:deptAtRisk: deptAtRiskCount,inFlight: inFlightCount,monitoring: monitoringProposals.length,- searchesNeedingAttention,}): [];@@ -2314,16 +2070,6 @@ export default function Briefing({ onContinue, showHeader = false, firstName }:Monitoring (live signals). Both render once; each is itsown Pulse card. */}<InFlightPanel inFlight={today.in_flight ?? []} id={SECTION_IDS.inFlight} />- <TalentPanel- talent={today.talent ?? []}- onContinue={onContinue}- id={SECTION_IDS.talent}- />- <OnboardingPanel- onboarding={today.onboarding ?? []}- onContinue={onContinue}- id={SECTION_IDS.onboarding}- /><PracticeClientsPanelclients={today.practice_clients ?? []}id={SECTION_IDS.practice}diff --git a/packages/ui/src/components/askoe/AskOEContext.tsx b/packages/ui/src/components/askoe/AskOEContext.tsxindex 81a284b7..bfe33086 100644--- a/packages/ui/src/components/askoe/AskOEContext.tsx+++ b/packages/ui/src/components/askoe/AskOEContext.tsx@@ -70,8 +70,6 @@ const ROUTE_GUIDE_MAP: Array<{ prefix: string; guideId: string; title: string }>// Routes with no guide section yet — still want a readable page title.const EXTRA_TITLES: Array<{ prefix: string; title: string }> = [- { prefix: "/talent", title: "Talent" },- { prefix: "/staff-onboarding", title: "Staff onboarding" },{ prefix: "/clients", title: "Client Companies" },{ prefix: "/architecture", title: "Architecture" },{ prefix: "/guide", title: "User Guide" },diff --git a/packages/ui/src/components/onboarding/meta.ts b/packages/ui/src/components/onboarding/meta.tsdeleted file mode 100644index 34cd02a1..00000000--- a/packages/ui/src/components/onboarding/meta.ts+++ /dev/null@@ -1,46 +0,0 @@-// Shared display metadata for the staff-onboarding surfaces (list page, detail-// page, and the briefing panel), so the labels/colours never drift apart —-// mirrors how the talent vertical centralises its stage metadata in-// `components/talent/stages.ts`.-import type { OnboardingPhase, OnboardingStatus } from "@/lib/api";--export const STATUS_META: Record<OnboardingStatus, { label: string; cls: string }> = {- draft: { label: "Draft", cls: "bg-slate-500/15 text-slate-300 border-slate-500/30" },- active: { label: "Active", cls: "bg-emerald-500/15 text-emerald-300 border-emerald-500/30" },- completed: { label: "Completed", cls: "bg-indigo-500/15 text-indigo-300 border-indigo-500/30" },- archived: { label: "Archived", cls: "bg-rose-500/15 text-rose-300 border-rose-500/30" },-};--export const PHASE_ORDER: OnboardingPhase[] = [- "pre_start",- "week_1",- "day_30",- "day_60",- "day_90",-];--export const PHASE_LABEL: Record<OnboardingPhase, string> = {- pre_start: "Pre-start",- week_1: "Week 1",- day_30: "Day 30",- day_60: "Day 60",- day_90: "Day 90",-};--// Sort weight for grouping plans on the list page (active first).-export const STATUS_ORDER: Record<OnboardingStatus, number> = {- active: 0,- draft: 1,- completed: 2,- archived: 3,-};--// Tolerant lookups for values that arrive as plain strings from the briefing-// digest (which types phase/status loosely).-export function phaseLabel(phase: string): string {- return PHASE_LABEL[phase as OnboardingPhase] ?? phase;-}--export function statusMeta(status: string): { label: string; cls: string } {- return STATUS_META[status as OnboardingStatus] ?? STATUS_META.draft;-}diff --git a/packages/ui/src/components/shell/AppShell.tsx b/packages/ui/src/components/shell/AppShell.tsxindex 4055a9d7..36c8152f 100644--- a/packages/ui/src/components/shell/AppShell.tsx+++ b/packages/ui/src/components/shell/AppShell.tsx@@ -35,10 +35,6 @@ const NAV_GROUPS = buildPrimaryNav();// Dynamic segments (slugs / ids) are rendered raw and truncated by CSS.const SEGMENT_LABELS: Record<string, string> = {today: "Today",- talent: "Talent",- candidates: "Candidate",- searches: "Searches",- engagements: "Engagement",review: "Review",proposals: "Proposals",people: "People",@@ -56,7 +52,6 @@ const SEGMENT_LABELS: Record<string, string> = {council: "Agent Council",architecture: "Architecture","company-profile": "Company profile",- "staff-onboarding": "Staff onboarding",demo: "Company Simulator",onboard: "Setup",watchlist: "Watch list",diff --git a/packages/ui/src/components/shell/navConfig.ts b/packages/ui/src/components/shell/navConfig.tsindex 87203971..321ad92d 100644--- a/packages/ui/src/components/shell/navConfig.ts+++ b/packages/ui/src/components/shell/navConfig.ts@@ -92,18 +92,6 @@ export function buildPrimaryNav({ isOnboarded = true, reviewBadge = 0 }: BuildOpdescription:"Your roster — who the Executive coordinates with and their approval scopes.",},- {- href: "/talent",- label: "Talent",- icon: "clipboard",- description: "Candidate searches and hiring engagements.",- },- {- href: "/staff-onboarding",- label: "Staff onboarding",- icon: "users",- description: "Onboarding plans for new hires — progress, tasks, and welcome briefs.",- },{href: isOnboarded ? "/company-profile" : "/onboard",label: isOnboarded ? "Company profile" : "Set up company",diff --git a/packages/ui/src/components/talent/CandidateCard.tsx b/packages/ui/src/components/talent/CandidateCard.tsxdeleted file mode 100644index f5f71926..00000000--- a/packages/ui/src/components/talent/CandidateCard.tsx+++ /dev/null@@ -1,37 +0,0 @@-import Link from "next/link";-import { Candidate } from "@/lib/api";-import { StageBadge } from "./StageBadge";-import { fitScoreColor } from "./stages";--/** Compact candidate card used on the pipeline board and engagement detail. */-export function CandidateCard({ candidate }: { candidate: Candidate }) {- const subtitle = [candidate.current_title, candidate.current_company]- .filter(Boolean)- .join(" · ");- return (- <Link- href={`/talent/candidates/${candidate.id}`}- className="block rounded-xl border border-line bg-surface-elevated hover:bg-surface-overlay transition-colors p-3 group"- >- <div className="flex items-start justify-between gap-2">- <div className="min-w-0">- <div className="text-sm font-semibold text-fg group-hover:text-indigo-300 truncate">- {candidate.full_name}- </div>- {subtitle && (- <div className="text-xs text-fg-muted truncate mt-0.5">{subtitle}</div>- )}- </div>- <div- className={`text-sm font-semibold tabular-nums ${fitScoreColor(candidate.fit_score)}`}- title="Fit score"- >- {candidate.fit_score ?? "—"}- </div>- </div>- <div className="mt-2">- <StageBadge stage={candidate.stage} />- </div>- </Link>- );-}diff --git a/packages/ui/src/components/talent/OfferPanel.tsx b/packages/ui/src/components/talent/OfferPanel.tsxdeleted file mode 100644index 48cb04e7..00000000--- a/packages/ui/src/components/talent/OfferPanel.tsx+++ /dev/null@@ -1,243 +0,0 @@-"use client";--import Link from "next/link";-import { useCallback, useEffect, useState } from "react";--import {- Candidate,- Offer,- OPEN_OFFER_STATUSES,- extendOffer,- listOffers,- recordOfferDecision,-} from "@/lib/api";-import { OFFER_STATUS_META } from "@/components/talent/stages";-import { workflowLink } from "@/components/talent/workflowLink";--/** Days-until-expiry copy for an extended offer; null when not applicable. */-function expiryCountdown(offer: Offer): { text: string; urgent: boolean } | null {- if (offer.status !== "extended" || !offer.expires_at) return null;- const ms = new Date(offer.expires_at).getTime() - Date.now();- if (Number.isNaN(ms)) return null;- const days = ms / 86_400_000;- if (days < 0) return { text: "expired — record a decision", urgent: true };- if (days < 1) return { text: "expires today", urgent: true };- const whole = Math.floor(days);- return { text: `expires in ${whole} day${whole === 1 ? "" : "s"}`, urgent: days <= 3 };-}--/** Offer lifecycle panel on the candidate detail page.- *- * Shows the candidate's current (or most recent) offer: status, terms, the- * persisted package from the offer_approval workflow, and the lifecycle- * actions — draft (workflow), mark extended, record the decision, start- * onboarding. OE never sends the offer to the candidate; the actions here- * record what the principal did. */-export function OfferPanel({- candidate,- onChanged,-}: {- candidate: Candidate;- /** Called after a lifecycle action so the parent can reload the candidate- * (accepting an offer moves them to `placed` server-side). */- onChanged?: () => void;-}) {- const [offers, setOffers] = useState<Offer[]>([]);- const [error, setError] = useState<string | null>(null);- const [notice, setNotice] = useState<string | null>(null);- const [busy, setBusy] = useState(false);- const [showPackage, setShowPackage] = useState(false);- const [expiresInDays, setExpiresInDays] = useState("7");-- const load = useCallback(() => {- listOffers({ candidateId: candidate.id })- .then(setOffers)- .catch((e) => setError(e instanceof Error ? e.message : "Failed to load offers"));- }, [candidate.id]);-- useEffect(() => {- load();- }, [load]);-- const open = offers.find((o) => OPEN_OFFER_STATUSES.includes(o.status));- // With no open offer, show the latest decided one as history.- const offer = open ?? offers[offers.length - 1];- const countdown = offer ? expiryCountdown(offer) : null;- const hireReady = candidate.stage === "placed" || offers.some((o) => o.status === "accepted");-- async function act(fn: () => Promise<{ warnings?: string[]; side_effects?: string[] }>) {- setBusy(true);- setError(null);- setNotice(null);- try {- const result = await fn();- const messages = [...(result.warnings ?? []), ...(result.side_effects ?? [])];- if (messages.length) setNotice(messages.join(" · "));- load();- onChanged?.();- } catch (e) {- setError(e instanceof Error ? e.message : "Offer action failed");- } finally {- setBusy(false);- }- }-- const meta = offer ? OFFER_STATUS_META[offer.status] : null;-- return (- <div className="mb-6">- <div className="text-xs font-semibold text-fg-muted uppercase tracking-wide mb-2">- Offer- </div>- <div className="rounded-xl border border-line bg-surface-elevated p-4 space-y-3">- {error && (- <div className="p-2 rounded-lg bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs">- {error}- </div>- )}- {notice && (- <div className="p-2 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-300 text-xs">- {notice}- </div>- )}-- {!offer ? (- <div className="flex items-center justify-between gap-3">- <p className="text-sm text-fg-subtle">- No offer yet. The workflow drafts terms against the comp band and- requests hiring sign-off.- </p>- <Link- href={workflowLink("offer_approval", { candidate_id: String(candidate.id) })}- className="shrink-0 px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-medium"- >- Draft offer- </Link>- </div>- ) : (- <>- <div className="flex items-center gap-2 flex-wrap">- {meta && (- <span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] font-medium ${meta.pill}`}>- {meta.label}- </span>- )}- {countdown && (- <span className={`text-xs ${countdown.urgent ? "text-rose-300" : "text-fg-muted"}`}>- {countdown.text}- </span>- )}- {offer.note && <span className="text-xs text-fg-subtle truncate">{offer.note}</span>}- </div>-- {offer.comp_summary && (- <p className="text-sm text-fg-muted whitespace-pre-wrap">{offer.comp_summary}</p>- )}-- {offer.package_md && (- <div>- <button- onClick={() => setShowPackage((v) => !v)}- className="text-xs text-indigo-300 hover:text-indigo-200"- >- {showPackage ? "Hide offer package" : "Show offer package"}- </button>- {showPackage && (- <pre className="mt-2 p-3 rounded-lg bg-surface-input border border-line text-xs text-fg-muted whitespace-pre-wrap overflow-x-auto">- {offer.package_md}- </pre>- )}- </div>- )}-- <div className="flex flex-wrap items-center gap-2">- {(offer.status === "draft" || offer.status === "pending_approval") && (- <>- <label className="flex items-center gap-1 text-xs text-fg-muted">- Expires in- <input- value={expiresInDays}- onChange={(e) => setExpiresInDays(e.target.value)}- className="w-12 px-2 py-1 rounded-lg bg-surface-input border border-line text-xs text-fg focus:outline-none focus:border-indigo-500"- />- days- </label>- <button- disabled={busy}- onClick={() =>- act(() =>- extendOffer(offer.id, {- expires_in_days: Math.max(1, Math.min(60, Number(expiresInDays) || 7)),- }),- )- }- className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-medium disabled:opacity-50"- title="You sent the offer yourself — this records it and schedules expiry reminders."- >- Mark extended- </button>- </>- )}- {offer.status === "extended" && (- <>- <button- disabled={busy}- onClick={() => act(() => recordOfferDecision(offer.id, "accepted"))}- className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-medium disabled:opacity-50"- >- Accepted- </button>- <button- disabled={busy}- onClick={() => act(() => recordOfferDecision(offer.id, "declined"))}- className="px-3 py-1.5 rounded-lg border border-rose-500/40 text-rose-300 hover:bg-rose-500/10 text-xs font-medium disabled:opacity-50"- >- Declined- </button>- <button- disabled={busy}- onClick={() => act(() => recordOfferDecision(offer.id, "expired"))}- className="px-3 py-1.5 rounded-lg border border-line text-fg-muted hover:bg-surface-overlay text-xs font-medium disabled:opacity-50"- >- Expired- </button>- </>- )}- {OPEN_OFFER_STATUSES.includes(offer.status) && (- <button- disabled={busy}- onClick={() => act(() => recordOfferDecision(offer.id, "rescinded"))}- className="px-3 py-1.5 rounded-lg border border-line text-fg-muted hover:bg-surface-overlay text-xs font-medium disabled:opacity-50"- >- Rescind- </button>- )}- {!open && !hireReady && (- <Link- href={workflowLink("offer_approval", { candidate_id: String(candidate.id) })}- className="px-3 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-medium"- >- Draft new offer- </Link>- )}- </div>- </>- )}-- {hireReady && (- <div className="flex items-center justify-between gap-3 pt-2 border-t border-line">- <p className="text-xs text-fg-muted">- Hired — add them to the roster and schedule 30/60/90 check-ins.- </p>- <Link- href={workflowLink("new_hire_onboarding", { candidate_id: String(candidate.id) })}- className="shrink-0 px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-medium"- >- Start onboarding- </Link>- </div>- )}- </div>- </div>- );-}diff --git a/packages/ui/src/components/talent/StageBadge.tsx b/packages/ui/src/components/talent/StageBadge.tsxdeleted file mode 100644index 2ba43f6b..00000000--- a/packages/ui/src/components/talent/StageBadge.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { CandidateStage, EngagementStatus } from "@/lib/api";-import { STAGE_META, STATUS_META } from "./stages";--export function StageBadge({ stage }: { stage: CandidateStage }) {- const meta = STAGE_META[stage] ?? { label: stage, pill: "bg-zinc-500/20 text-zinc-300 border-zinc-500/30" };- return (- <span- className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${meta.pill}`}- >- {meta.label}- </span>- );-}--export function StatusBadge({ status }: { status: EngagementStatus }) {- const meta = STATUS_META[status] ?? {- label: status,- pill: "bg-zinc-500/20 text-zinc-300 border-zinc-500/30",- };- return (- <span- className={`inline-block px-1.5 py-0.5 rounded border text-[10px] font-medium ${meta.pill}`}- >- {meta.label}- </span>- );-}diff --git a/packages/ui/src/components/talent/stages.ts b/packages/ui/src/components/talent/stages.tsdeleted file mode 100644index 42c5d6e7..00000000--- a/packages/ui/src/components/talent/stages.ts+++ /dev/null@@ -1,52 +0,0 @@-import { CandidateStage, EngagementStatus, OfferStatus } from "@/lib/api";--/** Display label + Tailwind pill classes for each candidate pipeline stage. */-export const STAGE_META: Record<CandidateStage, { label: string; pill: string }> = {- lead: { label: "Lead", pill: "bg-zinc-500/20 text-zinc-300 border-zinc-500/30" },- screened: { label: "Screened", pill: "bg-sky-500/20 text-sky-300 border-sky-500/30" },- interviewed: {- label: "Interviewed",- pill: "bg-indigo-500/20 text-indigo-300 border-indigo-500/30",- },- offer: { label: "Offer", pill: "bg-amber-500/20 text-amber-300 border-amber-500/30" },- placed: { label: "Placed", pill: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30" },- rejected: { label: "Rejected", pill: "bg-rose-500/20 text-rose-300 border-rose-500/30" },-};--/** The forward pipeline (excludes the `rejected` off-ramp), in board order. */-export const PIPELINE_STAGES: CandidateStage[] = [- "lead",- "screened",- "interviewed",- "offer",- "placed",-];--export const STATUS_META: Record<EngagementStatus, { label: string; pill: string }> = {- open: { label: "Open", pill: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30" },- on_hold: { label: "On hold", pill: "bg-amber-500/20 text-amber-300 border-amber-500/30" },- filled: { label: "Filled", pill: "bg-indigo-500/20 text-indigo-300 border-indigo-500/30" },- cancelled: { label: "Cancelled", pill: "bg-zinc-500/20 text-zinc-300 border-zinc-500/30" },-};--/** Display label + Tailwind pill classes for each offer status. */-export const OFFER_STATUS_META: Record<OfferStatus, { label: string; pill: string }> = {- draft: { label: "Draft", pill: "bg-zinc-500/20 text-zinc-300 border-zinc-500/30" },- pending_approval: {- label: "Pending sign-off",- pill: "bg-sky-500/20 text-sky-300 border-sky-500/30",- },- extended: { label: "Extended", pill: "bg-amber-500/20 text-amber-300 border-amber-500/30" },- accepted: { label: "Accepted", pill: "bg-emerald-500/20 text-emerald-300 border-emerald-500/30" },- declined: { label: "Declined", pill: "bg-rose-500/20 text-rose-300 border-rose-500/30" },- expired: { label: "Expired", pill: "bg-rose-500/20 text-rose-300 border-rose-500/30" },- rescinded: { label: "Rescinded", pill: "bg-zinc-500/20 text-zinc-300 border-zinc-500/30" },-};--/** Text color for a 0-100 fit score (or muted when unscored). */-export function fitScoreColor(score: number | null): string {- if (score == null) return "text-fg-subtle";- if (score >= 80) return "text-emerald-300";- if (score >= 60) return "text-amber-300";- return "text-rose-300";-}diff --git a/packages/ui/src/components/talent/workflowLink.ts b/packages/ui/src/components/talent/workflowLink.tsdeleted file mode 100644index 9ba1b842..00000000--- a/packages/ui/src/components/talent/workflowLink.ts+++ /dev/null@@ -1,14 +0,0 @@-/** Build a /jobs/{name} link with a base64url-encoded `?prefill=` payload.- *- * Mirrors the decoder in app/jobs/[name]/page.tsx (UTF-8 bytes → base64url).- * Values must be strings — the jobs form only applies string prefill values. */-export function workflowLink(name: string, prefill: Record<string, string>): string {- const json = JSON.stringify(prefill);- const bytes = new TextEncoder().encode(json);- let binary = "";- bytes.forEach((b) => {- binary += String.fromCharCode(b);- });- const b64 = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");- return `/jobs/${name}?prefill=${b64}`;-}diff --git a/packages/ui/src/lib/api.ts b/packages/ui/src/lib/api.tsindex 4398092a..69307a04 100644--- a/packages/ui/src/lib/api.ts+++ b/packages/ui/src/lib/api.ts@@ -2260,333 +2260,6 @@ export async function archivePerson(id: number): Promise<void> {if (!res.ok) throw new Error(`Failed to archive person: ${res.statusText}`);}-// ----------------------------------------------------------------------------// Talent / executive-search core (clients, engagements, candidates, matching)-// -----------------------------------------------------------------------------export const CANDIDATE_STAGES = [- "lead",- "screened",- "interviewed",- "offer",- "placed",- "rejected",-] as const;-export type CandidateStage = (typeof CANDIDATE_STAGES)[number];--export const ENGAGEMENT_STATUSES = ["open", "on_hold", "filled", "cancelled"] as const;-export type EngagementStatus = (typeof ENGAGEMENT_STATUSES)[number];--export interface Engagement {- id: number;- role_title: string;- department: string;- status: EngagementStatus;- location: string;- comp_band: string;- must_haves: string;- description: string;- archived: boolean;- created_at: string;- updated_at: string;-}--export interface EngagementCreate {- role_title: string;- department?: string;- status?: EngagementStatus;- location?: string;- comp_band?: string;- must_haves?: string;- description?: string;-}--export type EngagementPatch = Partial<EngagementCreate>;--export interface Candidate {- id: number;- engagement_id: number;- full_name: string;- current_title: string;- current_company: string;- location: string;- email: string | null;- linkedin_url: string | null;- source: string;- stage: CandidateStage;- fit_score: number | null;- screening_summary: string;- notes: string;- archived: boolean;- created_at: string;- updated_at: string;-}--export interface CandidateCreate {- engagement_id: number;- full_name: string;- current_title?: string;- current_company?: string;- location?: string;- email?: string | null;- linkedin_url?: string | null;- source?: string;- stage?: CandidateStage;- notes?: string;-}--export type CandidatePatch = Partial<Omit<CandidateCreate, "engagement_id" | "stage">>;--export interface CandidateMatch {- candidate_id: number;- engagement_id: number;- stage: string;- score: number;-}--// ---- Engagements ------export async function listEngagements(includeArchived = false): Promise<Engagement[]> {- const res = await fetch(- `${API_BASE}/engagements?include_archived=${includeArchived}`,- );- if (!res.ok) throw new Error(`Failed to load engagements: ${res.statusText}`);- return res.json();-}--export async function getEngagement(id: number): Promise<Engagement> {- const res = await fetch(`${API_BASE}/engagements/${id}`);- if (!res.ok) throw new Error(`Failed to load engagement: ${res.statusText}`);- return res.json();-}--export async function createEngagement(body: EngagementCreate): Promise<Engagement> {- const res = await fetch(`${API_BASE}/engagements`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });- if (!res.ok) throw new Error(`Failed to create engagement: ${res.statusText}`);- return res.json();-}--export async function updateEngagement(id: number, patch: EngagementPatch): Promise<Engagement> {- const res = await fetch(`${API_BASE}/engagements/${id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(patch),- });- if (!res.ok) throw new Error(`Failed to update engagement: ${res.statusText}`);- return res.json();-}--export async function archiveEngagement(id: number): Promise<void> {- const res = await fetch(`${API_BASE}/engagements/${id}/archive`, { method: "POST" });- if (!res.ok) throw new Error(`Failed to archive engagement: ${res.statusText}`);-}--// ---- Candidates ------export async function listCandidates(opts: {- engagementId?: number;- stage?: CandidateStage;- includeArchived?: boolean;-} = {}): Promise<Candidate[]> {- const params = new URLSearchParams({- include_archived: String(opts.includeArchived ?? false),- });- if (opts.engagementId != null) params.set("engagement_id", String(opts.engagementId));- if (opts.stage) params.set("stage", opts.stage);- const res = await fetch(`${API_BASE}/candidates?${params.toString()}`);- if (!res.ok) throw new Error(`Failed to load candidates: ${res.statusText}`);- return res.json();-}--export async function getCandidate(id: number): Promise<Candidate> {- const res = await fetch(`${API_BASE}/candidates/${id}`);- if (!res.ok) throw new Error(`Failed to load candidate: ${res.statusText}`);- return res.json();-}--export async function createCandidate(body: CandidateCreate): Promise<Candidate> {- const res = await fetch(`${API_BASE}/candidates`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });- if (!res.ok) throw new Error(`Failed to create candidate: ${res.statusText}`);- return res.json();-}--export async function updateCandidate(id: number, patch: CandidatePatch): Promise<Candidate> {- const res = await fetch(`${API_BASE}/candidates/${id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(patch),- });- if (!res.ok) throw new Error(`Failed to update candidate: ${res.statusText}`);- return res.json();-}--export async function setCandidateStage(id: number, stage: CandidateStage): Promise<Candidate> {- const res = await fetch(`${API_BASE}/candidates/${id}/stage`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ stage }),- });- if (!res.ok) throw new Error(`Failed to update candidate stage: ${res.statusText}`);- return res.json();-}--export async function archiveCandidate(id: number): Promise<void> {- const res = await fetch(`${API_BASE}/candidates/${id}/archive`, { method: "POST" });- if (!res.ok) throw new Error(`Failed to archive candidate: ${res.statusText}`);-}--// ---- Talent graph (matching) ------export async function matchCandidatesForEngagement(- engagementId: number,- limit = 10,-): Promise<CandidateMatch[]> {- const res = await fetch(`${API_BASE}/engagements/${engagementId}/matches?limit=${limit}`);- if (!res.ok) throw new Error(`Failed to load matches: ${res.statusText}`);- return res.json();-}--export async function similarCandidates(- candidateId: number,- limit = 5,-): Promise<CandidateMatch[]> {- const res = await fetch(`${API_BASE}/candidates/${candidateId}/similar?limit=${limit}`);- if (!res.ok) throw new Error(`Failed to load similar candidates: ${res.statusText}`);- return res.json();-}--export async function reindexTalent(): Promise<{ indexed: number }> {- const res = await fetch(`${API_BASE}/talent/reindex`, { method: "POST" });- if (!res.ok) throw new Error(`Failed to reindex talent: ${res.statusText}`);- return res.json();-}--// ---- Offers ------export const OFFER_STATUSES = [- "draft",- "pending_approval",- "extended",- "accepted",- "declined",- "expired",- "rescinded",-] as const;-export type OfferStatus = (typeof OFFER_STATUSES)[number];--// Statuses an offer can still move forward from (terminal ones are history).-export const OPEN_OFFER_STATUSES: readonly OfferStatus[] = [- "draft",- "pending_approval",- "extended",-];--export interface Offer {- id: number;- candidate_id: number;- engagement_id: number;- status: OfferStatus;- comp_summary: string;- package_md: string;- note: string;- expires_at: string | null;- extended_at: string;- decided_at: string;- approval_run_id: string;- approved_by_person_id: number | null;- nudge_action_ids: number[];- archived: boolean;- created_at: string;- updated_at: string;-}--// Mirrors the backend OfferActionResponse: the offer plus what else happened-// (nudges scheduled/cancelled, candidate placed, warnings about sign-off).-export interface OfferActionResponse {- offer: Offer;- approval_state: string;- nudges_scheduled: number;- cancelled_nudges: number;- side_effects: string[];- warnings: string[];-}--// Offer-lifecycle conflicts come back as 409s with a meaningful `detail`-// (e.g. "already has an open offer") — surface that, not just statusText.-async function offerError(res: Response, fallback: string): Promise<Error> {- try {- const body = await res.json();- if (body?.detail) return new Error(String(body.detail));- } catch {- // fall through to statusText- }- return new Error(`${fallback}: ${res.statusText}`);-}--export async function listOffers(opts: {- candidateId?: number;- engagementId?: number;- status?: OfferStatus;-} = {}): Promise<Offer[]> {- const params = new URLSearchParams();- if (opts.candidateId != null) params.set("candidate_id", String(opts.candidateId));- if (opts.engagementId != null) params.set("engagement_id", String(opts.engagementId));- if (opts.status) params.set("status", opts.status);- const qs = params.toString();- const res = await fetch(`${API_BASE}/offers${qs ? `?${qs}` : ""}`);- if (!res.ok) throw new Error(`Failed to load offers: ${res.statusText}`);- return res.json();-}--export async function createOffer(body: {- candidate_id: number;- comp_summary: string;- note?: string;-}): Promise<Offer> {- const res = await fetch(`${API_BASE}/offers`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });- if (!res.ok) throw await offerError(res, "Failed to create offer");- return res.json();-}--export async function extendOffer(- id: number,- body: { expires_at?: string; expires_in_days?: number; note?: string } = {},-): Promise<OfferActionResponse> {- const res = await fetch(`${API_BASE}/offers/${id}/extend`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });- if (!res.ok) throw await offerError(res, "Failed to extend offer");- return res.json();-}--export async function recordOfferDecision(- id: number,- decision: OfferStatus,- note?: string,-): Promise<OfferActionResponse> {- const res = await fetch(`${API_BASE}/offers/${id}/decision`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ decision, note }),- });- if (!res.ok) throw await offerError(res, "Failed to record offer decision");- return res.json();-}-// ---------------------------------------------------------------------------// Today (live dashboard) — was previously named "Morning Brief"// ---------------------------------------------------------------------------@@ -2725,39 +2398,6 @@ export interface AwaitingItem {overdue: boolean;}-// One active executive-search engagement, rolled up by pipeline stage for the-// briefing's "Executive Search" section. Mirrors the backend-// briefing.talent_digest.TalentBriefItem.-export interface TalentBriefItem {- engagement_id: number;- role_title: string;- department: string;- status: string;- location: string;- candidate_count: number;- // Maps a CandidateStage value ("lead", "screened", …) to its count.- stage_counts: Record<string, number>;- needs_screening: number;- offers_out: number;- // Extended offers within 72h of expiry (or already past it, undecided).- // Optional to keep older API builds + test mocks compiling.- offers_expiring_soon?: number;- stalled_count: number;-}--// Mirrors briefing.onboarding_digest.OnboardingBriefItem.-export interface OnboardingBriefItem {- plan_id: number;- full_name: string;- role: string;- status: OnboardingStatus;- current_phase: OnboardingPhase;- completion_pct: number;- open_tasks: number;- overdue_tasks: number;- days_to_start: number | null;-}-export interface Today {departments: DepartmentBriefItem[];people: PersonBriefItem[];@@ -2769,12 +2409,6 @@ export interface Today {// a reply from. Optional/default-empty for older API builds + test mocks.in_flight?: InFlightItem[];awaiting?: AwaitingItem[];- // Active executive searches rolled up by pipeline stage. Optional/default-- // empty for older API builds + test mocks.- talent?: TalentBriefItem[];- // New hires currently onboarding, rolled up by progress. Optional/default-- // empty for older API builds + test mocks.- onboarding?: OnboardingBriefItem[];// Parked client slots in multi-client practice mode (2+ slots). Empty for// single-company installs. Optional for older API builds + test mocks.practice_clients?: ClientCockpitCard[];@@ -3238,160 +2872,6 @@ export async function deleteClient(slug: string): Promise<void> {}}-// ----------------------------------------------------------------------------// Staff onboarding (plans / tasks / templates)-// -----------------------------------------------------------------------------export type OnboardingStatus = "draft" | "active" | "completed" | "archived";-export type OnboardingPhase =- | "pre_start"- | "week_1"- | "day_30"- | "day_60"- | "day_90";-export type OnboardingTaskStatus = "pending" | "in_progress" | "done" | "skipped";--export interface OnboardingTask {- id: number | null;- plan_id: number;- phase: OnboardingPhase;- title: string;- category: string;- owner_person_id: number | null;- due_date: string | null;- status: OnboardingTaskStatus;- completed_at: string | null;- completed_by_person_id: number | null;- notes: string;- sort_order: number;- created_at: string;- updated_at: string;-}--export interface OnboardingPlan {- id: number | null;- full_name: string;- role: string;- start_date: string;- person_id: number | null;- manager_person_id: number | null;- buddy_person_id: number | null;- template_name: string;- status: OnboardingStatus;- current_phase: OnboardingPhase;- brief_artifact: string;- reading_list: string[];- ramp_segments: string[];- ramp_next_index: number;- engagement_id: number | null;- candidate_id: number | null;- completion_pct: number;- archived: boolean;- created_at: string;- updated_at: string;- tasks: OnboardingTask[];-}--export interface OnboardingTemplate {- name: string;- title: string;- description: string;- department: string;- ramp_days: number;- checkin_cadence: string;- task_specs: Array<{- title: string;- category: string;- phase: OnboardingPhase;- owner_role: string;- due_offset_days: number;- }>;- brief_sections: string[];- is_active: boolean;- created_at: string;- updated_at: string;-}--export interface OnboardingPlanCreate {- full_name: string;- start_date: string;- role?: string;- template_name?: string;- person_id?: number | null;- manager_person_id?: number | null;- buddy_person_id?: number | null;-}--export async function listOnboardingPlans(- includeArchived = false,-): Promise<OnboardingPlan[]> {- const res = await fetch(- `${API_BASE}/onboarding-plans?include_archived=${includeArchived}`,- );- if (!res.ok) throw new Error(`Failed to load onboarding plans: ${res.statusText}`);- return res.json();-}--export async function getOnboardingPlan(id: number): Promise<OnboardingPlan> {- const res = await fetch(`${API_BASE}/onboarding-plans/${id}`);- if (!res.ok) throw new Error(`Failed to load onboarding plan: ${res.statusText}`);- return res.json();-}--export async function createOnboardingPlan(- body: OnboardingPlanCreate,-): Promise<OnboardingPlan> {- const res = await fetch(`${API_BASE}/onboarding-plans`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });- if (!res.ok) throw new Error(`Failed to create onboarding plan: ${res.statusText}`);- return res.json();-}--export async function setOnboardingTaskStatus(- taskId: number,- status: OnboardingTaskStatus,-): Promise<OnboardingTask> {- const res = await fetch(`${API_BASE}/onboarding-tasks/${taskId}/status`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ status }),- });- if (!res.ok) throw new Error(`Failed to update task: ${res.statusText}`);- return res.json();-}--export async function advanceOnboardingPlan(id: number): Promise<OnboardingPlan> {- const res = await fetch(`${API_BASE}/onboarding-plans/${id}/advance`, {- method: "POST",- });- if (!res.ok) throw new Error(`Failed to advance plan: ${res.statusText}`);- return res.json();-}--export async function activateOnboardingPlan(id: number): Promise<OnboardingPlan> {- const res = await fetch(`${API_BASE}/onboarding-plans/${id}/activate`, {- method: "POST",- });- if (!res.ok) throw new Error(`Failed to activate plan: ${res.statusText}`);- return res.json();-}--export async function archiveOnboardingPlan(id: number): Promise<void> {- const res = await fetch(`${API_BASE}/onboarding-plans/${id}/archive`, {- method: "POST",- });- if (!res.ok) throw new Error(`Failed to archive plan: ${res.statusText}`);-}--export async function listOnboardingTemplates(): Promise<OnboardingTemplate[]> {- const res = await fetch(`${API_BASE}/onboarding-templates`);- if (!res.ok) throw new Error(`Failed to load onboarding templates: ${res.statusText}`);- return res.json();-}-// Engagement intake: grounded AI draft of a real client from intake notes.export interface ClientDraftBundle {@@ -3473,7 +2953,6 @@ export interface ClientCockpitCard {overdue_actions?: number | null;awaiting_replies?: number | null;unread_alerts?: number | null;- onboarding_due_soon?: number | null;saved_at?: string | null;has_state: boolean;error: boolean;diff --git a/packages/ui/src/lib/practice.ts b/packages/ui/src/lib/practice.tsindex ed737e89..94118492 100644--- a/packages/ui/src/lib/practice.ts+++ b/packages/ui/src/lib/practice.ts@@ -30,7 +30,6 @@ export function clientCountsSummary(c: ClientCockpitCard): string {c.overdue_actions ? `${c.overdue_actions} overdue` : null,c.awaiting_replies ? `${c.awaiting_replies} awaiting reply` : null,c.unread_alerts ? `${c.unread_alerts} alerts` : null,- c.onboarding_due_soon ? `${c.onboarding_due_soon} onboarding due` : null,].filter(Boolean).join(" · ") || "all quiet";