: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(skills): stamp sha256 digests and byte sizes on skill content (#99975)
posthog[bot]47e4e7d19730
diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.pyindex 222f4ca4ead3..77bbeccfa26e 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -1,7 +1,7 @@from typing import Anyfrom django.db import transaction-from django.db.models import Value+from django.db.models import F, Valuefrom django.db.models.functions import Length, Replacefrom drf_spectacular.utils import extend_schema_field, extend_schema_serializer@@ -280,10 +280,18 @@ class LLMSkillFileSerializer(serializers.ModelSerializer):class LLMSkillFileManifestSerializer(serializers.ModelSerializer):line_count = serializers.IntegerField(help_text="Number of lines in the file content.")char_count = serializers.IntegerField(help_text="Number of characters in the file content.")+ size = serializers.IntegerField(+ allow_null=True,+ help_text="Size of the file content in bytes. Null on rows written before digests were stamped.",+ )+ sha256 = serializers.CharField(+ allow_null=True,+ help_text="Hex SHA-256 of the file content. Null on rows written before digests were stamped.",+ )class Meta:model = LLMSkillFile- fields = ["path", "content_type", "line_count", "char_count"]+ fields = ["path", "content_type", "line_count", "char_count", "size", "sha256"]class LLMSkillFileInputSerializer(serializers.Serializer):@@ -631,12 +639,17 @@ class LLMSkillSerializer(serializers.ModelSerializer):@extend_schema_field(LLMSkillFileManifestSerializer(many=True))def get_files(self, instance: LLMSkill) -> list[dict[str, Any]]:- # Counts are computed in the database so the manifest never fetches file contents.+ # Counts are computed in the database so the manifest never fetches file contents. The byte+ # size comes from the stamped column rather than a `Length()` count, which counts characters.annotated = LLMSkillFile.objects.filter(skill=instance).annotate(char_count=Length("content"),line_count=Length("content") - Length(Replace("content", Value("\n"))) + 1,+ size=F("content_size"),+ sha256=F("content_sha256"),)- return [dict(row) for row in annotated.values("path", "content_type", "line_count", "char_count")]+ return [+ dict(row) for row in annotated.values("path", "content_type", "line_count", "char_count", "size", "sha256")+ ]@extend_schema_field(LLMSkillOutlineEntrySerializer(many=True))def get_outline(self, instance: LLMSkill) -> list[dict[str, Any]]:diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex d75b247afaeb..4d7434a2afc1 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -1,6 +1,6 @@import refrom dataclasses import dataclass-from typing import Any+from typing import Any, TypeVarfrom django.db import IntegrityError, transactionfrom django.db.models import QuerySet@@ -19,10 +19,17 @@ from ..models.skills import (category_for_skill_name,)+_DigestModel = TypeVar("_DigestModel", LLMSkill, LLMSkillFile)+MAX_SKILL_VERSION = 2000MAX_SKILL_BODY_BYTES = 1_000_000MAX_SKILL_FILE_BYTES = 1_000_000MAX_SKILL_FILE_COUNT = 200+# A digest backfill page holds the full content of every row in it, because a digest cannot be+# computed without the content. One body or bundled file is allowed to reach MAX_SKILL_BODY_BYTES /+# MAX_SKILL_FILE_BYTES, so the page is sized against those caps rather than against a row count:+# 100 rows bounds a page at about 100 MB of content. Raise it with --batch-size for small rows.+DIGEST_BACKFILL_BATCH_SIZE = 100# Skill names that collide with reserved /skills routes and so can't be used: "new" is the create# form, and the rest mirror the category-tab slugs registered under /skills/<slug> in# products/skills/manifest.tsx — a skill with such a name would be shadowed by its tab route.@@ -738,26 +745,31 @@ def rename_skill(team: Team, *, skill_name: str, new_name: str) -> LLMSkill:raise LLMSkillRenameNotAllowedError(prefix=blocked_prefix)with transaction.atomic():- locked_version_ids = list(+ locked_versions = list(LLMSkill.objects.select_for_update().filter(team=team, name=skill_name, deleted=False).order_by("version", "created_at", "id")- .values_list("id", flat=True))- if not locked_version_ids:+ if not locked_versions:raise LLMSkillNotFoundError()if new_name == skill_name:return _renamed_skill_or_missing(team, new_name)if LLMSkill.objects.filter(team=team, name=new_name, deleted=False).exists():raise LLMSkillDuplicateNameConflictError()- # Bump updated_at (the .update() bypasses auto_now) so the marketplace plugin version,- # derived from max(updated_at) across all team rows, advances — a renamed skill changes- # the directory name in the exported tree, so installs must pick the rename up.- LLMSkill.objects.filter(team=team, name=skill_name, deleted=False).update(- name=new_name,- updated_at=timezone.now(),- )+ # Stamp each locked row rather than issuing one `.update()`: the name is the first+ # frontmatter key of the rendered SKILL.md, so a rename changes the bytes a host downloads,+ # and neither `.update()` nor `bulk_update` calls `save()` to restamp the digest. A stale+ # digest is invisible to the backfill, which only repairs rows that carry none.+ # `updated_at` is set by hand because both paths also bypass auto_now, and the marketplace+ # plugin version is max(updated_at) across all team rows: a renamed skill changes the+ # directory name in the exported tree, so installs must pick the rename up.+ renamed_at = timezone.now()+ for version in locked_versions:+ version.name = new_name+ version.updated_at = renamed_at+ version.stamp_digest()+ LLMSkill.objects.bulk_update(locked_versions, ["name", "updated_at", *LLMSkill.DIGEST_FIELDS])rename_skill_owners(team, skill_name, new_name)return _renamed_skill_or_missing(team, new_name)@@ -906,3 +918,44 @@ def set_skill_owners(team: Team, skill_name: str, users: list[User]) -> list[Use# write context-independent (works outside a request too)._owner_qs(team).create(team=team, skill_name=skill_name, user=user)return resolve_skill_owners(team, skill_name)+++@frozen+class SkillDigestBackfillCounts:+ skills: int+ files: int+++def backfill_skill_digests(+ *, batch_size: int = DIGEST_BACKFILL_BATCH_SIZE, recompute: bool = False+) -> SkillDigestBackfillCounts:+ """Stamp `sha256`/`size` on rows written before digests existed. Safe to re-run.++ Every write path stamps its own digest, so this only has to reach the history. It walks in+ primary-key order and writes fixed-size batches, so a team with a long skill history cannot+ pull the whole table into memory. `recompute` re-stamps rows that already carry a digest,+ for when the rendered form of a SKILL.md changes.+ """+ skills = LLMSkill.objects.all() if recompute else LLMSkill.objects.filter(skill_md_sha256__isnull=True)+ files = LLMSkillFile.objects.all() if recompute else LLMSkillFile.objects.filter(content_sha256__isnull=True)+ return SkillDigestBackfillCounts(+ skills=_backfill_digests(LLMSkill, skills, batch_size), files=_backfill_digests(LLMSkillFile, files, batch_size)+ )+++def _backfill_digests(model: type[_DigestModel], queryset: QuerySet[_DigestModel], batch_size: int) -> int:+ # Cursor on the primary key rather than re-running the "needs a digest" filter: under+ # `recompute` that filter matches every row, so a fixed `[:batch_size]` slice would never+ # advance and the walk would never end.+ cursor: Any = None+ stamped = 0+ while True:+ page = queryset.filter(pk__gt=cursor) if cursor is not None else queryset+ rows = list(page.order_by("pk")[:batch_size])+ if not rows:+ return stamped+ for row in rows:+ row.stamp_digest()+ model.objects.bulk_update(rows, list(model.DIGEST_FIELDS))+ stamped += len(rows)+ cursor = rows[-1].pkdiff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 7d97aab88f4d..6adfe1731144 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -1,4 +1,5 @@import uuid+import hashlibfrom datetime import timedeltafrom posthog.test.base import APIBaseTest@@ -33,7 +34,9 @@ from ...api.skill_serializers import ()from ...api.skill_services import (MAX_SKILL_FILE_COUNT,+ SkillDigestBackfillCounts,archive_skill,+ backfill_skill_digests,create_skill,publish_skill_version,resolve_skill_owners,@@ -652,16 +655,24 @@ class TestLLMSkillAPI(APIBaseTest):def test_get_skill_by_name_returns_file_manifest(self):skill = self.create_skill(name="with-files")LLMSkillFile.objects.create(skill=skill, path="scripts/setup.sh", content="#!/bin/bash\necho hi")- LLMSkillFile.objects.create(skill=skill, path="references/guide.md", content="# Guide")+ # Multibyte on purpose: the MCP Skills extension sizes a file in bytes, so a manifest that+ # reported the character count would understate this one and a host would reject the file.+ LLMSkillFile.objects.create(skill=skill, path="references/guide.md", content="# Guía ✅")response = self.client.get(self._url("name/with-files"))assert response.status_code == status.HTTP_200_OKfiles = response.json()["files"]assert len(files) == 2- manifest = {f["path"]: (f["line_count"], f["char_count"]) for f in files}- assert manifest["scripts/setup.sh"] == (2, len("#!/bin/bash\necho hi"))- assert manifest["references/guide.md"] == (1, len("# Guide"))+ manifest = {f["path"]: f for f in files}+ assert (manifest["scripts/setup.sh"]["line_count"], manifest["scripts/setup.sh"]["char_count"]) == (+ 2,+ len("#!/bin/bash\necho hi"),+ )+ guide = manifest["references/guide.md"]+ assert (guide["line_count"], guide["char_count"]) == (1, 8)+ assert guide["size"] == len("# Guía ✅".encode()) == 11+ assert guide["sha256"] == hashlib.sha256("# Guía ✅".encode()).hexdigest()def test_get_skill_not_found(self):response = self.client.get(self._url("name/nonexistent"))@@ -1243,6 +1254,12 @@ class TestLLMSkillAPI(APIBaseTest):v2.refresh_from_db()assert v2.updated_at > updated_at_beforeassert v1.name == "typo-free"+ # The name is the first frontmatter key of the rendered SKILL.md, so a digest left behind by+ # the rename describes bytes no version serves any more.+ for version in (v1, v2):+ rendered = version.rendered_skill_md().encode()+ assert version.skill_md_sha256 == hashlib.sha256(rendered).hexdigest()+ assert version.skill_md_size == len(rendered)def test_rename_to_an_existing_name_is_rejected(self):self.create_skill(name="source")@@ -2330,3 +2347,67 @@ class TestLLMSkillDescriptionCapSplit(SimpleTestCase):assert create_description.max_length == SPEC_DESCRIPTION_MAX_LENGTHassert detail_description.max_length == 4096assert list_description.max_length == 4096+++# Digests must land on every write path: a host that speaks the MCP Skills extension rejects+# content whose bytes disagree with the manifest.+class TestSkillContentDigests(APIBaseTest):+ def _digest_of(self, content: str) -> str:+ return hashlib.sha256(content.encode()).hexdigest()++ def test_create_and_publish_stamp_digests_on_the_skill_and_its_files(self):+ created = create_skill(+ self.team,+ user=self.user,+ name="digested",+ description="A skill",+ body="# Guía ✅",+ # A jsonb column keeps object keys sorted by length and then bytewise, so these come+ # back in neither the written order nor alphabetical order. The digest is stamped+ # before the insert, so it has to describe bytes that do not depend on that order.+ metadata={"seeded_by": "review_hog", "source": "products/skills", "nested": {"z": "1", "a": "2"}},+ files=[{"path": "references/guide.md", "content": "# Guía ✅"}],+ )++ # `create_skill` returns the stored row, which is what the store renders its SKILL.md from.+ assert created.skill_md_sha256 == self._digest_of(created.rendered_skill_md())+ assert created.skill_md_size == len(created.rendered_skill_md().encode())+ created_file = LLMSkillFile.objects.get(skill=created)+ assert created_file.content_sha256 == self._digest_of("# Guía ✅")+ assert created_file.content_size == 11++ # The publish path carries files forward with `bulk_create`, which never calls `save()`.+ published = publish_skill_version(+ self.team,+ user=self.user,+ skill_name="digested",+ body="# Changed ✅",+ base_version=1,+ )++ assert published.skill_md_sha256 == self._digest_of(published.rendered_skill_md())+ assert published.skill_md_sha256 != created.skill_md_sha256+ carried = LLMSkillFile.objects.get(skill=published)+ assert carried.content_sha256 == created_file.content_sha256+ assert carried.content_size == 11++ def test_backfill_stamps_legacy_rows_and_is_repeatable(self):+ skill = create_skill(self.team, user=self.user, name="legacy", description="A skill", body="# Body")+ LLMSkillFile.objects.create(skill=skill, path="notes.md", content="# Notes ✅")+ LLMSkill.objects.filter(pk=skill.pk).update(skill_md_sha256=None, skill_md_size=None)+ LLMSkillFile.objects.filter(skill=skill).update(content_sha256=None, content_size=None)++ first = backfill_skill_digests(batch_size=1)++ assert (first.skills, first.files) == (1, 1)+ skill.refresh_from_db()+ stamped_file = LLMSkillFile.objects.get(skill=skill)+ assert skill.skill_md_sha256 == self._digest_of(skill.rendered_skill_md())+ assert stamped_file.content_sha256 == self._digest_of("# Notes ✅")+ assert stamped_file.content_size == 11++ # A second run has nothing left to do, and forcing a recompute leaves the same values.+ assert backfill_skill_digests() == SkillDigestBackfillCounts(skills=0, files=0)+ assert backfill_skill_digests(batch_size=1, recompute=True) == SkillDigestBackfillCounts(skills=1, files=1)+ stamped_file.refresh_from_db()+ assert stamped_file.content_sha256 == self._digest_of("# Notes ✅")diff --git a/products/skills/backend/management/commands/backfill_skill_digests.py b/products/skills/backend/management/commands/backfill_skill_digests.pynew file mode 100644index 000000000000..e89177178324--- /dev/null+++ b/products/skills/backend/management/commands/backfill_skill_digests.py@@ -0,0 +1,26 @@+from typing import Any++from django.core.management.base import BaseCommand, CommandParser++from products.skills.backend.api.skill_services import DIGEST_BACKFILL_BATCH_SIZE, backfill_skill_digests+++class Command(BaseCommand):+ help = "Stamp SHA-256 digests and byte sizes on skill rows written before digests existed."++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument(+ "--batch-size",+ type=int,+ default=DIGEST_BACKFILL_BATCH_SIZE,+ help="Rows written per batch (default: %(default)s).",+ )+ parser.add_argument(+ "--recompute",+ action="store_true",+ help="Re-stamp rows that already carry a digest.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ counts = backfill_skill_digests(batch_size=options["batch_size"], recompute=options["recompute"])+ self.stdout.write(f"skills={counts.skills} files={counts.files}")diff --git a/products/skills/backend/marketplace/adapters.py b/products/skills/backend/marketplace/adapters.pyindex 2b73cfeb27f9..7bfede063c88 100644--- a/products/skills/backend/marketplace/adapters.py+++ b/products/skills/backend/marketplace/adapters.py@@ -27,7 +27,6 @@ from .packaging import (MAX_BUNDLE_SKILLS,SPEC_DESCRIPTION_MAX_LENGTH,SkillExport,- SkillFileExport,SkillStub,archive_entry_bytes,build_marketplace_tree,@@ -89,23 +88,9 @@ def sandbox_skills_flag_distinct_id(user: User) -> str:_SKIPPED_LOG_SAMPLE_SIZE = 20-def skill_to_export(skill: LLMSkill, files: list[LLMSkillFile]) -> SkillExport:- return SkillExport(- name=skill.name,- description=skill.description,- body=skill.body,- version=skill.version,- license=skill.license or "",- compatibility=skill.compatibility or "",- allowed_tools=list(skill.allowed_tools or []),- metadata=dict(skill.metadata or {}),- files=[SkillFileExport(path=f.path, content=f.content, content_type=f.content_type) for f in files],- )--def load_skill_export(skill: LLMSkill) -> SkillExport:files = list(LLMSkillFile.objects.filter(skill=skill).order_by("path"))- return skill_to_export(skill, files)+ return skill.to_export(files)def synthesize_team_marketplace_repo(team: Team) -> SynthesizedRepo:@@ -163,7 +148,7 @@ def build_team_marketplace_tree(team: Team, version: str | None = None) -> FileTskipped_oversize.append(skill.name)continuetotal_bytes += skill_bytes- exports.append(skill_to_export(skill, files))+ exports.append(skill.to_export(files))if skipped_unsafe:logger.warning("skills_marketplace_skipped_unsafe_skills", team_id=team.id, skills=skipped_unsafe)if skipped_oversize:@@ -502,7 +487,7 @@ def _walk_full(candidates: QuerySet[LLMSkill], limit: int) -> _BundleWalk:# it either, so it is neither included, skipped nor dropped.continuefiles = list(LLMSkillFile.objects.filter(skill=skill).order_by("path"))- export = skill_to_export(skill, files)+ export = skill.to_export(files)if validate_for_export(export):skipped_count = _record_skip(skipped_count, skipped_sample, name)continuediff --git a/products/skills/backend/marketplace/packaging.py b/products/skills/backend/marketplace/packaging.pyindex 3f8aa1711e70..7867db9f7cb8 100644--- a/products/skills/backend/marketplace/packaging.py+++ b/products/skills/backend/marketplace/packaging.py@@ -15,9 +15,11 @@ the spec serialization and tree assembly unit-testable without booting the app.import ioimport reimport json+import hashlibimport zipfileimport mimetypesfrom dataclasses import dataclass, field+from typing import Anyimport yaml@@ -72,6 +74,19 @@ class SkillExport:files: list[SkillFileExport] = field(default_factory=list)+def _key_sorted(value: Any) -> Any:+ """The same value with every object's keys in sorted order, at every depth.++ Sorted by the string form of the key, which is what the renderer writes out. List order is+ left alone, because a JSON array is ordered and storage keeps it that way.+ """+ if isinstance(value, dict):+ return {key: _key_sorted(value[key]) for key in sorted(value, key=str)}+ if isinstance(value, list):+ return [_key_sorted(item) for item in value]+ return value++def render_frontmatter(skill: SkillExport) -> str:"""Serialize a skill's spec fields as a YAML frontmatter block (with delimiters).@@ -87,7 +102,12 @@ def render_frontmatter(skill: SkillExport) -> str:# Spec metadata is a string->string map. Stored metadata first, then the platform version# last so it always wins — a user-stored metadata["version"] must not clobber the real one.- metadata: dict[str, str] = {str(k): str(v) for k, v in skill.metadata.items()}+ # The keys are sorted because the digest of this file is stamped from the in-memory row before+ # the insert, while every later render reads the value back out of a `jsonb` column, which+ # keeps object keys sorted by length and then bytewise. Rendering in whatever order the dict+ # carries would make the two describe different bytes, which is what a verifying host rejects.+ # The sort goes to every depth, because a nested object reaches the frontmatter through `str`.+ metadata: dict[str, str] = {str(k): str(v) for k, v in _key_sorted(skill.metadata).items()}metadata["version"] = str(skill.version)document["metadata"] = metadata@@ -102,6 +122,16 @@ def render_skill_md(skill: SkillExport) -> str:return render_frontmatter(skill) + "\n" + skill.body+def utf8_digest(content: str) -> tuple[str, int]:+ """Return the bare hex SHA-256 and the byte length of ``content`` encoded as UTF-8.++ Bytes, not characters: the MCP Skills extension makes a host reject any file whose bytes do not+ match the reported digest and size, so one multibyte character must count as its several bytes.+ """+ encoded = content.encode("utf-8")+ return hashlib.sha256(encoded).hexdigest(), len(encoded)++@dataclass(frozen=True)class SkillStub:"""The discovery half of a skill: enough for a harness to list and invoke it by name."""diff --git a/products/skills/backend/migrations/0009_llmskill_skill_md_sha256_llmskill_skill_md_size_and_more.py b/products/skills/backend/migrations/0009_llmskill_skill_md_sha256_llmskill_skill_md_size_and_more.pynew file mode 100644index 000000000000..68db57b2e79a--- /dev/null+++ b/products/skills/backend/migrations/0009_llmskill_skill_md_sha256_llmskill_skill_md_size_and_more.py@@ -0,0 +1,32 @@+# Generated by Django 5.2.17 on 2026-09-14 08:43++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("skills", "0008_alter_communityskillvote_user_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="llmskill",+ name="skill_md_sha256",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ migrations.AddField(+ model_name="llmskill",+ name="skill_md_size",+ field=models.PositiveIntegerField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="llmskillfile",+ name="content_sha256",+ field=models.CharField(blank=True, max_length=64, null=True),+ ),+ migrations.AddField(+ model_name="llmskillfile",+ name="content_size",+ field=models.PositiveIntegerField(blank=True, null=True),+ ),+ ]diff --git a/products/skills/backend/migrations/max_migration.txt b/products/skills/backend/migrations/max_migration.txtindex 9e91a633a690..6451863f7b93 100644--- a/products/skills/backend/migrations/max_migration.txt+++ b/products/skills/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_alter_communityskillvote_user_and_more+0009_llmskill_skill_md_sha256_llmskill_skill_md_size_and_morediff --git a/products/skills/backend/models/skills.py b/products/skills/backend/models/skills.pyindex 2d7cc3e4d8af..13c11785ea5f 100644--- a/products/skills/backend/models/skills.py+++ b/products/skills/backend/models/skills.py@@ -1,3 +1,5 @@+from typing import Any+from django.db import modelsfrom django.db.models import Count, DateTimeField, IntegerField, OuterRef, Q, QuerySet, Subqueryfrom django.utils import timezone@@ -5,6 +7,8 @@ from django.utils import timezonefrom posthog.models.scoping.manager import TeamScopedManagerfrom posthog.models.utils import UUIDModel+from ..marketplace.packaging import SkillExport, SkillFileExport, render_skill_md, utf8_digest+# Server-owned grouping stamped on every create path (REST serializer, MCP tool, import): the Skills# page's category tabs (SKILL_CATEGORY_TABS in llmSkillsLogic.ts) filter on `category`, and the# generic create flows are how custom scouts and review-hog skills are authored — without the stamp@@ -21,6 +25,22 @@ def category_for_skill_name(name: str) -> str:return next((category for prefix, category in CATEGORY_BY_NAME_PREFIX if name.startswith(prefix)), "")+class SkillDigestManager(models.Manager):+ """Manager that stamps content digests on ``bulk_create``, which never calls ``save()``.++ The store has many write paths — create, publish, duplicate, import, community install, and the+ per-file add/delete/rename — and every one of them must leave a digest behind, because a host+ that speaks the MCP Skills extension rejects content whose bytes disagree with the manifest.+ Stamping on the model rather than at each call site means a write path added later cannot forget.+ """++ def bulk_create(self, objs: Any, *args: Any, **kwargs: Any) -> Any:+ objs = list(objs)+ for obj in objs:+ obj.stamp_digest()+ return super().bulk_create(objs, *args, **kwargs)++class LLMSkill(UUIDModel):class Meta:db_table = "llm_analytics_llmskill"@@ -64,8 +84,9 @@ class LLMSkill(UUIDModel):# Versioning (same pattern as LLMPrompt)version = models.PositiveIntegerField(default=1)- is_latest = models.BooleanField(default=True)version_description = models.CharField(max_length=400, null=True, blank=True)+ is_latest = models.BooleanField(default=True)+ deleted = models.BooleanField(default=False)team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+")@@ -73,7 +94,48 @@ class LLMSkill(UUIDModel):created_at = models.DateTimeField(default=timezone.now)updated_at = models.DateTimeField(auto_now=True)- deleted = models.BooleanField(default=False)+ # Digest of the *rendered* SKILL.md (frontmatter + body), not of `body` alone: the manifest+ # describes the file a host downloads, and that file carries the frontmatter too. Bare hex,+ # without the `sha256:` prefix the spec puts on the wire — the MCP resource layer adds it. Nullable+ # until the backfill has run everywhere; new writes always stamp it.+ skill_md_sha256 = models.CharField(max_length=64, null=True, blank=True)+ skill_md_size = models.PositiveIntegerField(null=True, blank=True)++ DIGEST_FIELDS = ("skill_md_sha256", "skill_md_size")++ objects = SkillDigestManager()++ def to_export(self, files: "list[LLMSkillFile] | None" = None) -> SkillExport:+ """Map this row onto the Django-free spec dataclass. The one storage -> spec mapping.++ The digest below and the exported artifact must describe the same bytes, so they cannot+ each carry their own copy of this mapping — a spec field added to one and not the other+ would make every host reject the file it downloads.+ """+ return SkillExport(+ name=self.name,+ description=self.description,+ body=self.body,+ version=self.version,+ license=self.license or "",+ compatibility=self.compatibility or "",+ allowed_tools=list(self.allowed_tools or []),+ metadata=dict(self.metadata or {}),+ files=[SkillFileExport(path=f.path, content=f.content, content_type=f.content_type) for f in files or []],+ )++ def rendered_skill_md(self) -> str:+ return render_skill_md(self.to_export())++ def stamp_digest(self) -> None:+ self.skill_md_sha256, self.skill_md_size = utf8_digest(self.rendered_skill_md())++ def save(self, *args: Any, update_fields: Any = None, **kwargs: Any) -> None:+ self.stamp_digest()+ # A narrowed write would otherwise leave the old digest next to the new content.+ if update_fields is not None:+ update_fields = [*update_fields, *self.DIGEST_FIELDS]+ super().save(*args, update_fields=update_fields, **kwargs)class LLMSkillFile(UUIDModel):@@ -91,6 +153,23 @@ class LLMSkillFile(UUIDModel):content = models.TextField()content_type = models.CharField(max_length=100, default="text/plain")+ # See `LLMSkill.skill_md_sha256` for the storage shape and the nullability window.+ content_sha256 = models.CharField(max_length=64, null=True, blank=True)+ content_size = models.PositiveIntegerField(null=True, blank=True)++ DIGEST_FIELDS = ("content_sha256", "content_size")++ objects = SkillDigestManager()++ def stamp_digest(self) -> None:+ self.content_sha256, self.content_size = utf8_digest(self.content)++ def save(self, *args: Any, update_fields: Any = None, **kwargs: Any) -> None:+ self.stamp_digest()+ if update_fields is not None:+ update_fields = [*update_fields, *self.DIGEST_FIELDS]+ super().save(*args, update_fields=update_fields, **kwargs)+class LLMSkillOwner(UUIDModel):"""A human who owns a skill, keyed on the *logical* skill `(team, name)` — not a version row.diff --git a/products/skills/frontend/LLMSkillScene.stories.tsx b/products/skills/frontend/LLMSkillScene.stories.tsxindex 16f073009d68..356f5d3507a6 100644--- a/products/skills/frontend/LLMSkillScene.stories.tsx+++ b/products/skills/frontend/LLMSkillScene.stories.tsx@@ -75,8 +75,22 @@ const SKILL: LLMSkillApi = {metadata: {},category: '',files: [- { path: 'scripts/extract.sh', content_type: 'text/x-shellscript', line_count: 24, char_count: 512 },- { path: 'references/pdf-spec.md', content_type: 'text/markdown', line_count: 120, char_count: 4096 },+ {+ path: 'scripts/extract.sh',+ content_type: 'text/x-shellscript',+ line_count: 24,+ char_count: 512,+ size: 512,+ sha256: 'a'.repeat(64),+ },+ {+ path: 'references/pdf-spec.md',+ content_type: 'text/markdown',+ line_count: 120,+ char_count: 4096,+ size: 4098,+ sha256: 'b'.repeat(64),+ },],outline: [{ level: 1, text: 'PDF extractor' },diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex 1c33fc2ecdf2..0396dd252f02 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -244,6 +244,16 @@ export interface LLMSkillFileManifestApi {line_count: number/** Number of characters in the file content. */char_count: number+ /**+ * Size of the file content in bytes. Null on rows written before digests were stamped.+ * @nullable+ */+ size: number | null+ /**+ * Hex SHA-256 of the file content. Null on rows written before digests were stamped.+ * @nullable+ */+ sha256: string | null}export interface LLMSkillOutlineEntryApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 04bf4fe7c793..6cbae3cd6d06 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49307,6 +49307,16 @@ export namespace Schemas {line_count: number;/** Number of characters in the file content. */char_count: number;+ /**+ * Size of the file content in bytes. Null on rows written before digests were stamped.+ * @nullable+ */+ size: number | null;+ /**+ * Hex SHA-256 of the file content. Null on rows written before digests were stamped.+ * @nullable+ */+ sha256: string | null;}export interface LLMSkillOutlineEntry {