AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(backend): launch roster with real workflow bundles (#14030)
Abhimanyu Yadavbb40b51071d1
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.pyindex bed8843ec7..721a3329b5 100644--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py@@ -1,5 +1,6 @@import asyncioimport uuid+from test import load_store_agents as store_assetsfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, patch@@ -10,18 +11,41 @@ import pytestimport backend.api.features.store.model as store_modelfrom backend.api.features.experts import experts_db, scheduling, seed-from backend.api.features.experts.models import ExpertSoulFieldsPatch, ExpertSoulUpdate+from backend.api.features.experts.models import (+ ExpertSoulFieldsPatch,+ ExpertSoulUpdate,+ HireResult,+)from backend.api.features.library import db as library_dbfrom backend.api.features.library import model as library_modelfrom backend.api.model import CreateGraphfrom backend.blocks.io import AgentInputBlockfrom backend.copilot.model import create_chat_session+from backend.data.db import prisma as db_clientfrom backend.data.graph import Graph, Node+from backend.data.model import Userfrom backend.data.user import get_or_create_userfrom backend.usecases.sample import create_test_userfrom backend.util.exceptions import ExpertRunPausedErrorfrom backend.util.test import SpinTestServer+EXPECTED_ROSTER_PRELOAD_SLUGS = {+ "ai-webpage-copy-improver",+ "automated-blog-writer",+ "automated-support-ai",+ "business-ownerceo-finder",+ "email-address-finder",+ "lead-finder-local-businesses",+ "linkedin-post-generator",+ "personalized-morning-coffee-newsletter",+ "smart-meeting-brief",+}+EXPECTED_ROSTER_SCHEDULE = (+ "Frankie",+ "personalized-morning-coffee-newsletter",+ "40 7 * * *",+)+@pytest.fixture(scope="session", autouse=True)def mock_embedding_functions():@@ -111,6 +135,74 @@ async def _seed_store_listing(server: SpinTestServer) -> str:return slv_id+async def _load_roster_store_assets() -> dict[str, str]:+ """Load the checked-in production store assets (StoreAgent_rows.csv plus+ the matching graph JSONs) for every ROSTER preload slug into the test DB,+ published under the official creator — the exact data ``load-store-agents``+ deploys. Idempotent: the loaders skip rows that already exist.++ Returns slug -> the CSV's StoreListingVersion id, the version a hire is+ expected to install. A ROSTER slug with no checked-in asset fails here+ instead of being silently substituted by a synthetic listing.+ """+ await store_assets.create_user_and_profile(db_client)+ metadata = await store_assets.load_csv_metadata()+ by_slug = {m["slug"]: m for m in metadata.values() if m["is_available"]}+ expected: dict[str, str] = {}+ for slug in EXPECTED_ROSTER_PRELOAD_SLUGS:+ assert slug in by_slug, f"Expected roster slug '{slug}' has no store asset"+ meta = by_slug[slug]+ version_id = meta["store_listing_version_id"]+ agent_json = await store_assets.load_agent_json(+ store_assets.AGENTS_DIR / f"agent_{version_id}.json"+ )+ graph_id, graph_version = await store_assets.create_agent_graph(+ db_client, agent_json, set()+ )+ await store_assets.create_store_listing(+ db_client, graph_id, graph_version, meta+ )+ expected[slug] = version_id+ return expected+++async def _hire_roster_and_assert_preloads(+ hire_user: User,+ templates: dict[str, prisma.models.Expert],+ expected: dict[str, str],+) -> dict[str, HireResult]:+ scheduler = AsyncMock()+ scheduler.add_execution_schedule = AsyncMock(+ return_value=SimpleNamespace(id="sched-1")+ )+ results: dict[str, HireResult] = {}+ with patch.object(scheduling, "get_scheduler_client", return_value=scheduler):+ for entry in seed.ROSTER:+ result = await experts_db.hire_expert(+ hire_user.id, templates[entry["name"]].id, None+ )+ assert result.failed_preloads == []+ assert {w.store_listing_version_id for w in result.expert.workflows} == {+ expected[p["slug"]] for p in entry["preloads"]+ }+ results[entry["name"]] = result+ return results+++async def _transfer_listing_to_official_creator(slv_id: str) -> None:+ """Re-own an ad-hoc test listing to the official creator so seed slug+ resolution (creator-scoped) can see it."""+ await store_assets.create_user_and_profile(db_client)+ listing = await prisma.models.StoreListing.prisma().find_first(+ where={"activeVersionId": slv_id}+ )+ assert listing is not None+ await prisma.models.StoreListing.prisma().update(+ where={"id": listing.id},+ data={"owningUserId": store_assets.AUTOGPT_USER_ID},+ )++async def _seed_template(name: str,preload_listings: list[str],@@ -638,6 +730,7 @@ async def test_enforce_budget_pauses_blocks_and_resumes(@pytest.mark.asyncio(loop_scope="session")async def test_seed_roster_round_trip(server: SpinTestServer):+ await _load_roster_store_assets()first_ids = await seed.seed_roster()assert len(first_ids) == 3@@ -658,6 +751,403 @@ async def test_seed_roster_round_trip(server: SpinTestServer):assert len(seeded_after) == 3[email protected](loop_scope="session")+async def test_seed_roster_rejects_missing_preloads_before_template_mutation(+ monkeypatch: pytest.MonkeyPatch,+):+ resolve = AsyncMock(return_value=None)+ upsert = AsyncMock()+ monkeypatch.setattr(seed, "_resolve_active_version_id", resolve)+ monkeypatch.setattr(seed, "_upsert_template", upsert)++ with pytest.raises(RuntimeError, match="Load marketplace store assets"):+ await seed.seed_roster()++ assert resolve.await_count == len(EXPECTED_ROSTER_PRELOAD_SLUGS)+ upsert.assert_not_awaited()+++def test_roster_assigns_two_to_four_workflows_with_one_scheduled_cadence():+ """Launch invariant, checked without a DB: every persona ships 2-4+ preloads, and exactly one scheduled cadence exists across the whole+ roster (Frankie's daily ops digest), so schedule attribution has a+ single unambiguous real case."""+ for entry in seed.ROSTER:+ assert 2 <= len(entry["preloads"]) <= 4, entry["name"]++ assert {+ preload["slug"] for entry in seed.ROSTER for preload in entry["preloads"]+ } == EXPECTED_ROSTER_PRELOAD_SLUGS+ scheduled = [+ (entry["name"], preload["slug"], preload["cron"])+ for entry in seed.ROSTER+ for preload in entry["preloads"]+ if preload["cron"] is not None+ ]+ assert scheduled == [EXPECTED_ROSTER_SCHEDULE]++[email protected](loop_scope="session")+async def test_roster_preloads_resolve_and_hire_installs_cleanly(+ server: SpinTestServer,+):+ """Launch acceptance gate against the real checked-in store assets: every+ ROSTER preload slug resolves to the exact StoreListingVersion the CSV+ ships, each persona's template carries exactly its preloads, and hiring+ installs all of them with zero failed preloads. A fictional or renamed+ ROSTER slug fails the asset lookup instead of being papered over by a+ synthetic listing."""+ expected = await _load_roster_store_assets()++ for slug, version_id in expected.items():+ assert await seed._resolve_active_version_id(slug) == version_id, slug++ template_ids = await seed.seed_roster()+ templates = {+ t.name: t for t in await experts_db.list_templates() if t.id in template_ids+ }+ for entry in seed.ROSTER:+ expected_versions = {expected[p["slug"]] for p in entry["preloads"]}+ assert len(expected_versions) == len(entry["preloads"])+ assert {+ w.store_listing_version_id for w in templates[entry["name"]].workflows+ } == expected_versions++ # A fresh user per run: a reused fixture user would make hire_expert+ # short-circuit to a previous run's copy and skip _install_preloads.+ hire_user = await _create_seed_user()+ results = await _hire_roster_and_assert_preloads(hire_user, templates, expected)++ frankie_crons = [+ w.schedule_cron for w in results["Frankie"].expert.workflows if w.schedule_cron+ ]+ assert frankie_crons == ["40 7 * * *"]+ for name in ("Maria", "Max"):+ assert all(w.schedule_cron is None for w in results[name].expert.workflows)++[email protected](loop_scope="session")+async def test_roster_slug_resolution_rejects_impostor_creator(+ server: SpinTestServer,+):+ expected = await _load_roster_store_assets()+ slug = "automated-blog-writer"+ impostor_version_id = await _seed_store_listing(server)+ impostor_listing = await prisma.models.StoreListing.prisma().find_first(+ where={"activeVersionId": impostor_version_id}+ )+ assert impostor_listing is not None+ await prisma.models.StoreListing.prisma().update(+ where={"id": impostor_listing.id}, data={"slug": slug}+ )++ resolved = await seed._resolve_active_version_id(slug)++ assert resolved == expected[slug]+ assert resolved != impostor_version_id++[email protected](loop_scope="session")+async def test_seed_clears_removed_cadences_on_hired_copies(server: SpinTestServer):+ """Hires made before the single-cadence decision still carry the removed+ template cadences with live scheduler jobs; the seed's migration must+ delete the job (owner-scoped) and clear the row, while a user-customized+ cadence on the same listing is left alone."""+ expected = await _load_roster_store_assets()+ removed_slug, removed_cron = seed.REMOVED_TEMPLATE_CADENCES[0]+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(owner.id, template.id, None)+ legacy = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired.expert.id,+ "storeListingVersionId": expected[removed_slug],+ "scheduleCron": removed_cron,+ "scheduleId": "sched-legacy",+ }+ )+ custom = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired.expert.id,+ "storeListingVersionId": expected["lead-finder-local-businesses"],+ "scheduleCron": "0 12 * * 1",+ "scheduleId": "sched-custom",+ }+ )+ sched = AsyncMock()+ sched.get_execution_schedules = AsyncMock(+ return_value=[+ SimpleNamespace(id="sched-legacy"),+ SimpleNamespace(id="sched-custom"),+ ]+ )+ sched.delete_schedule = AsyncMock()+ with patch.object(seed, "get_scheduler_client", return_value=sched):+ assert await seed._clear_removed_cadences() >= 1++ sched.delete_schedule.assert_any_await("sched-legacy", user_id=owner.id)+ deleted_ids = [c.args[0] for c in sched.delete_schedule.await_args_list]+ assert "sched-custom" not in deleted_ids+ legacy_after = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": legacy.id}+ )+ assert legacy_after is not None+ assert legacy_after.scheduleId is None+ assert legacy_after.scheduleCron is None+ custom_after = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": custom.id}+ )+ assert custom_after is not None+ assert custom_after.scheduleId == "sched-custom"+ assert custom_after.scheduleCron == "0 12 * * 1"++[email protected](loop_scope="session")+async def test_seed_clears_removed_cadences_without_live_jobs(server: SpinTestServer):+ expected = await _load_roster_store_assets()+ removed_slug, removed_cron = seed.REMOVED_TEMPLATE_CADENCES[0]+ template = await _seed_template(name="Maria", preload_listings=[])+ owner_without_id = await _create_seed_user()+ owner_with_missing_job = await _create_seed_user()+ hired_without_id = await experts_db.hire_expert(+ owner_without_id.id, template.id, None+ )+ hired_with_missing_job = await experts_db.hire_expert(+ owner_with_missing_job.id, template.id, None+ )+ without_id = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired_without_id.expert.id,+ "storeListingVersionId": expected[removed_slug],+ "scheduleCron": removed_cron,+ }+ )+ with_missing_job = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired_with_missing_job.expert.id,+ "storeListingVersionId": expected[removed_slug],+ "scheduleCron": removed_cron,+ "scheduleId": "already-gone",+ }+ )+ scheduler = AsyncMock()+ scheduler.get_execution_schedules = AsyncMock(return_value=[])+ scheduler.delete_schedule = AsyncMock()++ with patch.object(seed, "get_scheduler_client", return_value=scheduler):+ assert await seed._clear_removed_cadences() >= 2++ scheduler.get_execution_schedules.assert_awaited_once_with(+ user_id=owner_with_missing_job.id, kind="graph"+ )+ scheduler.delete_schedule.assert_not_awaited()+ for workflow_id in (without_id.id, with_missing_job.id):+ row = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": workflow_id}+ )+ assert row is not None+ assert row.scheduleId is None+ assert row.scheduleCron is None++[email protected](loop_scope="session")+async def test_seed_clears_removed_cadence_after_listing_version_rotation(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):+ previous_version_id = await _seed_store_listing(server)+ await _transfer_listing_to_official_creator(previous_version_id)+ listing = await prisma.models.StoreListing.prisma().find_first(+ where={"activeVersionId": previous_version_id}+ )+ previous = await prisma.models.StoreListingVersion.prisma().find_unique(+ where={"id": previous_version_id}+ )+ assert listing is not None+ assert previous is not None++ current = await prisma.models.StoreListingVersion.prisma().create(+ data={+ "version": previous.version + 1,+ "agentGraphId": previous.agentGraphId,+ "agentGraphVersion": previous.agentGraphVersion,+ "name": previous.name,+ "subHeading": previous.subHeading,+ "imageUrls": previous.imageUrls,+ "description": previous.description,+ "categories": previous.categories,+ "submissionStatus": prisma.enums.SubmissionStatus.APPROVED,+ "storeListingId": listing.id,+ }+ )+ await prisma.models.StoreListing.prisma().update(+ where={"id": listing.id}, data={"activeVersionId": current.id}+ )++ removed_cron = "0 9 * * 1"+ monkeypatch.setattr(+ seed, "REMOVED_TEMPLATE_CADENCES", [(listing.slug, removed_cron)]+ )+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(owner.id, template.id, None)+ legacy = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired.expert.id,+ "storeListingVersionId": previous_version_id,+ "scheduleCron": removed_cron,+ "scheduleId": "sched-previous-version",+ }+ )+ sched = AsyncMock()+ sched.get_execution_schedules = AsyncMock(+ return_value=[SimpleNamespace(id="sched-previous-version")]+ )+ sched.delete_schedule = AsyncMock()++ with patch.object(seed, "get_scheduler_client", return_value=sched):+ assert await seed._clear_removed_cadences() == 1++ sched.delete_schedule.assert_awaited_once_with(+ "sched-previous-version", user_id=owner.id+ )+ legacy_after = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": legacy.id}+ )+ assert legacy_after is not None+ assert legacy_after.scheduleId is None+ assert legacy_after.scheduleCron is None++[email protected](loop_scope="session")+async def test_seed_clears_removed_cadence_on_soft_deleted_listing(+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch+):+ """Soft-deleting the listing must not strand the schedule: the hired copy+ still fires the removed cron, so the migration has to reach it even though+ the listing is gone from the marketplace."""+ version_id = await _seed_store_listing(server)+ await _transfer_listing_to_official_creator(version_id)+ listing = await prisma.models.StoreListing.prisma().find_first(+ where={"activeVersionId": version_id}+ )+ assert listing is not None+ await prisma.models.StoreListing.prisma().update(+ where={"id": listing.id}, data={"isDeleted": True}+ )++ removed_cron = "0 9 * * 1"+ monkeypatch.setattr(+ seed, "REMOVED_TEMPLATE_CADENCES", [(listing.slug, removed_cron)]+ )+ owner = await _create_seed_user()+ template = await _seed_template(name="Maria", preload_listings=[])+ hired = await experts_db.hire_expert(owner.id, template.id, None)+ legacy = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired.expert.id,+ "storeListingVersionId": version_id,+ "scheduleCron": removed_cron,+ "scheduleId": "sched-soft-deleted-listing",+ }+ )+ sched = AsyncMock()+ sched.get_execution_schedules = AsyncMock(+ return_value=[SimpleNamespace(id="sched-soft-deleted-listing")]+ )+ sched.delete_schedule = AsyncMock()++ with patch.object(seed, "get_scheduler_client", return_value=sched):+ assert await seed._clear_removed_cadences() == 1++ sched.delete_schedule.assert_awaited_once_with(+ "sched-soft-deleted-listing", user_id=owner.id+ )+ legacy_after = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": legacy.id}+ )+ assert legacy_after is not None+ assert legacy_after.scheduleId is None+ assert legacy_after.scheduleCron is None++[email protected](loop_scope="session")+async def test_delete_live_schedule_updates_owner_cache():+ scheduler = AsyncMock()+ scheduler.get_execution_schedules = AsyncMock(+ return_value=[SimpleNamespace(id="sched-shared")]+ )+ scheduler.delete_schedule = AsyncMock()+ live_by_owner: dict[str, set[str]] = {}++ with patch.object(seed, "get_scheduler_client", return_value=scheduler):+ assert await seed._delete_live_schedule(+ "owner-1", "sched-shared", live_by_owner+ )+ assert await seed._delete_live_schedule(+ "owner-1", "sched-shared", live_by_owner+ )++ scheduler.get_execution_schedules.assert_awaited_once_with(+ user_id="owner-1", kind="graph"+ )+ scheduler.delete_schedule.assert_awaited_once_with(+ "sched-shared", user_id="owner-1"+ )+ assert live_by_owner == {"owner-1": set()}++[email protected](loop_scope="session")+async def test_seed_preserves_cadence_when_schedule_delete_fails(+ server: SpinTestServer,+):+ """A scheduler failure must keep scheduleId/scheduleCron on the hired row+ so the next seed run retries — clearing first would leave the live job+ firing with nothing pointing at it. The retry then clears the row."""+ expected = await _load_roster_store_assets()+ removed_slug, removed_cron = seed.REMOVED_TEMPLATE_CADENCES[0]+ owner = await _create_seed_user()+ template = await _seed_template(name="Frankie", preload_listings=[])+ hired = await experts_db.hire_expert(owner.id, template.id, None)+ row = await prisma.models.ExpertWorkflow.prisma().create(+ data={+ "expertId": hired.expert.id,+ "storeListingVersionId": expected[removed_slug],+ "scheduleCron": removed_cron,+ "scheduleId": "sched-stuck",+ }+ )+ broken = AsyncMock()+ broken.get_execution_schedules = AsyncMock(+ return_value=[SimpleNamespace(id="sched-stuck")]+ )+ broken.delete_schedule = AsyncMock(side_effect=RuntimeError("scheduler down"))+ with patch.object(seed, "get_scheduler_client", return_value=broken):+ await seed._clear_removed_cadences()++ stuck = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": row.id}+ )+ assert stuck is not None+ assert stuck.scheduleId == "sched-stuck"+ assert stuck.scheduleCron == removed_cron++ healed = AsyncMock()+ healed.get_execution_schedules = AsyncMock(+ return_value=[SimpleNamespace(id="sched-stuck")]+ )+ healed.delete_schedule = AsyncMock()+ with patch.object(seed, "get_scheduler_client", return_value=healed):+ await seed._clear_removed_cadences()++ healed.delete_schedule.assert_any_await("sched-stuck", user_id=owner.id)+ cleared = await prisma.models.ExpertWorkflow.prisma().find_unique(+ where={"id": row.id}+ )+ assert cleared is not None+ assert cleared.scheduleId is None+ assert cleared.scheduleCron is None++@pytest.mark.asyncio(loop_scope="session")async def test_list_experts_includes_last_run(server: SpinTestServer, test_user):"""The /team card needs last-run status: the latest expert-attributed@@ -696,6 +1186,9 @@ async def test_sync_preloads_updates_template_cadence(server: SpinTestServer):"""Re-seeding must propagate roster cadence changes onto existingtemplate preload rows — the old sync was create-only."""slv_id = await _seed_store_listing(server)+ # Resolution is creator-scoped, so the ad-hoc listing must belong to the+ # official creator for _sync_preloads to see it.+ await _transfer_listing_to_official_creator(slv_id)listing = await prisma.models.StoreListing.prisma().find_first(where={"activeVersionId": slv_id})@@ -761,6 +1254,7 @@ async def test_seed_backfills_presentation_fields_onto_hired_copies(refreshed = await experts_db.get_expert(test_user.id, hired.expert.id)assert refreshed is not Noneassert refreshed.avatar_url == "/experts/maria.svg"+ assert refreshed.tagline == "Refreshed tagline"assert refreshed.bio == "Maria is a senior marketing strategist."assert refreshed.skills == ["Content strategy", "SEO writing"]# A user's rename of their own hire survives the refresh.diff --git a/autogpt_platform/backend/backend/api/features/experts/seed.py b/autogpt_platform/backend/backend/api/features/experts/seed.pyindex a53cd1826a..5acd6ea59a 100644--- a/autogpt_platform/backend/backend/api/features/experts/seed.py+++ b/autogpt_platform/backend/backend/api/features/experts/seed.py@@ -4,22 +4,31 @@ Run with: poetry run python -m backend.api.features.experts.seedUpserts the three roster templates (Maria, Max, Frankie) by template name,so repeated runs keep the same template ids. Preload workflows are resolved-from store listing slugs; missing listings are logged and skipped, never-fatal. Each upsert also refreshes the presentation fields (avatar, bio,-skills) on experts already hired from that template, so roster changes reach-existing users and not just new hires.+from official store listing slugs; all listings are validated before any+template is mutated. Each upsert also refreshes the presentation fields+(avatar, tagline, bio, skills) on experts already hired from that template,+so roster changes reach existing users and not just new hires."""import asyncioimport logging+from collections.abc import Mappingfrom typing import TypedDictimport prisma.modelsfrom backend.data import db as database+from backend.util.clients import get_scheduler_clientlogger = logging.getLogger(__name__)+# StoreListing slugs are only unique per owner, so slug resolution must be+# scoped to the official creator — otherwise another creator publishing the+# same slug could get their listing preloaded. Matches the username the+# checked-in marketplace assets (backend/agents) publish under and the live+# marketplace creator of the roster listings.+OFFICIAL_CREATOR_USERNAME = "autogpt"+class PreloadSeed(TypedDict):slug: str@@ -47,16 +56,14 @@ ROSTER: list[RosterEntry] = [{"name": "Maria","role": "Marketing",- "tagline": "Turns your product story into campaigns that land.",+ "tagline": "Writes your LinkedIn posts, SEO articles, and webpage copy.","avatar_url": "/experts/maria.svg",- "bio": """Maria is a senior marketing strategist with fifteen years across B2B SaaS and consumer brands. She thinks positioning first: before any tactic, she wants to know who the customer is, what keeps them up at night, and why they would choose your product over doing nothing. She writes clear, confident prose and distrusts jargon — if a headline could sit on a competitor's site, she rewrites it.--Day to day she covers content strategy, social copy, email campaigns, and SEO-aware long-form writing, always tied to a measurable goal: signups, demos booked, or rankings improved. Give her a rough idea and she returns an outline, three headline options, and a full draft.""",+ "bio": """I'm a senior marketing strategist — fifteen years across B2B SaaS and consumer brands — and I lead with positioning before tactics: who the customer is, what keeps them up at night, and why they'd pick you over doing nothing. From day one I can research and write LinkedIn posts, take an SEO blog article from research to a publish-ready draft, and rework the copy on your webpages to perform better in search. Everything ships in clear, confident prose with the jargon stripped out.""","skills": ["Content strategy","Social copy",- "Email campaigns","SEO writing",+ "Web copy","Positioning",],"identity": """You are Maria, a senior marketing strategist with fifteen years of experience across B2B SaaS and consumer brands. You think in terms of positioning first: before any tactic, you want to know who the customer is, what keeps them up at night, and why they would choose this product over doing nothing. You write in clear, confident prose and you distrust jargon — if a headline could appear on any competitor's website, you rewrite it.@@ -68,23 +75,20 @@ You are direct about trade-offs. If a campaign idea is clever but off-brand, you"boundaries": "Never invent customer claims or statistics. Ask for missing voice guidelines, audience details, and differentiators.","preloads": [{"slug": "linkedin-post-generator", "cron": None},- # Weekly blog draft, Monday 9:00 — Maria's recurring deliverable.- {"slug": "automated-blog-writer", "cron": "0 9 * * 1"},+ {"slug": "automated-blog-writer", "cron": None},{"slug": "ai-webpage-copy-improver", "cron": None},],},{"name": "Max","role": "Sales",- "tagline": "Finds the right prospects and opens the right conversations.",+ "tagline": "Finds your leads, their decision-makers, and their contact details.","avatar_url": "/experts/max.svg",- "bio": """Max is a sales development expert who has built outbound pipelines for startups and mid-market companies. He believes pipeline problems are usually targeting problems in disguise, so he starts by sharpening the ideal customer profile: industry, size, trigger events, and the specific pain your product removes. Volume without fit is noise, and he says so plainly.--His core work is prospecting and outreach: researching accounts, surfacing decision makers, and drafting first-touch messages that reference something real about the prospect. He keeps outreach short, specific, and honest — and helps separate genuine buying signals from curiosity.""",+ "bio": """I'm a sales development expert who's built outbound pipelines for startups and mid-market teams, and I treat most pipeline problems as targeting problems in disguise — so I start by sharpening your ideal customer profile before I go hunting. From day one I can pull lists of businesses that fit that profile, surface the owner or decision-maker behind a company, and track down a contact's email address. Volume without fit is noise, and I say so plainly.""","skills": ["Prospecting","Lead qualification",- "Cold outreach",+ "Contact research","ICP targeting","Account research",],@@ -96,8 +100,7 @@ You are rigorous about data quality. You flag when contact information looks sta"voice_preferences": "Short, specific, honest, and plain-spoken about trade-offs.","boundaries": "Never fabricate prospect details. Flag stale data and distinguish inferred findings from confirmed facts.","preloads": [- # Fresh lead batch every Monday morning before outreach starts.- {"slug": "lead-finder-local-businesses", "cron": "0 8 * * 1"},+ {"slug": "lead-finder-local-businesses", "cron": None},{"slug": "business-ownerceo-finder", "cron": None},{"slug": "email-address-finder", "cron": None},],@@ -105,11 +108,9 @@ You are rigorous about data quality. You flag when contact information looks sta{"name": "Frankie","role": "Ops",- "tagline": "Keeps the shop running: meetings, follow-ups, and busywork handled.",+ "tagline": "Starts your day briefed: meeting prep, support email, and a morning digest.","avatar_url": "/experts/frankie.svg",- "bio": """Frankie is an operations specialist who has run the back office for fast-growing teams. Their job is to make the routine disappear: meeting prep, follow-up emails, support triage, scheduling, and the hundred small tasks that eat a founder's day. Systematic by temperament, Frankie would rather build a repeatable checklist than firefight the same problem twice.--Before any meeting Frankie assembles a brief; afterwards, notes become action items with owners and dates. Frankie never promises dates, refunds, or policy exceptions on your behalf — everything sensitive is drafted and flagged for a human to approve.""",+ "bio": """I'm an operations specialist who's run the back office for fast-growing teams, and my job is to keep you ahead of the routine instead of buried in it. From day one I can brief you before your business meetings; after you connect the required inbox sources, I can draft support replies and land a personalized morning digest on your desk at 7:40 in your timezone. I'm conservative about commitments: I never promise a date, refund, or policy exception on your behalf — I draft it and flag it for you to approve.""","skills": ["Meeting prep","Follow-ups",@@ -125,25 +126,125 @@ You are conservative about commitments. You never promise a delivery date, refun"voice_preferences": "Tidy and scannable, with a one-line summary, clear bullets, owners, and explicit deadlines.","boundaries": "Never promise dates, refunds, or policy exceptions. Draft sensitive commitments and flag them for human approval.","preloads": [- # Weekday meeting brief before the workday starts.- {"slug": "smart-meeting-brief", "cron": "0 7 * * 1-5"},+ {"slug": "smart-meeting-brief", "cron": None},{"slug": "automated-support-ai", "cron": None},- # Daily 7:40am — the roster's flagship morning-briefing cadence.+ # Daily 7:40am ops digest — the roster's single scheduled cadence,+ # so expert schedule attribution has exactly one real case.{"slug": "personalized-morning-coffee-newsletter", "cron": "40 7 * * *"},],},]+# Cadences dropped when the roster consolidated on a single scheduled+# workflow (Frankie's daily digest). _sync_preloads only reaches template+# rows, so hires made before the change would keep firing these forever —+# every seed run retries this cleanup until no hired copy still carries the+# old template-managed cadence. Rows whose cron a user changed no longer+# match and are deliberately left alone.+REMOVED_TEMPLATE_CADENCES: list[tuple[str, str]] = [+ ("automated-blog-writer", "0 9 * * 1"),+ ("lead-finder-local-businesses", "0 8 * * 1"),+ ("smart-meeting-brief", "0 7 * * 1-5"),+]++async def _resolve_active_version_id(slug: str) -> str | None:+ # (owningUserId, slug) is the listing's uniqueness, and the username is+ # unique, so this match is deterministic: at most one listing.listing = await prisma.models.StoreListing.prisma().find_first(- where={"slug": slug, "isDeleted": False}+ where={+ "slug": slug,+ "isDeleted": False,+ "CreatorProfile": {"is": {"username": OFFICIAL_CREATOR_USERNAME}},+ })if listing is None:return Nonereturn listing.activeVersionId+async def _clear_removed_cadences() -> int:+ """Migrate hired copies off cadences the roster no longer ships.++ Deletes each hired copy's scheduler job by owner + scheduleId and clears+ the row only once the job is confirmed gone (deleted now, or already+ absent) — a scheduler failure preserves scheduleId/scheduleCron so the+ next seed run retries, mirroring ``detach_expert_triggers``.+ """+ cleared = 0+ live_by_owner: dict[str, set[str]] = {}+ for slug, old_cron in REMOVED_TEMPLATE_CADENCES:+ rows = await prisma.models.ExpertWorkflow.prisma().find_many(+ where={+ "StoreListingVersion": {+ "is": {+ "StoreListing": {+ "is": {+ "slug": slug,+ # No isDeleted filter: soft-deleting the listing+ # does not stop the hired copy's schedule, so+ # the migration must still reach those rows.+ "CreatorProfile": {+ "is": {+ "username": OFFICIAL_CREATOR_USERNAME,+ }+ },+ }+ }+ }+ },+ "scheduleCron": old_cron,+ "Expert": {"is": {"isTemplate": False}},+ },+ include={"Expert": True},+ )+ for row in rows:+ owner = row.Expert.ownerUserId if row.Expert else None+ if owner is None:+ continue+ if row.scheduleId is not None and not await _delete_live_schedule(+ owner, row.scheduleId, live_by_owner+ ):+ continue+ await prisma.models.ExpertWorkflow.prisma().update(+ where={"id": row.id},+ data={"scheduleId": None, "scheduleCron": None},+ )+ cleared += 1+ if cleared:+ logger.info(f"Cleared removed roster cadences on {cleared} hired workflows")+ return cleared+++async def _delete_live_schedule(+ owner_id: str, schedule_id: str, live_by_owner: dict[str, set[str]]+) -> bool:+ """Delete *schedule_id* if the scheduler still has it for *owner_id*.++ Returns True when the job is confirmed gone; False on any scheduler+ failure so the caller keeps the row for a later retry.+ """+ try:+ scheduler = get_scheduler_client()+ if owner_id not in live_by_owner:+ schedules = await scheduler.get_execution_schedules(+ user_id=owner_id, kind="graph"+ )+ live_by_owner[owner_id] = {s.id for s in schedules}+ if schedule_id not in live_by_owner[owner_id]:+ return True+ await scheduler.delete_schedule(schedule_id, user_id=owner_id)+ live_by_owner[owner_id].discard(schedule_id)+ return True+ except Exception as e:+ logger.warning(+ f"Could not delete schedule #{schedule_id} for user #{owner_id}; "+ f"keeping cadence for retry: {type(e).__name__}: {e}"+ )+ return False++async def _upsert_template(entry: RosterEntry) -> prisma.models.Expert:fields = {"role": entry["role"],@@ -177,27 +278,36 @@ async def _backfill_hired_copies(template: prisma.models.Expert) -> int:A hire copies the template row, so roster updates would otherwise onlyever reach new hires and everyone who hired earlier would keep a blank- avatar/bio/skills forever. ``name`` is deliberately excluded — users may- have renamed their hire — as are ``role``/``identity``, which drive live- persona behaviour.+ avatar/tagline/bio/skills forever. ``name`` is deliberately excluded —+ users may have renamed their hire — as are ``role``/``identity``, which+ drive live persona behaviour."""return await prisma.models.Expert.prisma().update_many(where={"sourceTemplateId": template.id, "isTemplate": False},data={"avatarUrl": template.avatarUrl,+ "tagline": template.tagline,"bio": template.bio,"skills": template.skills,},)-async def _sync_preloads(template_id: str, entry: RosterEntry) -> None:+async def _sync_preloads(+ template_id: str,+ entry: RosterEntry,+ resolved_versions: Mapping[str, str] | None = None,+) -> None:existing = await prisma.models.ExpertWorkflow.prisma().find_many(where={"expertId": template_id})existing_by_version = {w.storeListingVersionId: w for w in existing}for preload in entry["preloads"]:- version_id = await _resolve_active_version_id(preload["slug"])+ version_id = (+ resolved_versions.get(preload["slug"])+ if resolved_versions is not None+ else await _resolve_active_version_id(preload["slug"])+ )if version_id is None:logger.warning(f"Store listing slug '{preload['slug']}' not found; "@@ -223,18 +333,37 @@ async def _sync_preloads(template_id: str, entry: RosterEntry) -> None:)+async def _resolve_roster_preloads() -> dict[str, str]:+ slugs = {preload["slug"] for entry in ROSTER for preload in entry["preloads"]}+ resolved = {+ slug: version_id+ for slug in sorted(slugs)+ if (version_id := await _resolve_active_version_id(slug)) is not None+ }+ missing = sorted(slugs - resolved.keys())+ if missing:+ raise RuntimeError(+ f"Official creator '{OFFICIAL_CREATOR_USERNAME}' is missing roster "+ f"listings for: {', '.join(missing)}. Load marketplace store assets "+ "before seeding the expert roster."+ )+ return resolved++async def seed_roster() -> list[str]:"""Upsert the roster templates and their preloads. Returns template ids."""+ resolved_versions = await _resolve_roster_preloads()template_ids = []for entry in ROSTER:template = await _upsert_template(entry)- await _sync_preloads(template.id, entry)+ await _sync_preloads(template.id, entry, resolved_versions)refreshed = await _backfill_hired_copies(template)template_ids.append(template.id)logger.info(f"Seeded expert template '{entry['name']}' (#{template.id}); "f"refreshed {refreshed} hired copies")+ await _clear_removed_cadences()return template_ids