Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(growth): versioned curated-list config for ICP fit scoring (#86006)

minekansu263426ea4475
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 4d3b5564cbd0..784651c76b58 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -180,6 +180,10 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
# Instance-global classifier definition, so there is no team_id to scope on. Seeded by
# migration and read by the batch runner; no API endpoint, never looked up by user-supplied ID.
"EnrichmentPromptConfig",
+ # Instance-global versioned ICP curated-list rows (created_by is authorship provenance,
+ # not access scoping). Written by a management command, read by the enrichment scorer;
+ # admin-only surface, never looked up by user-supplied ID.
+ "IcpScoringConfig",
# Shadow classifier output, org-scoped rather than team-scoped. Written only by the batch
# runner and read-only in admin; no API endpoint, never looked up by user-supplied ID.
# It carries an Organization FK, so the org_scoped rule would otherwise cover it: remove this
diff --git a/products/growth/backend/admin.py b/products/growth/backend/admin.py
index ba86d9900522..047f44931a32 100644
--- a/products/growth/backend/admin.py
+++ b/products/growth/backend/admin.py
@@ -17,8 +17,14 @@ from posthog.admin.inline_registry import register_admin_inline
from posthog.models.organization import Organization
from posthog.schema_enums import ProductKey
+from products.growth.backend.enrichment.icp_lists import clear_lists_cache
from products.growth.backend.enrichment.labels import MAX_INPUT_COLUMNS, RESERVED_OUTPUT_FIELD_KEYS, UNKNOWN
-from products.growth.backend.models import EnrichmentLabelResult, EnrichmentPromptConfig, ProductPushCampaign
+from products.growth.backend.models import (
+ EnrichmentLabelResult,
+ EnrichmentPromptConfig,
+ IcpScoringConfig,
+ ProductPushCampaign,
+)
from products.growth.backend.product_push.selection import select_next_product
from products.growth.backend.product_push.service import cancel_campaigns, get_eligible_organization_queryset
@@ -442,3 +448,47 @@ class EnrichmentPromptConfigAdmin(admin.ModelAdmin):
if not change and request.user.is_authenticated:
obj.created_by = request.user
super().save_model(request, obj, form, change)
+
+
[email protected](IcpScoringConfig)
+class IcpScoringConfigAdmin(admin.ModelAdmin):
+ """Versioned curated-list rows for V0.5 ICP scoring. Rows are created by the
+ sync_icp_scoring_lists command from the RevOps sheet exports; the admin exists to
+ inspect rows and move the active flag (activate here after a non---activate sync).
+ A list change is always a new row, so behavior-defining fields lock on save."""
+
+ list_display = ("version", "is_active", "tag_rows", "investor_rows", "created_by", "created_at")
+ list_filter = ("is_active",)
+ search_fields = ("version",)
+ ordering = ("-created_at",)
+ show_full_result_count = False
+
+ @admin.display(description="Tag rows")
+ def tag_rows(self, obj: IcpScoringConfig) -> int:
+ return len(obj.tags) if isinstance(obj.tags, list) else 0
+
+ @admin.display(description="Investors")
+ def investor_rows(self, obj: IcpScoringConfig) -> int:
+ return len(obj.quality_investors) if isinstance(obj.quality_investors, list) else 0
+
+ def get_readonly_fields(self, request: HttpRequest, obj: IcpScoringConfig | None = None) -> tuple[str, ...]:
+ readonly: tuple[str, ...] = ("id", "created_by", "created_at")
+ if obj is not None:
+ readonly = (*readonly, "version", "tags", "quality_investors")
+ return readonly
+
+ def has_add_permission(self, request: HttpRequest) -> bool:
+ return False
+
+ def has_delete_permission(self, request: HttpRequest, obj: IcpScoringConfig | None = None) -> bool:
+ return False
+
+ def save_model(self, request: HttpRequest, obj: IcpScoringConfig, form: forms.ModelForm, change: bool) -> None:
+ if not change and request.user.is_authenticated:
+ obj.created_by = request.user
+ if obj.is_active:
+ # Activation moves the flag: the one-active partial unique constraint would
+ # otherwise reject the save with an IntegrityError.
+ IcpScoringConfig.objects.filter(is_active=True).exclude(pk=obj.pk).update(is_active=False)
+ super().save_model(request, obj, form, change)
+ clear_lists_cache()
diff --git a/products/growth/backend/enrichment/icp_lists.py b/products/growth/backend/enrichment/icp_lists.py
new file mode 100644
index 000000000000..67893f2608fc
--- /dev/null
+++ b/products/growth/backend/enrichment/icp_lists.py
@@ -0,0 +1,195 @@
+"""RevOps-curated lists for ICP fit scoring: the container, the loader, and the sheet-export parsers.
+
+The curated tag buckets and quality-investor names live in versioned IcpScoringConfig rows
+(rails are code; brains are rows — the EnrichmentPromptConfig precedent), so RevOps'
+quarterly review lands without a deploy and the internal sheets never get committed to this
+public repo. This module turns the active row into the frozen CuratedLists the scorer
+consumes, normalized once at load, cached with a short TTL so the signup path doesn't
+re-read the row per score while a newly-activated row still takes effect within a minute.
+
+No active row means fit scoring is skipped (callers degrade to writing firmographics with
+no score) — never a crash and never a silently empty-list score, which would floor the
+Capital/AIPilled/SoftwareRelevance components for every org and look like a real
+evaluation.
+
+Django-free at import on purpose: the scorer and its tests import CuratedLists/norm from
+here, and only load_active_lists touches the ORM (lazily), so the pure scoring path never
+drags model imports in.
+"""
+
+import time
+import typing
+import threading
+import dataclasses
+from collections import Counter
+from typing import Any, Optional
+
+if typing.TYPE_CHECKING:
+ from products.growth.backend.models import IcpScoringConfig
+
+# Buckets a tag row's recommendation may name; anything else (e.g. "ignore") is skipped.
+TAG_BUCKETS = frozenset({"dq", "capital_quality", "software_positive", "software_negative", "ai_positive"})
+
+# The one non-bucket recommendation value the sheet uses deliberately; not a typo to flag.
+_IGNORE_RECOMMENDATION = "ignore"
+
+_CACHE_TTL_SECONDS = 60
+
+_cache_lock = threading.Lock()
+_cached: Optional[tuple[float, Optional["CuratedLists"]]] = None
+
+
+def norm(value: Optional[str]) -> str:
+ """Case + and/& normalization for tag and investor matching."""
+ return (value or "").lower().replace(" and ", " & ").strip()
+
+
[email protected](frozen=True)
+class CuratedLists:
+ """The RevOps-curated tag buckets and quality-investor names, pre-normalized via norm().
+
+ Built from the active IcpScoringConfig row; tests construct small synthetic instances
+ directly. dq/software_negative are curation metadata carried for auditability — the
+ scoring formula does not read them today.
+ """
+
+ version: str
+ capital_quality: frozenset[str] = frozenset()
+ ai_positive: frozenset[str] = frozenset()
+ software_positive: frozenset[str] = frozenset()
+ software_negative: frozenset[str] = frozenset()
+ dq: frozenset[str] = frozenset()
+ quality_investors: frozenset[str] = frozenset()
+
+
+def build_curated_lists(config: "IcpScoringConfig") -> CuratedLists:
+ """Parse one config row's JSON into pre-normalized frozensets.
+
+ Malformed rows are skipped rather than raising: a partially-bad sheet export should
+ degrade to a slightly smaller list, not take down scoring.
+ """
+ buckets: dict[str, set[str]] = {bucket: set() for bucket in TAG_BUCKETS}
+ for row in config.tags if isinstance(config.tags, list) else []:
+ if not isinstance(row, dict):
+ continue
+ tag = norm(row.get("tag"))
+ if not tag:
+ continue
+ for bucket in str(row.get("recommendation") or "").split("+"):
+ bucket = bucket.strip().lower()
+ if bucket in buckets:
+ buckets[bucket].add(tag)
+
+ investors: set[str] = set()
+ for row in config.quality_investors if isinstance(config.quality_investors, list) else []:
+ if not isinstance(row, dict):
+ continue
+ name = norm(row.get("investor"))
+ if name:
+ investors.add(name)
+ aliases = row.get("aliases")
+ for alias in aliases if isinstance(aliases, list) else []:
+ alias = norm(alias if isinstance(alias, str) else None)
+ if alias:
+ investors.add(alias)
+
+ return CuratedLists(
+ version=config.version,
+ capital_quality=frozenset(buckets["capital_quality"]),
+ ai_positive=frozenset(buckets["ai_positive"]),
+ software_positive=frozenset(buckets["software_positive"]),
+ software_negative=frozenset(buckets["software_negative"]),
+ dq=frozenset(buckets["dq"]),
+ quality_investors=frozenset(investors),
+ )
+
+
+def load_active_lists() -> Optional[CuratedLists]:
+ """The active config row as CuratedLists, or None when no row is active."""
+ from products.growth.backend.models import (
+ IcpScoringConfig, # noqa: PLC0415 — keep this module Django-free at import
+ )
+
+ global _cached
+ with _cache_lock:
+ if _cached is not None and time.monotonic() - _cached[0] < _CACHE_TTL_SECONDS:
+ return _cached[1]
+
+ config = IcpScoringConfig.objects.filter(is_active=True).first()
+ lists = build_curated_lists(config) if config is not None else None
+
+ # Stamp the entry after the query so a slow read can't silently shrink the TTL.
+ now = time.monotonic()
+ with _cache_lock:
+ _cached = (now, lists)
+ return lists
+
+
+def clear_lists_cache() -> None:
+ """Test hook; also useful right after activating a new row from a shell."""
+ global _cached
+ with _cache_lock:
+ _cached = None
+
+
+def parse_tags_csv_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Normalize RevOps' tag-sheet export rows into the stored shape.
+
+ Applies the one standing import-time decision (Mine, 2026-08-13): AI Grant batch tags
+ count as BOTH quality capital and AI signal, whatever single bucket the sheet assigned —
+ stored rows then carry the effective assignment visibly instead of hiding it in loader
+ code.
+ """
+ stored = []
+ for row in rows:
+ tag = (row.get("tag") or "").strip()
+ if not tag:
+ continue
+ recommendation = (row.get("recommendation") or "").strip()
+ if norm(tag).startswith("ai grant batch"):
+ # Normalize tokens the same way build_curated_lists does, so a cased/spaced
+ # sheet export ("Capital_Quality ") keeps its buckets through this rewrite.
+ effective = {
+ normalized
+ for bucket in recommendation.split("+")
+ if (normalized := bucket.strip().lower()) in TAG_BUCKETS
+ }
+ effective.update({"capital_quality", "ai_positive"})
+ recommendation = "+".join(sorted(effective))
+ stored.append(
+ {
+ "tag": tag,
+ "type": (row.get("type") or "").strip(),
+ "recommendation": recommendation,
+ "reason": (row.get("reason") or "").strip(),
+ "note": (row.get("note") or "").strip(),
+ }
+ )
+ return stored
+
+
+def unrecognized_recommendation_tokens(tags: list[dict[str, Any]]) -> Counter[str]:
+ """Count recommendation tokens that match neither a TAG_BUCKETS bucket nor "ignore".
+
+ Normalizes the same way build_curated_lists does, so a token this misses is exactly one
+ that would otherwise silently drop out of every bucket at load time.
+ """
+ counts: Counter[str] = Counter()
+ for row in tags:
+ for token in str(row.get("recommendation") or "").split("+"):
+ token = token.strip().lower()
+ if token and token not in TAG_BUCKETS and token != _IGNORE_RECOMMENDATION:
+ counts[token] += 1
+ return counts
+
+
+def parse_investors_csv_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Normalize RevOps' investor-sheet export rows ("aliases" pipe-separated) into the stored shape."""
+ stored = []
+ for row in rows:
+ investor = (row.get("investor") or "").strip()
+ if not investor:
+ continue
+ aliases = [alias.strip() for alias in (row.get("aliases") or "").split("|") if alias.strip()]
+ stored.append({"investor": investor, "aliases": aliases, "notes": (row.get("notes") or "").strip()})
+ return stored
diff --git a/products/growth/backend/management/commands/sync_icp_scoring_lists.py b/products/growth/backend/management/commands/sync_icp_scoring_lists.py
new file mode 100644
index 000000000000..711000111f53
--- /dev/null
+++ b/products/growth/backend/management/commands/sync_icp_scoring_lists.py
@@ -0,0 +1,118 @@
+"""Load the RevOps ICP scoring list exports (tags + quality investors) into a new IcpScoringConfig row.
+
+Quarterly flow: RevOps edits the two internal sheets, exports them as CSV, and this command
+turns the exports into a new versioned row — optionally activating it in the same run.
+A list change is always a new row; rows are never edited in place, so every stamped
+`icp_lists_version` in stored scores stays reconstructable.
+"""
+
+import csv
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.db import transaction
+
+from products.growth.backend.enrichment.icp_lists import (
+ TAG_BUCKETS,
+ build_curated_lists,
+ clear_lists_cache,
+ parse_investors_csv_rows,
+ parse_tags_csv_rows,
+ unrecognized_recommendation_tokens,
+)
+from products.growth.backend.models import IcpScoringConfig
+
+TAGS_REQUIRED_COLUMNS = {"tag", "recommendation"}
+INVESTORS_REQUIRED_COLUMNS = {"investor"}
+
+
+def _read_csv(path: str, required: set[str]) -> list[dict[str, Any]]:
+ try:
+ with open(path, newline="", encoding="utf-8-sig") as handle:
+ reader = csv.DictReader(handle)
+ columns = set(reader.fieldnames or [])
+ missing = required - columns
+ if missing:
+ raise CommandError(f"{path} is missing required columns: {sorted(missing)}")
+ return list(reader)
+ except OSError as e:
+ raise CommandError(f"could not read {path}: {e}")
+
+
+class Command(BaseCommand):
+ help = (
+ "Create a new versioned IcpScoringConfig row from the RevOps sheet exports "
+ "(tags + quality investors). Never edits an existing row; --activate atomically "
+ "moves the active flag to the new row."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--tags-csv", required=True, help="Path to the tag-list sheet export")
+ parser.add_argument("--investors-csv", required=True, help="Path to the quality-investor sheet export")
+ # not --version: that collides with the built-in flag every Django command inherits
+ parser.add_argument("--list-version", required=True, help="Version label for the new row, e.g. 2026-08-13")
+ parser.add_argument("--activate", action="store_true", help="Make the new row the active one")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ version: str = options["list_version"]
+ if IcpScoringConfig.objects.filter(version=version).exists():
+ raise CommandError(f"IcpScoringConfig version {version!r} already exists; pick a new version")
+
+ tags = parse_tags_csv_rows(_read_csv(options["tags_csv"], TAGS_REQUIRED_COLUMNS))
+ investors = parse_investors_csv_rows(_read_csv(options["investors_csv"], INVESTORS_REQUIRED_COLUMNS))
+ if not tags:
+ raise CommandError("tags export parsed to zero rows; refusing to create an empty list version")
+ if not investors:
+ raise CommandError("investors export parsed to zero rows; refusing to create an empty list version")
+
+ curated = build_curated_lists(IcpScoringConfig(version=version, tags=tags, quality_investors=investors))
+ bucket_counts = {field: len(getattr(curated, field)) for field in sorted(TAG_BUCKETS)}
+ if not any(bucket_counts.values()):
+ raise CommandError(
+ f"tags export for version {version!r} parsed to buckets that are all empty "
+ "(vocabulary drift, a wrong delimiter, or a shifted column?); refusing to create it"
+ )
+ if not curated.quality_investors:
+ raise CommandError(
+ f"investors export for version {version!r} parsed to zero quality investors; refusing to create it"
+ )
+
+ with transaction.atomic():
+ if options["activate"]:
+ IcpScoringConfig.objects.filter(is_active=True).update(is_active=False)
+ config = IcpScoringConfig.objects.create(
+ version=version,
+ tags=tags,
+ quality_investors=investors,
+ is_active=options["activate"],
+ )
+ clear_lists_cache()
+
+ investors_with_aliases = sum(1 for investor in investors if investor["aliases"])
+ state = "active" if config.is_active else "inactive (activate via admin or --activate)"
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"created IcpScoringConfig {version}: {len(tags)} tag rows, {len(investors)} investors "
+ f"({investors_with_aliases} with aliases) — {state}"
+ )
+ )
+ self.stdout.write(
+ "buckets: "
+ + ", ".join(f"{field}={count}" for field, count in bucket_counts.items())
+ + f", quality_investors={len(curated.quality_investors)}"
+ )
+
+ if investors_with_aliases == 0:
+ self.stdout.write(
+ self.style.WARNING(
+ "no investor has any aliases — check whether the aliases column was renamed or dropped"
+ )
+ )
+
+ unrecognized = unrecognized_recommendation_tokens(tags)
+ if unrecognized:
+ total = sum(unrecognized.values())
+ detail = ", ".join(f"{token!r} x{count}" for token, count in unrecognized.most_common())
+ self.stdout.write(
+ self.style.WARNING(f"{total} unrecognized recommendation token(s) dropped from every bucket: {detail}")
+ )
diff --git a/products/growth/backend/migrations/0008_icpscoringconfig.py b/products/growth/backend/migrations/0008_icpscoringconfig.py
new file mode 100644
index 000000000000..d87aa000de99
--- /dev/null
+++ b/products/growth/backend/migrations/0008_icpscoringconfig.py
@@ -0,0 +1,52 @@
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("growth", "0007_organizationenrichmentfetch_growth_enrich_fetch_org_ts_id"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="IcpScoringConfig",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("version", models.CharField(max_length=128, unique=True)),
+ ("tags", models.JSONField(default=list)),
+ ("quality_investors", models.JSONField(default=list)),
+ ("is_active", models.BooleanField(default=False)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.AddConstraint(
+ model_name="icpscoringconfig",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("is_active", True)),
+ fields=("is_active",),
+ name="growth_icp_lists_one_active",
+ ),
+ ),
+ ]
diff --git a/products/growth/backend/migrations/max_migration.txt b/products/growth/backend/migrations/max_migration.txt
index 3d35abbfca3a..66801f8397cc 100644
--- a/products/growth/backend/migrations/max_migration.txt
+++ b/products/growth/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0007_organizationenrichmentfetch_growth_enrich_fetch_org_ts_id
+0008_icpscoringconfig
diff --git a/products/growth/backend/models.py b/products/growth/backend/models.py
index 88b8267e8442..608ed003f184 100644
--- a/products/growth/backend/models.py
+++ b/products/growth/backend/models.py
@@ -275,6 +275,52 @@ class EnrichmentLabelResult(UUIDModel):
return f"{self.organization_id} {self.label_name} {self.prompt_version}"
+class IcpScoringConfig(UUIDModel):
+ """A versioned snapshot of the RevOps-curated lists behind the ICP fit score.
+
+ Rails are code; brains are rows (the EnrichmentPromptConfig precedent): the scoring
+ formula and weights live in code (the fit scorer, landing separately), but the curated
+ tag buckets and quality-investor names it matches against live here, so RevOps'
+ quarterly review lands without a deploy — and the internal sheets never get committed
+ to this public repo. A list change is always a new row (new version) activated
+ explicitly, never an in-place edit; scores stamp the row's version as
+ `icp_fit_lists_version`, so a list update is distinguishable from a formula change
+ (`icp_fit_version`) in every stored score.
+
+ Rows are written by the `sync_icp_scoring_lists` management command from the RevOps
+ sheet exports; see enrichment/icp_lists.py for the row shapes and the loader.
+ """
+
+ # Human-readable list version, e.g. "2026-08-13".
+ version = models.CharField(max_length=128, unique=True)
+ # Tag curation rows: [{"tag", "type", "recommendation", "reason", "note"}]. recommendation
+ # is "+"-joined bucket names (ai_positive, capital_quality, software_positive,
+ # software_negative, dq, ignore).
+ tags = models.JSONField(default=list)
+ # Quality investor rows: [{"investor", "aliases": [...], "notes"}].
+ quality_investors = models.JSONField(default=list)
+ # The row the scorer loads; at most one active row (enforced below).
+ is_active = models.BooleanField(default=False)
+ created_by = models.ForeignKey(
+ "posthog.User",
+ on_delete=models.SET_NULL,
+ null=True,
+ blank=True,
+ db_constraint=False,
+ )
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ constraints = [
+ models.UniqueConstraint(
+ fields=["is_active"], condition=Q(is_active=True), name="growth_icp_lists_one_active"
+ ),
+ ]
+
+ def __str__(self) -> str:
+ return f"icp lists {self.version}{' (active)' if self.is_active else ''}"
+
+
class EnrichmentSignupSnapshot(UUIDModel):
"""Write-once marker that the at-signup enrichment snapshot has been emitted for an org.
diff --git a/products/growth/backend/tests/test_icp_lists.py b/products/growth/backend/tests/test_icp_lists.py
new file mode 100644
index 000000000000..b2e6629f429a
--- /dev/null
+++ b/products/growth/backend/tests/test_icp_lists.py
@@ -0,0 +1,259 @@
+import os
+import csv
+import tempfile
+
+from posthog.test.base import BaseTest
+
+from django.core.management import CommandError, call_command
+
+from products.growth.backend.enrichment.icp_lists import (
+ build_curated_lists,
+ clear_lists_cache,
+ load_active_lists,
+ parse_tags_csv_rows,
+ unrecognized_recommendation_tokens,
+)
+from products.growth.backend.models import IcpScoringConfig
+
+
+def _config(**overrides) -> IcpScoringConfig:
+ kwargs = {
+ "version": "lists-1",
+ "tags": [
+ {"tag": "Artificial Intelligence", "type": "MARKET", "recommendation": "ai_positive"},
+ {"tag": "Developer Tools", "type": "MARKET", "recommendation": "software_positive"},
+ {"tag": "AI Grant Batch 1", "type": "ACCELERATOR", "recommendation": "ai_positive+capital_quality"},
+ {"tag": "Plug and Play", "type": "ACCELERATOR", "recommendation": "ignore"},
+ "not-a-dict-row",
+ ],
+ "quality_investors": [
+ {"investor": "Y Combinator", "aliases": ["YC"], "notes": ""},
+ {"investor": "Sequoia Capital", "aliases": [], "notes": ""},
+ {"investor": "", "aliases": ["dropped"], "notes": "no name, alias still counts"},
+ ],
+ "is_active": False,
+ }
+ kwargs.update(overrides)
+ return IcpScoringConfig.objects.create(**kwargs)
+
+
+class TestIcpLists(BaseTest):
+ def setUp(self):
+ super().setUp()
+ clear_lists_cache()
+
+ def tearDown(self):
+ clear_lists_cache()
+ super().tearDown()
+
+ def test_build_curated_lists_buckets_normalizes_and_skips_malformed_rows(self):
+ lists = build_curated_lists(_config())
+
+ assert lists.version == "lists-1"
+ assert "artificial intelligence" in lists.ai_positive
+ assert "ai grant batch 1" in lists.ai_positive
+ assert "ai grant batch 1" in lists.capital_quality # "+"-joined recommendation lands in both
+ assert "developer tools" in lists.software_positive
+ assert "plug & play" not in lists.capital_quality # "ignore" is not a bucket
+ assert lists.quality_investors == {"y combinator", "yc", "sequoia capital", "dropped"}
+
+ def test_load_active_lists_returns_none_without_an_active_row(self):
+ _config() # inactive
+ assert load_active_lists() is None
+
+ def test_load_active_lists_caches_until_cleared(self):
+ config = _config(is_active=True)
+
+ def active_version() -> str:
+ lists = load_active_lists()
+ assert lists is not None
+ return lists.version
+
+ assert active_version() == "lists-1"
+
+ config.version = "lists-2"
+ config.save()
+ assert active_version() == "lists-1" # cached
+ clear_lists_cache()
+ assert active_version() == "lists-2"
+
+ def test_recommendation_tokens_are_normalized_and_strays_are_countable(self):
+ # A reformatted sheet export ("AI_Positive ", "Capital_Quality") must not silently
+ # empty a bucket; genuinely unknown tokens are surfaced by the counter the sync
+ # command warns with.
+ config = _config(
+ version="messy",
+ tags=[
+ {"tag": "Artificial Intelligence", "recommendation": " AI_POSITIVE "},
+ {"tag": "Developer Tools", "recommendation": "Software_Positive+banana"},
+ ],
+ )
+ lists = build_curated_lists(config)
+ assert "artificial intelligence" in lists.ai_positive
+ assert "developer tools" in lists.software_positive
+
+ strays = unrecognized_recommendation_tokens(config.tags)
+ assert strays == {"banana": 1}
+
+ def test_ai_grant_rows_are_upgraded_to_both_buckets_at_import(self):
+ rows = parse_tags_csv_rows(
+ [
+ {
+ "tag": "AI Grant Batch 2",
+ "type": "ACCELERATOR",
+ "recommendation": "ai_positive",
+ "reason": "",
+ "note": "",
+ }
+ ]
+ )
+ assert rows[0]["recommendation"] == "ai_positive+capital_quality"
+
+ def test_ai_grant_rewrite_keeps_cased_tokens_from_a_reformatted_export(self):
+ # The rewrite must normalize tokens like build_curated_lists does, or a cased
+ # export would silently drop buckets from the stored recommendation.
+ rows = parse_tags_csv_rows(
+ [
+ {
+ "tag": "AI Grant Batch 1",
+ "type": "ACCELERATOR",
+ "recommendation": " Software_Positive +AI_POSITIVE",
+ "reason": "",
+ "note": "",
+ }
+ ]
+ )
+ assert rows[0]["recommendation"] == "ai_positive+capital_quality+software_positive"
+
+ def _write_exports(self):
+ tempdir = tempfile.mkdtemp()
+ tags_path = os.path.join(tempdir, "tags.csv")
+ investors_path = os.path.join(tempdir, "investors.csv")
+ with open(tags_path, "w", newline="") as handle:
+ writer = csv.DictWriter(
+ handle, fieldnames=["tag", "type", "n_companies", "recommendation", "reason", "note"]
+ )
+ writer.writeheader()
+ writer.writerow(
+ {
+ "tag": "Artificial Intelligence",
+ "type": "MARKET",
+ "n_companies": "9",
+ "recommendation": "ai_positive",
+ "reason": "",
+ "note": "",
+ }
+ )
+ with open(investors_path, "w", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=["investor", "aliases", "notes"])
+ writer.writeheader()
+ writer.writerow({"investor": "Y Combinator", "aliases": "YC|Y Combinator Continuity", "notes": ""})
+ return tags_path, investors_path
+
+ def test_sync_command_creates_and_activates_a_row(self):
+ tags_path, investors_path = self._write_exports()
+ call_command(
+ "sync_icp_scoring_lists",
+ "--tags-csv",
+ tags_path,
+ "--investors-csv",
+ investors_path,
+ "--list-version",
+ "2026-08-13",
+ "--activate",
+ )
+
+ config = IcpScoringConfig.objects.get(version="2026-08-13")
+ assert config.is_active is True
+ assert config.quality_investors[0]["aliases"] == ["YC", "Y Combinator Continuity"]
+ lists = load_active_lists()
+ assert lists is not None and "y combinator continuity" in lists.quality_investors
+
+ def test_sync_command_moves_the_active_flag_atomically(self):
+ _config(version="old", is_active=True)
+ tags_path, investors_path = self._write_exports()
+ call_command(
+ "sync_icp_scoring_lists",
+ "--tags-csv",
+ tags_path,
+ "--investors-csv",
+ investors_path,
+ "--list-version",
+ "new",
+ "--activate",
+ )
+
+ assert IcpScoringConfig.objects.get(version="old").is_active is False
+ assert IcpScoringConfig.objects.get(version="new").is_active is True
+
+ def test_sync_command_rejects_duplicate_versions_and_empty_exports(self):
+ _config(version="dup")
+ tags_path, investors_path = self._write_exports()
+ with self.assertRaises(CommandError):
+ call_command(
+ "sync_icp_scoring_lists",
+ "--tags-csv",
+ tags_path,
+ "--investors-csv",
+ investors_path,
+ "--list-version",
+ "dup",
+ )
+
+ empty_path = os.path.join(tempfile.mkdtemp(), "empty.csv")
+ with open(empty_path, "w", newline="") as handle:
+ csv.DictWriter(handle, fieldnames=["tag", "recommendation"]).writeheader()
+ with self.assertRaises(CommandError):
+ call_command(
+ "sync_icp_scoring_lists",
+ "--tags-csv",
+ empty_path,
+ "--investors-csv",
+ investors_path,
+ "--list-version",
+ "fresh",
+ )
+
+ def test_sync_command_refuses_a_row_that_would_produce_only_empty_buckets(self):
+ tempdir = tempfile.mkdtemp()
+ tags_path = os.path.join(tempdir, "tags.csv")
+ with open(tags_path, "w", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=["tag", "recommendation"])
+ writer.writeheader()
+ writer.writerow({"tag": "Plug and Play", "recommendation": "ignore"})
+ writer.writerow({"tag": "Some Vertical", "recommendation": "banana"})
+ _, investors_path = self._write_exports()
+
+ with self.assertRaises(CommandError):
+ call_command(
+ "sync_icp_scoring_lists",
+ "--tags-csv",
+ tags_path,
+ "--investors-csv",
+ investors_path,
+ "--list-version",
+ "empty-buckets",
+ )
+ assert not IcpScoringConfig.objects.filter(version="empty-buckets").exists()
+
+ def test_sync_command_warns_but_succeeds_when_no_investor_has_aliases(self):
+ tags_path, _ = self._write_exports()
+ tempdir = tempfile.mkdtemp()
+ investors_path = os.path.join(tempdir, "investors.csv")
+ with open(investors_path, "w", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=["investor", "aliases", "notes"])
+ writer.writeheader()
+ writer.writerow({"investor": "Y Combinator", "aliases": "", "notes": ""})
+ writer.writerow({"investor": "Sequoia Capital", "aliases": "", "notes": ""})
+
+ call_command(
+ "sync_icp_scoring_lists",
+ "--tags-csv",
+ tags_path,
+ "--investors-csv",
+ investors_path,
+ "--list-version",
+ "no-aliases",
+ )
+
+ assert IcpScoringConfig.objects.filter(version="no-aliases").exists()
diff --git a/products/growth/backend/tests/test_icp_scoring_admin.py b/products/growth/backend/tests/test_icp_scoring_admin.py
new file mode 100644
index 000000000000..de4239d40c9c
--- /dev/null
+++ b/products/growth/backend/tests/test_icp_scoring_admin.py
@@ -0,0 +1,23 @@
+from posthog.test.base import BaseTest
+
+from django.contrib.admin import AdminSite
+from django.test import RequestFactory
+
+from products.growth.backend.admin import IcpScoringConfigAdmin
+from products.growth.backend.models import IcpScoringConfig
+
+
+class TestIcpScoringConfigAdminPermissions(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.admin = IcpScoringConfigAdmin(IcpScoringConfig, AdminSite())
+ self.request = RequestFactory().get("/admin/growth/icpscoringconfig/")
+
+ def test_add_is_never_permitted(self) -> None:
+ assert self.admin.has_add_permission(self.request) is False
+
+ def test_delete_is_never_permitted(self) -> None:
+ config = IcpScoringConfig.objects.create(version="v1", is_active=True)
+
+ assert self.admin.has_delete_permission(self.request, config) is False
+ assert self.admin.has_delete_permission(self.request, None) is False