: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(llma): community skills catalog models + ingest (1/7) (#71867)
Andrew Maguire2fe5fbb87b8e
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex 2d25416b26df..d853c0d810a6 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -285,6 +285,8 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"PromptSequence","UserPromptState",# --- Global catalogs ---+ "CommunitySkill", # instance-global community skills catalog, synced from GitHub+ "CommunitySkillFile", # bundled files of a CommunitySkill (scoped via the catalog row)"HogFunctionTemplate","MCPServer",# --- Special (has source_team + destination_team, not a plain team) ---diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 017fed96a62e..6b275336bf88 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -942,7 +942,8 @@ rules:metavariable: $MODELregex: |(?x)(- DashboardPrivilege+ CommunitySkillVote+ |DashboardPrivilege|PersonalAPIKey|ScoreDefinitionVersion|SignalUserAutonomyConfig@@ -997,7 +998,8 @@ rules:metavariable: $MODELregex: |(?x)(- DashboardPrivilege+ CommunitySkillVote+ |DashboardPrivilege|PersonalAPIKey|ScoreDefinitionVersion|SignalUserAutonomyConfigdiff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex a4ff68850dd1..44da5c60810b 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -103,6 +103,7 @@ from products.signals.backend.tasks import (refresh_signal_repository_activity,sync_pending_signals_refund_credits,)+from products.skills.backend.tasks import sync_community_skillsfrom products.stamphog.backend.facade.tasks import DAILY_DIGEST_CRONTAB, send_daily_digestsfrom products.streamlit_apps.backend.facade.api import (auto_restart_crashed_streamlit_sandboxes,@@ -523,6 +524,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="send llm analytics usage reports",)+ # Sync the community skills catalog from GitHub hourly+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="20"),+ sync_community_skills.s(),+ name="sync community skills catalog",+ )+# Send HogFunctions daily digest at 9:30 AM UTC (good for US and EU)sender.add_periodic_task(crontab(hour="9", minute="30"),diff --git a/products/skills/backend/api/community_skill_sync.py b/products/skills/backend/api/community_skill_sync.pynew file mode 100644index 000000000000..d452a67362e9--- /dev/null+++ b/products/skills/backend/api/community_skill_sync.py@@ -0,0 +1,313 @@+from typing import Any++from django.core.exceptions import ValidationError as DjangoValidationError+from django.db import DataError, IntegrityError, transaction+from django.db.models import Field, Model+from django.utils import timezone++import structlog+from rest_framework.serializers import ValidationError as DRFValidationError++from posthog.egress.github.transport import github_request++from ..models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillTrustTier+from .skill_serializers import RESERVED_SKILL_NAMES, SKILL_NAME_PATTERN, validate_skill_file_path+from .skill_services import MAX_SKILL_BODY_BYTES, MAX_SKILL_FILE_BYTES, MAX_SKILL_FILE_COUNT++logger = structlog.get_logger(__name__)++_VALID_TRUST_TIERS = set(CommunitySkillTrustTier.values)+DEFAULT_FILE_CONTENT_TYPE = "text/plain"+# CharField columns that raise DataError past their max_length — checked before persisting.+_CHECKED_CHAR_FIELDS = (+ "slug",+ "name",+ "description",+ "license",+ "compatibility",+ "author_handle",+ "github_url",+ "source_sha",+)+++def _text(container: dict[str, Any], key: str, label: str, default: str = "") -> str:+ """Read a text field, rejecting non-strings before any default is applied.++ An `or <default>` fallback masks a *falsy* non-string (``False``, ``0``, ``[]``): it satisfies+ a later isinstance check as ``""`` while the raw value is what reaches the column, and+ Char/TextField stores its repr (``"False"``, ``"0"``, ``"[]"``). Both validation and+ persistence go through here so they can't disagree about what the value is. Absent and+ explicit-null both mean "use the default".+ """+ raw = container.get(key)+ if raw is None:+ return default+ if not isinstance(raw, str):+ raise ValueError(f"{label} must be a string")+ return raw+++def _field_max_length(model: type[Model], field_name: str) -> int | None:+ # _meta.get_field returns Field | ForeignObjectRel | GenericForeignKey; only concrete+ # Fields carry max_length. All names we pass here are CharFields, so narrow to Field.+ field = model._meta.get_field(field_name)+ return field.max_length if isinstance(field, Field) else None+++COMMUNITY_SKILLS_REPO = "PostHog/community-skills"+COMMUNITY_SKILLS_BRANCH = "main"+COMMUNITY_SKILLS_REGISTRY_URL = (+ f"https://raw.githubusercontent.com/{COMMUNITY_SKILLS_REPO}/{COMMUNITY_SKILLS_BRANCH}/registry.json"+)+COMMUNITY_SKILLS_SYNC_TIMEOUT_SECONDS = 30+++def _validate_entry_shape(entry: dict[str, Any]) -> None:+ """Reject entries whose field shapes would break catalog rendering or install.++ The registry is generated in a review-gated repo, but a single mistyped field (a scalar+ ``metadata``, a non-list ``tags``, a slug that DRF's lookup regex can't route) would+ otherwise 500 the whole list/detail page or the install copy. Raising ValueError isolates+ the failure to the one bad entry (the sync loop's per-entry ``except`` catches it).+ """+ slug = entry.get("slug", "")+ # The slug is both the catalog URL segment and the default installed-skill name, so it must+ # satisfy the skill-name rules — lowercase alnum + single hyphens, not reserved. This also+ # keeps DRF's default lookup regex (which rejects '.'/'/') able to route detail/install URLs,+ # and means the default-name install can never raise an uncaught name ValidationError.+ # fullmatch, not match: `$` also matches just before a trailing newline, so `match` would+ # accept "valid-skill\n" and persist the newline into the URL segment and install name.+ if (+ not isinstance(slug, str)+ or not SKILL_NAME_PATTERN.fullmatch(slug)+ or "--" in slug+ or slug.lower() in RESERVED_SKILL_NAMES+ ):+ raise ValueError(f"slug '{slug}' is not a valid, routable skill identifier")++ # Blank passes both the type and length checks but leaves an unusable entry: a nameless card in+ # the catalog, and a blank description that `marketplace.packaging.validate_for_export` refuses,+ # so the skill installs and then can't be exported. The install path rejects it too.+ for required in ("name", "description"):+ if not _text(entry, required, f"'{required}'").strip():+ raise ValueError(f"'{required}' is required and must be non-blank")++ metadata = entry.get("metadata")+ if metadata is not None and not isinstance(metadata, dict):+ raise ValueError("metadata must be an object")++ # A falsy non-list (`{}`, `false`, `0`, `""`) must not be normalized to "no files": the upsert+ # deletes the skill's existing files before recreating them, so a mistyped `files` on an entry+ # with a changed source_sha would strip every bundled file from a live catalog skill and still+ # report the sync as successful. Absent/null legitimately mean "no files".+ files = entry.get("files")+ if files is not None and not isinstance(files, list):+ raise ValueError("files must be a list")++ tags = entry.get("tags")+ if tags is not None and (not isinstance(tags, list) or not all(isinstance(t, str) for t in tags)):+ raise ValueError("tags must be a list of strings")++ allowed_tools = entry.get("allowed_tools")+ if allowed_tools is not None:+ if not isinstance(allowed_tools, list) or not all(isinstance(t, str) for t in allowed_tools):+ raise ValueError("allowed_tools must be a list of strings")+ # The Agent Skills spec serializes allowed-tools as one space-separated string, so a name+ # with whitespace would silently fracture into multiple tools on export/round-trip.+ if any(any(ch.isspace() for ch in t) for t in allowed_tools):+ raise ValueError("allowed_tools names cannot contain whitespace")+++def _validate_entry_within_caps(entry: dict[str, Any]) -> None:+ """Reject entries that would violate a DB constraint before persisting.++ The registry is built in a review-gated repo, but a single entry that overflows a column+ (oversized body/file, an overlong slug/name, a duplicate file path) would otherwise raise+ DataError/IntegrityError mid-loop — aborting the whole sync and skipping the soft-delete+ reconciliation. Raising ValueError here keeps that failure isolated to the one bad entry.+ """+ body = _text(entry, "body", "body")+ if len(body.encode("utf-8")) > MAX_SKILL_BODY_BYTES:+ raise ValueError(f"body exceeds the {MAX_SKILL_BODY_BYTES} byte limit")++ for field in _CHECKED_CHAR_FIELDS:+ value = _text(entry, field, f"'{field}'")+ max_length = _field_max_length(CommunitySkill, field)+ if max_length is not None and len(value) > max_length:+ raise ValueError(f"'{field}' exceeds the {max_length} character limit")++ files = entry.get("files", []) or []+ if len(files) > MAX_SKILL_FILE_COUNT:+ raise ValueError(f"has more than {MAX_SKILL_FILE_COUNT} files")+ path_max = _field_max_length(CommunitySkillFile, "path")+ seen_paths: set[str] = set()+ for f in files:+ raw_path = _text(f, "path", "file path")+ # Same invariant the skill create/import paths enforce: traversal, absolute, reserved and+ # backslash spellings produce corrupt git/export trees. Normalizing here also means dedup+ # compares canonical paths, so `references\g.md` and `references/g.md` can't both land.+ try:+ path = validate_skill_file_path(raw_path)+ except DRFValidationError as err:+ raise ValueError(f"file path '{raw_path}' is invalid: {err.detail}") from err+ if path_max is not None and len(path) > path_max:+ raise ValueError(f"file path '{path}' exceeds the {path_max} character limit")+ # Case-insensitive, matching `_skill_files_are_tree_safe`: two paths differing only by case+ # collide on a case-insensitive filesystem, and that check silently drops the whole skill+ # from a team's marketplace clone. Cheaper to reject the entry than to ship a skill that+ # installs fine and then vanishes from the generated tree.+ if path.lower() in seen_paths:+ raise ValueError(f"duplicate file path '{path}'")+ seen_paths.add(path.lower())+ content_type = _text(f, "content_type", f"file '{path}' content_type", DEFAULT_FILE_CONTENT_TYPE)+ ct_max = _field_max_length(CommunitySkillFile, "content_type")+ if ct_max is not None and len(content_type) > ct_max:+ raise ValueError(f"file '{path}' content_type exceeds the {ct_max} character limit")+ content = _text(f, "content", f"file '{path}' content")+ if len(content.encode("utf-8")) > MAX_SKILL_FILE_BYTES:+ raise ValueError(f"file '{path}' exceeds the {MAX_SKILL_FILE_BYTES} byte limit")+++def _upsert_community_skill(entry: dict[str, Any]) -> bool:+ """Upsert a single registry entry. Returns True if the row was created or updated."""+ slug = entry["slug"]+ _validate_entry_shape(entry)+ _validate_entry_within_caps(entry)+ # Read through _text after validation so the value compared against the stored sha (and every+ # value persisted below) is the same coerced string the caps check approved.+ source_sha = _text(entry, "source_sha", "'source_sha'")++ existing = CommunitySkill.objects.filter(slug=slug).first()+ if existing is not None and existing.source_sha and existing.source_sha == source_sha and not existing.deleted:+ return False++ # Model choices aren't DB-enforced, so an unknown tier would persist raw and break consumers+ # that coerce it back to CommunitySkillTrustTier — fall back to the least-privileged tier.+ trust_tier = entry.get("trust_tier") or CommunitySkillTrustTier.COMMUNITY.value+ if trust_tier not in _VALID_TRUST_TIERS:+ logger.warning("community_skills_sync_unknown_trust_tier", slug=slug, trust_tier=trust_tier)+ trust_tier = CommunitySkillTrustTier.COMMUNITY.value++ defaults: dict[str, Any] = {+ # name/description stay subscripted: they're required, and a missing one must raise+ # KeyError so the entry is isolated rather than persisted with empty visible text.+ "name": entry["name"],+ "description": entry["description"],+ "body": _text(entry, "body", "body"),+ "license": _text(entry, "license", "'license'"),+ "compatibility": _text(entry, "compatibility", "'compatibility'"),+ # `or <empty>` rather than a .get default: an explicitly-null field in the registry makes+ # .get return None, which these non-nullable JSON columns reject at insert time.+ "allowed_tools": entry.get("allowed_tools") or [],+ "metadata": entry.get("metadata") or {},+ "tags": entry.get("tags") or [],+ "trust_tier": trust_tier,+ "author_handle": _text(entry, "author_handle", "'author_handle'"),+ "github_url": _text(entry, "github_url", "'github_url'"),+ "source_sha": source_sha,+ "deleted": False,+ }+ if entry.get("published_at"):+ defaults["published_at"] = entry["published_at"]++ with transaction.atomic():+ skill, _ = CommunitySkill.objects.update_or_create(slug=slug, defaults=defaults)+ if skill.published_at is None:+ CommunitySkill.objects.filter(pk=skill.pk).update(published_at=timezone.now())++ skill.files.all().delete()+ files = entry.get("files", [])+ if files:+ CommunitySkillFile.objects.bulk_create(+ [+ CommunitySkillFile(+ # Store the canonical form the caps check produced, not the raw spelling.+ path=validate_skill_file_path(_text(f, "path", "file path")),+ skill=skill,+ content=_text(f, "content", "file content"),+ content_type=_text(f, "content_type", "file content_type", DEFAULT_FILE_CONTENT_TYPE),+ )+ for f in files+ ]+ )+ return True+++def sync_community_skills_from_github(registry_url: str = COMMUNITY_SKILLS_REGISTRY_URL) -> dict[str, int]:+ """Pull the community-skills registry and reconcile the local read-model.++ The registry.json is generated in the repo's CI and embeds each skill's content, so a+ single fetch is enough. Skills missing from the registry are soft-deleted. Returns a+ summary of {synced, skipped, removed} counts.+ """+ # Identity-blind GitHub egress: an unauthenticated CDN fetch with no installation to meter,+ # so it records request volume only and skips the limiter, but still goes through the gated,+ # recorded transport rather than hand-rolled requests.+ response = github_request(+ "GET",+ registry_url,+ source="community_skills",+ installation_id=None,+ timeout=COMMUNITY_SKILLS_SYNC_TIMEOUT_SECONDS,+ )+ response.raise_for_status()+ payload = response.json()+ entries = payload.get("skills", [])++ # Fail closed on malformed/empty payloads: a missing/empty `skills` key (bad generated+ # registry, proxy error, rate-limit body) would otherwise soft-delete the entire catalog.+ if not isinstance(entries, list):+ raise ValueError("Registry payload 'skills' must be a list")+ if not entries:+ logger.warning("community_skills_sync_skipped_empty_registry")+ return {"synced": 0, "skipped": 0, "removed": 0}++ synced = 0+ skipped = 0+ processed_ok = 0+ seen_slugs: set[str] = set()+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ slug = entry.get("slug")+ # Must be a string before it can go in a set: a truthy-but-unhashable slug (object/array+ # from a malformed registry) would raise TypeError here, outside the per-entry boundary,+ # and abort the whole sync. Full slug validation still happens inside the upsert.+ if not slug or not isinstance(slug, str):+ # Unidentifiable: we can't tell which catalog row it meant, so it can't be marked seen.+ # Logged because it's otherwise invisible — it never reaches the per-entry handler.+ logger.warning("community_skills_sync_unidentifiable_entry", slug_type=type(slug).__name__)+ continue+ # Mark the slug seen before upserting so a malformed entry can't soft-delete the+ # existing row for a skill that's still present in the registry.+ seen_slugs.add(slug)+ try:+ created_or_updated = _upsert_community_skill(entry)+ except (KeyError, ValueError, TypeError, AttributeError, DjangoValidationError, IntegrityError, DataError):+ # One bad entry (missing/oversized/mistyped field, or a constraint violation) must not+ # abort the whole loop or skip the reconciliation below. Each upsert runs in its own+ # atomic block, so the failed insert has already rolled back cleanly by the time we+ # catch. Only entry-local constraint errors are caught: operational failures+ # (connection loss, failover, statement timeout) are not one bad entry, and swallowing+ # them would report a successful sync while the catalog silently went stale.+ logger.warning("community_skills_sync_skipped_invalid_entry", slug=slug, exc_info=True)+ skipped += 1+ continue+ processed_ok += 1+ if created_or_updated:+ synced += 1+ else:+ skipped += 1++ # Fail-safe: only reconcile once at least one entry processed cleanly. A registry that parsed+ # but yielded zero healthy entries (schema change, generator bug, every entry malformed) must+ # not soft-delete the catalog — even when the malformed entries carried slugs.+ if not processed_ok:+ logger.warning("community_skills_sync_skipped_no_healthy_entries", entry_count=len(entries))+ return {"synced": synced, "skipped": skipped, "removed": 0}++ removed = CommunitySkill.objects.filter(deleted=False).exclude(slug__in=seen_slugs).update(deleted=True)++ logger.info("community_skills_synced", synced=synced, skipped=skipped, removed=removed, total=len(entries))+ return {"synced": synced, "skipped": skipped, "removed": removed}diff --git a/products/skills/backend/api/test/test_community_skill_sync.py b/products/skills/backend/api/test/test_community_skill_sync.pynew file mode 100644index 000000000000..e4625364f086--- /dev/null+++ b/products/skills/backend/api/test/test_community_skill_sync.py@@ -0,0 +1,333 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.db import OperationalError++from parameterized import parameterized++from ...models.community_skills import CommunitySkill+from ..community_skill_sync import sync_community_skills_from_github+from ..skill_services import MAX_SKILL_BODY_BYTES+++def _create_community_skill(+ *,+ slug: str = "web-analytics-triage",+ name: str = "Web analytics triage",+ trust_tier: str = "official",+ install_count: int = 0,+ deleted: bool = False,+) -> CommunitySkill:+ return CommunitySkill.objects.create(+ slug=slug,+ name=name,+ description="Investigate a change in web traffic.",+ body="# Triage\nDo the thing.",+ trust_tier=trust_tier,+ tags=["web-analytics"],+ install_count=install_count,+ deleted=deleted,+ )+++class TestCommunitySkillSync(APIBaseTest):+ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_upserts_and_soft_deletes_missing(self, mock_get) -> None:+ _create_community_skill(slug="stale-skill", install_count=3)++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "version": 1,+ "skills": [+ {+ "slug": "fresh-skill",+ "name": "Fresh skill",+ "description": "New one",+ "body": "# Fresh",+ "trust_tier": "community",+ "source_sha": "abc123",+ "files": [{"path": "ref.md", "content": "x"}],+ }+ ],+ }++ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 0, "removed": 1})++ fresh = CommunitySkill.objects.get(slug="fresh-skill")+ self.assertEqual(fresh.files.count(), 1)+ self.assertFalse(fresh.deleted)+ self.assertIsNotNone(fresh.published_at)++ self.assertTrue(CommunitySkill.objects.get(slug="stale-skill").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_skips_unchanged_sha(self, mock_get) -> None:+ existing = _create_community_skill(slug="web-analytics-triage")+ CommunitySkill.objects.filter(pk=existing.pk).update(source_sha="same-sha")++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {+ "slug": "web-analytics-triage",+ "name": "Web analytics triage",+ "description": "Investigate a change in web traffic.",+ "source_sha": "same-sha",+ }+ ],+ }++ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 0, "skipped": 1, "removed": 0})++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_empty_registry_does_not_wipe_catalog(self, mock_get) -> None:+ _create_community_skill(slug="keep-me")++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {"skills": []}++ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 0, "skipped": 0, "removed": 0})+ self.assertFalse(CommunitySkill.objects.get(slug="keep-me").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_skips_malformed_entry_but_still_reconciles(self, mock_get) -> None:+ _create_community_skill(slug="stale-skill")++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {"slug": "fresh-skill", "name": "Fresh skill", "description": "New one", "body": "# Fresh"},+ {"slug": "bad-skill"}, # missing required name/description+ ],+ }++ # One bad entry must not abort the loop or block the soft-delete of stale-skill.+ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 1, "removed": 1})+ self.assertTrue(CommunitySkill.objects.filter(slug="fresh-skill", deleted=False).exists())+ self.assertFalse(CommunitySkill.objects.filter(slug="bad-skill").exists())+ self.assertTrue(CommunitySkill.objects.get(slug="stale-skill").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_does_not_wipe_catalog_when_no_valid_slugs(self, mock_get) -> None:+ _create_community_skill(slug="keep-me")++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [{"name": "no slug here"}, {"foo": "bar"}],+ }++ # Non-empty registry that parses to zero valid slugs must not soft-delete everything.+ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 0, "skipped": 0, "removed": 0})+ self.assertFalse(CommunitySkill.objects.get(slug="keep-me").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_skips_oversized_entry(self, mock_get) -> None:+ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {+ "slug": "huge-skill",+ "name": "Huge skill",+ "description": "Too big",+ "body": "x" * (MAX_SKILL_BODY_BYTES + 1),+ }+ ],+ }++ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 0, "skipped": 1, "removed": 0})+ self.assertFalse(CommunitySkill.objects.filter(slug="huge-skill").exists())++ @parameterized.expand(+ [+ ("overlong_name", {"name": "n" * 65}),+ ("overlong_slug", {"slug": "s" * 65}),+ ("overlong_source_sha", {"source_sha": "s" * 65}),+ ("overlong_file_path", {"files": [{"path": "p" * 501, "content": "x"}]}),+ ("overlong_content_type", {"files": [{"path": "a.md", "content": "x", "content_type": "t" * 101}]}),+ (+ "duplicate_file_paths",+ {"files": [{"path": "ref.md", "content": "a"}, {"path": "ref.md", "content": "b"}]},+ ),+ ("non_string_body", {"body": {"nested": "object"}}),+ ("non_dict_file", {"files": ["not-a-dict"]}),+ # A non-string bounded field has a len(), so a length-only check would pass it and+ # CharField would persist its repr as the catalog's visible text.+ ("non_string_name", {"name": ["Bad", "skill"]}),+ ("non_string_source_sha", {"source_sha": {"sha": "abc"}}),+ # Falsy non-strings are the sharper case: an `or ""` fallback coerces them to "" for+ # the length check while the raw value is what reaches the column, so Char/TextField+ # persists "False" / "0" / "[]" as the catalog's visible text.+ ("false_name", {"name": False}),+ ("zero_description", {"description": 0}),+ ("empty_list_source_sha", {"source_sha": []}),+ ("non_string_content_type", {"files": [{"path": "a.md", "content": "x", "content_type": ["text/md"]}]}),+ ("falsy_non_string_content_type", {"files": [{"path": "a.md", "content": "x", "content_type": 0}]}),+ ("falsy_non_string_file_content", {"files": [{"path": "a.md", "content": False}]}),+ # A falsy non-list `files` normalized to [] would count as "no files" — the upsert+ # deletes the existing files first, so a live skill would lose its whole bundle.+ ("falsy_non_list_files", {"files": {}}),+ # Blank passes the type and length checks but leaves a nameless catalog card, and a+ # blank description is refused by marketplace.packaging.validate_for_export.+ ("blank_name", {"name": " "}),+ ("blank_description", {"description": ""}),+ # Case-only collisions break a case-insensitive filesystem, and the marketplace+ # tree-safety check drops the entire skill from the generated clone.+ (+ "case_only_duplicate_file_paths",+ {+ "files": [+ {"path": "references/Guide.md", "content": "a"},+ {"path": "references/guide.md", "content": "b"},+ ]+ },+ ),+ # `$` matches before a trailing newline, so a match-only check would let the newline+ # into the slug — the URL segment and the default installed-skill name.+ ("trailing_newline_slug", {"slug": "bad-skill\n"}),+ # Paths that would synthesize a corrupt git/export tree, rejected at ingest the same+ # way the skill create/import paths reject them.+ ("traversal_file_path", {"files": [{"path": "../secret", "content": "x"}]}),+ ("absolute_file_path", {"files": [{"path": "/etc/passwd", "content": "x"}]}),+ ("reserved_file_path", {"files": [{"path": "SKILL.md", "content": "x"}]}),+ (+ "backslash_duplicate_file_paths",+ {"files": [{"path": "ref/g.md", "content": "a"}, {"path": "ref\\g.md", "content": "b"}]},+ ),+ # Shape checks: a slug DRF can't route, or a mistyped metadata/tags/allowed_tools that+ # would 500 the list/detail render or fracture allowed-tools on export.+ ("non_routable_slug", {"slug": "triage.v2"}),+ ("scalar_metadata", {"metadata": 5}),+ ("non_list_tags", {"tags": 5}),+ ("whitespace_allowed_tool", {"allowed_tools": ["Bash Write"]}),+ ]+ )+ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_isolates_constraint_violating_entry(self, _name, bad_fields, mock_get) -> None:+ _create_community_skill(slug="stale-skill")+ bad_entry = {"slug": "bad-skill", "name": "Bad skill", "description": "Bad", "body": "# Bad", **bad_fields}++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {"slug": "fresh-skill", "name": "Fresh skill", "description": "New one", "body": "# Fresh"},+ bad_entry,+ ],+ }++ # An entry that would overflow a column, hit the unique file-path constraint, or be the+ # wrong shape (AttributeError) must be skipped without aborting the loop or blocking+ # reconciliation of the healthy entries.+ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 1, "removed": 1})+ self.assertTrue(CommunitySkill.objects.filter(slug="fresh-skill", deleted=False).exists())+ self.assertFalse(CommunitySkill.objects.filter(slug=bad_entry["slug"]).exists())+ self.assertTrue(CommunitySkill.objects.get(slug="stale-skill").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_does_not_wipe_catalog_when_all_slugged_entries_invalid(self, mock_get) -> None:+ _create_community_skill(slug="keep-me")++ mock_get.return_value.raise_for_status.return_value = None+ # Entry carries a slug but is otherwise malformed — it must not satisfy the reconciliation+ # safeguard on its own, or the whole catalog gets soft-deleted until a later good sync.+ mock_get.return_value.json.return_value = {"skills": [{"slug": "broken"}]}++ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 0, "skipped": 1, "removed": 0})+ self.assertFalse(CommunitySkill.objects.get(slug="keep-me").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_coerces_null_body_to_empty_string(self, mock_get) -> None:+ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [{"slug": "nullish", "name": "Nullish", "description": "Null body", "body": None}],+ }++ # A present-but-null body would violate the non-nullable TextField; coerce it to "" instead.+ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 0, "removed": 0})+ self.assertEqual(CommunitySkill.objects.get(slug="nullish").body, "")++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_coerces_null_collection_fields_to_empty(self, mock_get) -> None:+ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {+ "slug": "nullish",+ "name": "Nullish",+ "description": "Explicit nulls",+ "body": "# Nullish",+ "allowed_tools": None,+ "metadata": None,+ "tags": None,+ }+ ],+ }++ # An explicitly-null collection makes .get return None rather than the model default,+ # which these non-nullable JSON columns reject at insert time.+ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 0, "removed": 0})+ skill = CommunitySkill.objects.get(slug="nullish")+ self.assertEqual((skill.allowed_tools, skill.metadata, skill.tags), ([], {}, []))++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_survives_unhashable_slug(self, mock_get) -> None:+ _create_community_skill(slug="stale-skill")++ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {"slug": {"nested": "object"}, "name": "Unhashable", "description": "d", "body": "# b"},+ {"slug": "fresh-skill", "name": "Fresh skill", "description": "New one", "body": "# Fresh"},+ ],+ }++ # A truthy-but-unhashable slug is tracked in a set outside the per-entry boundary, so it+ # would raise TypeError and abort the sync before later entries or reconciliation ran.+ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 0, "removed": 1})+ self.assertTrue(CommunitySkill.objects.filter(slug="fresh-skill", deleted=False).exists())+ self.assertTrue(CommunitySkill.objects.get(slug="stale-skill").deleted)++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_lets_operational_database_errors_escape(self, mock_get) -> None:+ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [{"slug": "fresh-skill", "name": "Fresh skill", "description": "New one", "body": "# Fresh"}],+ }++ # A connection loss / failover / statement timeout is not one bad entry. Swallowing it+ # would report a successful sync (and skip reconciliation) while the catalog went stale.+ with patch(+ "products.skills.backend.api.community_skill_sync._upsert_community_skill",+ side_effect=OperationalError("server closed the connection unexpectedly"),+ ):+ with self.assertRaises(OperationalError):+ sync_community_skills_from_github()++ @patch("products.skills.backend.api.community_skill_sync.github_request")+ def test_sync_coerces_unknown_trust_tier_to_community(self, mock_get) -> None:+ mock_get.return_value.raise_for_status.return_value = None+ mock_get.return_value.json.return_value = {+ "skills": [+ {+ "slug": "shady-skill",+ "name": "Shady skill",+ "description": "Claims a bogus tier",+ "body": "# Shady",+ "trust_tier": "definitely-official",+ }+ ],+ }++ result = sync_community_skills_from_github()+ self.assertEqual(result, {"synced": 1, "skipped": 0, "removed": 0})+ self.assertEqual(CommunitySkill.objects.get(slug="shady-skill").trust_tier, "community")diff --git a/products/skills/backend/migrations/0005_communityskill.py b/products/skills/backend/migrations/0005_communityskill.pynew file mode 100644index 000000000000..4395802d4d65--- /dev/null+++ b/products/skills/backend/migrations/0005_communityskill.py@@ -0,0 +1,132 @@+import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("skills", "0004_llmskillowner"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="CommunitySkill",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("slug", models.CharField(max_length=64, unique=True)),+ ("name", models.CharField(max_length=64)),+ ("description", models.CharField(max_length=4096)),+ ("body", models.TextField()),+ ("license", models.CharField(blank=True, default="", max_length=255)),+ ("compatibility", models.CharField(blank=True, default="", max_length=500)),+ ("allowed_tools", models.JSONField(blank=True, default=list)),+ ("metadata", models.JSONField(blank=True, default=dict)),+ ("tags", models.JSONField(blank=True, default=list)),+ (+ "trust_tier",+ models.CharField(+ choices=[+ ("official", "Official"),+ ("verified", "Verified"),+ ("community", "Community"),+ ],+ default="community",+ max_length=20,+ ),+ ),+ ("author_handle", models.CharField(blank=True, default="", max_length=255)),+ ("github_url", models.CharField(blank=True, default="", max_length=8201)),+ ("source_sha", models.CharField(blank=True, default="", max_length=64)),+ ("install_count", models.PositiveIntegerField(default=0)),+ ("published_at", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("deleted", models.BooleanField(default=False)),+ ],+ options={+ "db_table": "llm_analytics_communityskill",+ },+ ),+ migrations.CreateModel(+ name="CommunitySkillFile",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("path", models.CharField(max_length=500)),+ ("content", models.TextField()),+ ("content_type", models.CharField(default="text/plain", max_length=100)),+ (+ "skill",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="files",+ to="skills.communityskill",+ ),+ ),+ ],+ options={+ "db_table": "llm_analytics_communityskillfile",+ },+ ),+ migrations.CreateModel(+ name="CommunitySkillVote",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ (+ "skill",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="votes",+ to="skills.communityskill",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "llm_analytics_communityskillvote",+ },+ ),+ migrations.AddConstraint(+ model_name="communityskillfile",+ constraint=models.UniqueConstraint(fields=("skill", "path"), name="unique_community_skill_file_path"),+ ),+ migrations.AddConstraint(+ model_name="communityskillvote",+ constraint=models.UniqueConstraint(fields=("skill", "user"), name="unique_community_skill_vote_per_user"),+ ),+ ]diff --git a/products/skills/backend/migrations/max_migration.txt b/products/skills/backend/migrations/max_migration.txtindex a6c09606e036..6d0a868709d6 100644--- a/products/skills/backend/migrations/max_migration.txt+++ b/products/skills/backend/migrations/max_migration.txt@@ -1 +1 @@-0004_llmskillowner+0005_communityskilldiff --git a/products/skills/backend/models/__init__.py b/products/skills/backend/models/__init__.pyindex f6f49966477a..72d8160b2aa3 100644--- a/products/skills/backend/models/__init__.py+++ b/products/skills/backend/models/__init__.py@@ -1,3 +1,12 @@+from .community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillTrustTier, CommunitySkillVotefrom .skills import LLMSkill, LLMSkillFile, LLMSkillOwner-__all__ = ["LLMSkill", "LLMSkillFile", "LLMSkillOwner"]+__all__ = [+ "CommunitySkill",+ "CommunitySkillFile",+ "CommunitySkillTrustTier",+ "CommunitySkillVote",+ "LLMSkill",+ "LLMSkillFile",+ "LLMSkillOwner",+]diff --git a/products/skills/backend/models/community_skills.py b/products/skills/backend/models/community_skills.pynew file mode 100644index 000000000000..1a857ae18edc--- /dev/null+++ b/products/skills/backend/models/community_skills.py@@ -0,0 +1,91 @@+from django.db import models+from django.utils import timezone++from posthog.models.utils import UUIDModel+++class CommunitySkillTrustTier(models.TextChoices):+ OFFICIAL = "official", "Official"+ VERIFIED = "verified", "Verified"+ COMMUNITY = "community", "Community"+++class CommunitySkill(UUIDModel):+ """Instance-global catalog of community-shared agent skills.++ The source of truth for skill content is the PostHog/community-skills GitHub repo;+ rows here are a synced read-model that powers in-app discovery, search, ranking, and+ install. This model is deliberately NOT team-scoped — it is shared catalog data (the+ same way DashboardTemplate GLOBAL templates are), so it has no team_id by design.+ Installing a community skill copies it into a team as a regular LLMSkill.+ """++ class Meta:+ db_table = "llm_analytics_communityskill"++ # The repo directory name — the stable, human-readable identifier used in URLs.+ slug = models.CharField(max_length=64, unique=True)++ # Mirrors the Agent Skills spec fields carried by LLMSkill.+ name = models.CharField(max_length=64)+ description = models.CharField(max_length=4096)+ body = models.TextField()+ license = models.CharField(max_length=255, blank=True, default="")+ compatibility = models.CharField(max_length=500, blank=True, default="")+ allowed_tools = models.JSONField(blank=True, default=list)+ metadata = models.JSONField(blank=True, default=dict)++ # Marketplace fields.+ tags = models.JSONField(blank=True, default=list)+ trust_tier = models.CharField(+ max_length=20,+ choices=CommunitySkillTrustTier.choices,+ default=CommunitySkillTrustTier.COMMUNITY,+ )+ author_handle = models.CharField(max_length=255, blank=True, default="")+ github_url = models.CharField(max_length=8201, blank=True, default="")+ # Commit SHA of the repo state this row was last synced from — lets the sync job skip unchanged skills.+ source_sha = models.CharField(max_length=64, blank=True, default="")+ # Denormalized install counter, incremented on each install. Strongest popularity signal.+ install_count = models.PositiveIntegerField(default=0)++ published_at = models.DateTimeField(null=True, blank=True)+ created_at = models.DateTimeField(default=timezone.now)+ updated_at = models.DateTimeField(auto_now=True)+ # Soft-delete for skills removed from the repo, so install history and votes survive.+ deleted = models.BooleanField(default=False)+++class CommunitySkillFile(UUIDModel):+ class Meta:+ db_table = "llm_analytics_communityskillfile"+ constraints = [+ models.UniqueConstraint(+ fields=["skill", "path"],+ name="unique_community_skill_file_path",+ ),+ ]++ skill = models.ForeignKey(CommunitySkill, on_delete=models.CASCADE, related_name="files")+ path = models.CharField(max_length=500)+ content = models.TextField()+ content_type = models.CharField(max_length=100, default="text/plain")+++class CommunitySkillVote(UUIDModel):+ """A single user's upvote of a community skill. User-scoped, not tenant data."""++ class Meta:+ db_table = "llm_analytics_communityskillvote"+ constraints = [+ models.UniqueConstraint(+ fields=["skill", "user"],+ name="unique_community_skill_vote_per_user",+ ),+ ]++ skill = models.ForeignKey(CommunitySkill, on_delete=models.CASCADE, related_name="votes")+ # db_constraint=False: posthog_user is a hot table — a real FK constraint takes a SHARE ROW+ # EXCLUSIVE lock on it at create time. Cascade is still enforced by the ORM collector.+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, db_constraint=False)+ created_at = models.DateTimeField(default=timezone.now)diff --git a/products/skills/backend/tasks.py b/products/skills/backend/tasks.pynew file mode 100644index 000000000000..aaa80d1c756a--- /dev/null+++ b/products/skills/backend/tasks.py@@ -0,0 +1,24 @@+from celery import shared_task+from structlog import get_logger++from posthog.scoping_audit import skip_team_scope_audit++from products.skills.backend.api.community_skill_sync import sync_community_skills_from_github++logger = get_logger(__name__)+++@shared_task(ignore_result=True)+@skip_team_scope_audit+def sync_community_skills() -> None:+ """Reconcile the local community-skills catalog with the PostHog/community-skills repo.++ Operates on the instance-global CommunitySkill catalog (no team scope), so the team-scope+ audit is intentionally skipped.+ """+ try:+ result = sync_community_skills_from_github()+ except Exception:+ logger.exception("community_skills_sync_failed")+ raise+ logger.info("community_skills_sync_complete", **result)diff --git a/tach.toml b/tach.tomlindex 8f1f8497d56e..4b378caace54 100644--- a/tach.toml+++ b/tach.toml@@ -119,6 +119,7 @@ depends_on = ["products.revenue_analytics","products.review_hog","products.signals",+ "products.skills","products.slack_app","products.stamphog","products.streamlit_apps",