: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(agent_platform): pin store skills into agent bundles via skill_refs (#65838)
Danilo Campos422890232bfa
diff --git a/products/agent_platform/backend/logic/skill_resolution.py b/products/agent_platform/backend/logic/skill_resolution.pynew file mode 100644index 000000000000..5434712b49e0--- /dev/null+++ b/products/agent_platform/backend/logic/skill_resolution.py@@ -0,0 +1,152 @@+"""Resolve a draft revision's skill references against the llma-skill store.++A draft revision can reference versioned skills in the store via+``AgentRevision.skill_refs`` — each entry is ``{from_template, alias, version?}``+where ``from_template`` is the store skill *name* (human-readable, stable across+versions) and ``version`` optionally pins a specific published version.++At freeze the references are resolved to their pinned bytes and materialized+into the bundle (``skills/<alias>/SKILL.md`` + companions) so a frozen revision+never re-resolves a possibly-changed skill at runtime. Resolution happens here,+in Django, because the store lives in the main DB the janitor cannot reach; the+resolved files are pushed into the bundle through the existing janitor proxy.+"""++from dataclasses import dataclass++from rest_framework.exceptions import PermissionDenied, ValidationError++from posthog.models import Team+from posthog.rbac.user_access_control import UserAccessControl++from products.skills.backend.api.skill_services import get_skill_by_name_from_db+from products.skills.backend.marketplace.adapters import load_skill_export+from products.skills.backend.marketplace.packaging import render_skill_md, validate_for_export+++@dataclass(frozen=True)+class ResolvedSkill:+ """A store skill resolved to its bundle-ready form plus freeze provenance."""++ alias: str+ # `body` is the *rendered* SKILL.md (frontmatter + body) so the janitor's+ # freeze-time `deriveSkillDescription` reads the curated `description:` from+ # frontmatter rather than falling back to the first prose line.+ body: str+ files: list[dict[str, str]]+ description: str+ # Provenance stamped onto the frozen SkillRef. `from_template` is the+ # human-readable name; `source_version_id` is the immutable per-version row+ # UUID — a readable reference plus an exact anchor.+ from_template: str+ version: int+ source_version_id: str++ def put_skill_payload(self) -> dict:+ """The body for the janitor `PUT /revisions/:id/skills/:alias` call."""+ return {"description": self.description, "body": self.body, "files": self.files}+++def assert_skill_refs_readable(+ team: Team,+ refs: list[dict],+ *,+ scopes: list[str] | None,+ user_access_control: UserAccessControl,+) -> None:+ """Authorize the caller to read every referenced store skill before it can be+ materialized into a bundle.++ Freeze and ``set_skill_refs`` pull ``llm_skill`` content into the agent+ bundle, which is then readable through the ``agents:read`` bundle APIs. So+ they must honour the same boundary ``LLMSkillViewSet`` enforces: the+ ``llm_skill:read`` API scope for token callers, plus object-level access+ control for everyone. Without this an ``agents:write`` token (or an+ RBAC-restricted user) could exfiltrate a private skill by freezing it into a+ bundle and reading it back. ``scopes`` is ``None`` for session auth, which+ carries no API scopes and is governed solely by object-level access control.+ """+ names: list[str] = []+ for ref in refs:+ name = ref.get("from_template")+ if isinstance(name, str) and name and name not in names:+ names.append(name)+ if not names:+ return+ # Cross-resource API-scope check for token callers (personal API key / OAuth).+ if scopes is not None and not ({"*", "llm_skill:read", "llm_skill:write"} & set(scopes)):+ raise PermissionDenied(+ "Referencing skill store skills requires the `llm_skill:read` scope in addition to `agents:write`."+ )+ # Object-level access control, mirroring LLMSkillViewSet's AccessControlPermission.+ # A missing skill is left to resolve_skill_ref to reject loudly at freeze.+ for name in names:+ skill = get_skill_by_name_from_db(team, name)+ if skill is not None and not user_access_control.check_access_level_for_object(skill, "viewer"):+ raise PermissionDenied(+ f"You do not have read access to the skill '{name}' in the skill store. Ask a skill admin to "+ "share it with you, or remove it from the agent's skill references."+ )+++def resolve_skill_ref(team: Team, ref: dict) -> ResolvedSkill:+ """Resolve one ``{from_template, alias, version?}`` ref to a ``ResolvedSkill``.++ Fails loud (``ValidationError``) on a malformed ref, a missing/deleted+ pinned version, or a skill that isn't export-ready under the Agent Skills+ spec — freeze must never silently ship an empty or partial skill.+ """+ name = ref.get("from_template")+ alias = ref.get("alias")+ version = ref.get("version")+ # `source_version_id` is the immutable per-version row UUID a prior freeze+ # stamped back onto the ref. When present it pins the exact version row —+ # the truly immortal anchor — so a forked re-freeze can't drift to "latest".+ source_version_id = ref.get("source_version_id")+ if not name or not alias:+ known = alias or name+ label = f" '{known}'" if known else ""+ raise ValidationError(f"A skill reference{label} is missing its required 'from_template' or 'alias'.")+ if version is not None and not isinstance(version, int):+ raise ValidationError(f"Skill reference '{alias}' has a non-integer version: {version!r}")++ # A pinned `source_version_id` targets one immutable version row — resolve it+ # even if the skill was later archived, so the pin stays the immortal anchor.+ skill = get_skill_by_name_from_db(team, name, version, source_version_id, include_archived=bool(source_version_id))+ if skill is None:+ pinned = (+ f" {source_version_id}" if source_version_id else f" v{version}" if version is not None else " (latest)"+ )+ raise ValidationError(f"Skill '{name}'{pinned} referenced by '{alias}' was not found in the store.")++ export = load_skill_export(skill)+ problems = validate_for_export(export)+ if problems:+ raise ValidationError(+ f"Skill '{name}' v{skill.version} referenced by '{alias}' is not export-ready: {'; '.join(problems)}"+ )++ return ResolvedSkill(+ alias=alias,+ body=render_skill_md(export),+ files=[{"path": f.path, "content": f.content} for f in export.files],+ description=export.description,+ from_template=name,+ version=skill.version,+ source_version_id=str(skill.id),+ )+++def stamp_skill_provenance(derived_spec: dict, provenance_by_alias: dict[str, dict]) -> None:+ """Merge freeze provenance onto the derived SkillRefs, matching by id == alias.++ The janitor derives content-based skill refs (``{id, path, description}``)+ where ``id`` is the bundle folder name — i.e. the alias we materialized the+ skill under. This stamps ``from_template``/``version``/``source_version_id``+ back on so the frozen spec records each store-sourced skill's provenance.+ Mutates ``derived_spec`` in place.+ """+ for skill in derived_spec.get("skills") or []:+ prov = provenance_by_alias.get(skill.get("id"))+ if prov:+ skill.update(prov)diff --git a/products/agent_platform/backend/logic/spec_schema.py b/products/agent_platform/backend/logic/spec_schema.pyindex 50ed28194303..62ab00fe1c1e 100644--- a/products/agent_platform/backend/logic/spec_schema.py+++ b/products/agent_platform/backend/logic/spec_schema.py@@ -310,7 +310,7 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {"kind": {"type": "string", "const": "custom_template"},"from_template": {"type": "string"},"alias": {"type": "string"},- "version": {"type": "integer", "minimum": 0},+ "version": {"type": "integer", "minimum": 1},},"required": ["kind", "from_template", "alias"],"additionalProperties": False,@@ -416,10 +416,15 @@ _AGENT_SPEC_JSON_SCHEMA_RAW: dict[str, Any] = {"description": {"type": "string"},# Registry lineage for a skill pinned from a template.# Present on a draft spec; freeze resolves `from_template`,- # assembles `skills/<alias>/SKILL.md`, and stamps id/path.+ # assembles `skills/<alias>/SKILL.md`, and stamps id/path ++ # `source_version_id`. Allowed here so a forked frozen spec+ # (which carries the stamped provenance) round-trips through+ # the write path — authors can't set skills[] regardless, the+ # serializer pins it to the server value."from_template": {"type": "string"},"alias": {"type": "string"},- "version": {"type": "integer", "minimum": 0},+ "version": {"type": "integer", "minimum": 1},+ "source_version_id": {"type": "string"},},"required": ["id", "path"],"additionalProperties": False,diff --git a/products/agent_platform/backend/migrations/0011_agentrevision_skill_refs.py b/products/agent_platform/backend/migrations/0011_agentrevision_skill_refs.pynew file mode 100644index 000000000000..c5420ad19356--- /dev/null+++ b/products/agent_platform/backend/migrations/0011_agentrevision_skill_refs.py@@ -0,0 +1,19 @@+# Draft skill references on a revision. Additive nullable-default JSONB column+# on the agent_platform product DB (not a hot table) — `db_default` lands a real+# Postgres default so non-Django writers and the test-schema path stay happy.++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("agent_platform", "0010_remove_is_preview_state_only"),+ ]++ operations = [+ migrations.AddField(+ model_name="agentrevision",+ name="skill_refs",+ field=models.JSONField(db_default=models.Value("[]"), default=list),+ ),+ ]diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txtindex 6f2720731c92..16ae82e58b3d 100644--- a/products/agent_platform/backend/migrations/max_migration.txt+++ b/products/agent_platform/backend/migrations/max_migration.txt@@ -1 +1 @@-0010_remove_is_preview_state_only+0011_agentrevision_skill_refsdiff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.pyindex 1de9d814f08f..a01661c709ca 100644--- a/products/agent_platform/backend/models.py+++ b/products/agent_platform/backend/models.py@@ -127,6 +127,15 @@ class AgentRevision(ProductTeamModel, UUIDModel):spec = models.JSONField(default=dict)+ # Draft references to versioned skills in the llma-skill store. Each entry+ # is {from_template, alias, version?}. Freeze resolves them against the+ # store at the pinned version, materializes the skill (SKILL.md + any+ # companion files) into the bundle under skills/<alias>/, and stamps+ # provenance onto the frozen spec — so a frozen revision never re-resolves a+ # possibly-changed skill at runtime. Authoring-time only; carried forward+ # when a new draft is forked from a parent.+ skill_refs = models.JSONField(default=list, db_default=Value("[]"))+# Encrypted JSON env block — the secret values this revision runs with.# Decrypted at runtime by the worker via `EncryptedFields` (see# services/agent-shared/src/runtime/encryption.ts). Lives on the revisiondiff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.pyindex b7aae38376de..42a8117c2f3b 100644--- a/products/agent_platform/backend/presentation/serializers.py+++ b/products/agent_platform/backend/presentation/serializers.py@@ -13,6 +13,7 @@ import secretsfrom typing import Anyfrom django.conf import settings+from django.core.validators import RegexValidatorfrom django.db import IntegrityErrorimport jsonschema@@ -250,8 +251,70 @@ class AgentSpecField(serializers.JSONField):opaque `{}`."""+# Bound the number of skill references on a revision so freeze (one store fetch ++# one janitor write per ref) can't fan out without limit. Enforced both at+# `set_skill_refs` and again at freeze (refs can reach the column via fork / raw write).+MAX_SKILL_REFS = 50+++class SkillRefSerializer(serializers.Serializer):+ """One reference to a versioned skill in the llma-skill store, pinned into+ this agent's bundle at freeze."""++ from_template = serializers.CharField(+ # Mirrors the store's `LLMSkill.name` max_length so an unresolvable,+ # oversized name can't be persisted into the JSON column.+ max_length=64,+ help_text=(+ "Name of the skill in the llma-skill store to pin into this agent. "+ "Resolved at freeze to the chosen `version` and materialized into the bundle."+ ),+ )+ alias = serializers.CharField(+ max_length=64,+ validators=[+ RegexValidator(+ r"^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$",+ message="alias must be lowercase letters, digits, hyphens or underscores, and must start "+ "and end with a letter or digit.",+ )+ ],+ help_text=(+ "Folder the resolved skill is materialized under in the bundle (`skills/<alias>/`). "+ "Lowercase letters, digits, hyphens or underscores, starting and ending with a letter or digit; "+ "must be unique within the revision."+ ),+ )+ version = serializers.IntegerField(+ required=False,+ min_value=1,+ help_text="Specific published version to pin. Omit to pin the store's latest version at freeze time.",+ )+++class SetSkillRefsRequestSerializer(serializers.Serializer):+ """Body for PUT /revisions/<id>/skill_refs/ — full-replace the draft's references."""++ skill_refs = SkillRefSerializer(+ many=True,+ # `many=True` builds a ListSerializer, which accepts max_length to bound the+ # list — drf-stubs types the call against the child and misses the kwarg.+ max_length=MAX_SKILL_REFS, # type: ignore[call-arg]+ help_text="The complete set of store-skill references for this draft; replaces any existing references.",+ )++class AgentRevisionSerializer(serializers.ModelSerializer):spec = AgentSpecField(required=False, default=dict)+ skill_refs = SkillRefSerializer(+ many=True,+ read_only=True,+ help_text=(+ "Store-skill references for this draft, set via the `skill_refs` action and resolved into the "+ "bundle at freeze. Preserved as the authoring record on the frozen revision (and carried forward "+ "when forking a new draft); resolved provenance is stamped onto `spec.skills[].source_version_id`."+ ),+ )created_by = serializers.SerializerMethodField(help_text="Resolved creator (id, first_name, email) from `created_by_id`, or null if unset or the user was deleted.",)@@ -261,6 +324,15 @@ class AgentRevisionSerializer(serializers.ModelSerializer):return _resolve_created_by(self.context, obj.created_by_id)def validate_spec(self, value: Any) -> Any:+ # `skills[]` is server-derived — resolved from `skill_refs` and stamped+ # with provenance at freeze, never author-authored. Pin it to the existing+ # server value (empty on create) so an author spec edit can neither change+ # which skills materialize nor forge `source_version_id` to defeat the+ # freeze legacy guard. `new_draft`/`clone_from` set spec on the model+ # directly (not via this serializer), so a fork's carried skills survive.+ if isinstance(value, dict):+ existing = getattr(self.instance, "spec", None)+ value["skills"] = existing.get("skills", []) if isinstance(existing, dict) else []# Same shape the janitor's `AgentSpecSchema.parse` will reject on# read. Catching it here turns a future 500 / process-level surprise# into a clean 400 at write time.@@ -282,18 +354,21 @@ class AgentRevisionSerializer(serializers.ModelSerializer):"bundle_uri","bundle_sha256","spec",+ "skill_refs","created_by_id","created_by","created_at","updated_at",]# state transitions happen through promote / archive actions; spec is- # mutable only while state='draft' (enforced in the view).+ # mutable only while state='draft' (enforced in the view). skill_refs is+ # set through the dedicated `skill_refs` action, not this serializer.read_only_fields = ["id","application","state","bundle_sha256",+ "skill_refs","created_by_id","created_at","updated_at",@@ -362,22 +437,6 @@ class WriteSpecRequestSerializer(serializers.Serializer):spec = serializers.DictField(child=serializers.JSONField())-class WriteSkillRequestSerializer(serializers.Serializer):- """Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored- at the canonical `skills/<skill_id>/SKILL.md` path in the bundle."""-- description = serializers.CharField(- allow_blank=False,- trim_whitespace=False,- help_text="One-line summary shown in the skill index; the model uses it to decide when to load the skill.",- )- body = serializers.CharField(- allow_blank=True,- trim_whitespace=False,- help_text="The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`.",- )--class WriteToolRequestSerializer(serializers.Serializer):"""Body shape for PUT /revisions/<id>/tools/<tool_id>/."""@@ -388,30 +447,24 @@ class WriteToolRequestSerializer(serializers.Serializer):class WriteTypedBundleRequestSerializer(serializers.Serializer):"""Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed- payload."""+ payload. Skills are not authored here: they come from the llma-skill store+ via `skill_refs` and are materialized into the bundle at freeze."""agent_md = serializers.CharField(allow_blank=True, trim_whitespace=False)- skills = serializers.ListField(child=WriteSkillRequestSerializer(), required=False, default=list)tools = serializers.ListField(child=WriteToolRequestSerializer(), required=False, default=list)spec = serializers.DictField(child=serializers.JSONField())def to_internal_value(self, data: dict) -> dict:- """Skill / tool items carry an `id` field that the nested serializer- doesn't declare (it lives in the URL for the single-resource PUTs).- Stash + restore so the per-item validation still passes."""- skills = data.get("skills", [])+ """Tool items carry an `id` field that the nested serializer doesn't+ declare (it lives in the URL for the single-resource PUTs). Stash ++ restore so the per-item validation still passes."""tools = data.get("tools", [])- skill_ids = [s.get("id") for s in skills]tool_ids = [t.get("id") for t in tools]- # Strip ids so the inner serializers don't complain about unknowns.stripped = {**data,- "skills": [{k: v for k, v in s.items() if k != "id"} for s in skills],"tools": [{k: v for k, v in t.items() if k != "id"} for t in tools],}out = super().to_internal_value(stripped)- # Reattach ids — janitor wants them.- out["skills"] = [{**s, "id": skill_ids[i]} for i, s in enumerate(out.get("skills", []))]out["tools"] = [{**t, "id": tool_ids[i]} for i, t in enumerate(out.get("tools", []))]return outdiff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex 85acdbe870d2..6eac46560845 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -67,15 +67,18 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.helpers.encrypted_fields import EncryptedTextFieldfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User+from posthog.permissions import get_authenticator_scopesfrom posthog.security.outbound_proxy import internal_requestsfrom ..db import WRITER_DBfrom ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwtfrom ..logic.janitor_client import JanitorClient, JanitorClientError, default_clientfrom ..logic.posthog_identity_app import provision_posthog_identity_apps+from ..logic.skill_resolution import assert_skill_refs_readable, resolve_skill_ref, stamp_skill_provenancefrom ..logic.spec_schema import missing_required_secretsfrom ..models import AgentApplication, AgentIdentityCredential, AgentRevisionfrom .serializers import (+ MAX_SKILL_REFS,AgentApplicationSerializer,AgentRevisionSerializer,CloneFromRequestSerializer,@@ -85,8 +88,8 @@ from .serializers import (PromoteRevisionRequestSerializer,SetEnvKeyRequestSerializer,SetEnvRequestSerializer,+ SetSkillRefsRequestSerializer,WriteAgentMdRequestSerializer,- WriteSkillRequestSerializer,WriteSpecRequestSerializer,WriteToolRequestSerializer,WriteTypedBundleRequestSerializer,@@ -183,6 +186,25 @@ class JanitorUpstreamError(APIException):super().__init__(detail=detail_str)+# Skill folder aliases the janitor recognizes (mirrors the `skills/<id>/` id regex+# in agent-janitor's typed-bundle.ts). Used to keep the freeze sweep set identical+# to the set the janitor derives as skills.+_SKILL_ALIAS_RE = re.compile(r"^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$")+++def _is_sealed_bundle_conflict(e: JanitorClientError) -> bool:+ """True when a janitor edit was refused because the bundle is already sealed.++ The janitor returns 409 `revision_not_draft` from any authoring edit once the+ `.frozen` marker exists. During freeze that means a prior attempt sealed the+ bundle but its HTTP response was lost — the materialization is already done, so+ we skip ahead to the idempotent freeze rather than failing the retry.+ """+ if e.status_code != 409:+ return False+ return isinstance(e.body, dict) and e.body.get("error") == "revision_not_draft"++# The `log_source` tag the agent runner stamps on every log_entries row.# Mirrors `AGENT_SESSION_LOG_SOURCE` in services/agent-shared/src/runtime/# log-sink.ts — keep both sides in sync.@@ -1622,8 +1644,7 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"put_bundle","put_agent_md","put_spec",- "put_skill",- "delete_skill",+ "set_skill_refs","put_tool","delete_tool","cron_fire",@@ -2040,19 +2061,46 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):body.is_valid(raise_exception=True)return Response(self._call(_janitor().put_spec, str(revision.id), body.validated_data["spec"]))- @extend_schema(request=WriteSkillRequestSerializer)- @action(detail=True, methods=["put"], url_path=r"skills/(?P<skill_id>[a-z0-9][a-z0-9_-]*)")- def put_skill(self, request: Request, skill_id: str, **kwargs) -> Response:+ @extend_schema(request=SetSkillRefsRequestSerializer, responses={200: AgentRevisionSerializer})+ @action(detail=True, methods=["put"], url_path="skill_refs")+ def set_skill_refs(self, request: Request, **kwargs) -> Response:+ """Full-replace the draft's store-skill references. They are resolved+ and materialized into the bundle at freeze, not here — this only records+ which skills (and pinned versions) the freeze should pull in."""revision: AgentRevision = self.get_object()- body = WriteSkillRequestSerializer(data=request.data)+ if revision.state != "draft":+ raise ValidationError(+ f"Cannot set skill references on a {revision.state} revision; only 'draft' is mutable."+ )+ body = SetSkillRefsRequestSerializer(data=request.data)body.is_valid(raise_exception=True)- return Response(self._call(_janitor().put_skill, str(revision.id), skill_id, body.validated_data))-- @extend_schema(request=None)- @put_skill.mapping.delete- def delete_skill(self, request: Request, skill_id: str, **kwargs) -> Response:- revision: AgentRevision = self.get_object()- return Response(self._call(_janitor().delete_skill, str(revision.id), skill_id))+ refs = body.validated_data["skill_refs"]+ aliases = [r["alias"] for r in refs]+ if len(set(aliases)) != len(aliases):+ raise ValidationError("Each skill reference must have a unique 'alias' within the revision.")+ # Same skill-read authorization the freeze enforces — surfaced early here+ # so an author setting refs gets the 403 at write time, not at freeze.+ assert_skill_refs_readable(+ self.team,+ [dict(r) for r in refs],+ scopes=get_authenticator_scopes(getattr(request, "successful_authenticator", None)),+ user_access_control=self.user_access_control,+ )+ # Lock the row and re-check state before writing: a concurrent freeze+ # could have sealed the bundle and flipped this revision to `ready`+ # between our first read and this write — writing `skill_refs` onto a+ # frozen revision would leave the column describing skills the sealed+ # bundle doesn't contain.+ with transaction.atomic(using=WRITER_DB):+ locked = AgentRevision.all_teams.using(WRITER_DB).select_for_update().get(pk=revision.pk)+ if locked.state != "draft":+ raise ValidationError(+ f"Cannot set skill references on a {locked.state} revision; only 'draft' is mutable."+ )+ locked.skill_refs = [dict(r) for r in refs]+ locked.save(update_fields=["skill_refs"])+ revision.refresh_from_db()+ return Response(AgentRevisionSerializer(revision).data)@extend_schema(request=WriteToolRequestSerializer)@action(detail=True, methods=["put"], url_path=r"tools/(?P<tool_id>[a-z0-9][a-z0-9_-]*)")@@ -2262,20 +2310,132 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# promote path doesn't expect. Mirrors the `update()` non-draft guard.if revision.state != "draft":raise ValidationError(f"Cannot freeze a {revision.state} revision; only 'draft' can be frozen.")+ skill_refs = revision.skill_refs or []+ # Re-bound the ref count here too: the serializer cap only guards+ # `set_skill_refs`, but refs reach the column via fork / raw write, and each+ # ref is one store fetch + one janitor round-trip, all sequential.+ if len(skill_refs) > MAX_SKILL_REFS:+ raise ValidationError(f"A revision may reference at most {MAX_SKILL_REFS} store skills.")+ # Authorize skill reads before materializing any store content into the+ # bundle — refs can reach the column via fork or raw write, so the+ # `set_skill_refs` check alone isn't enough. (Confused-deputy guard:+ # `agents:write` must not become a backdoor read of private skills.)+ assert_skill_refs_readable(+ self.team,+ skill_refs,+ scopes=get_authenticator_scopes(getattr(request, "successful_authenticator", None)),+ user_access_control=self.user_access_control,+ )janitor_client = _janitor()- # Skill / custom-tool template pinning (freeze_templates_into_bundle) is- # disabled pending a registry rethink — see the commented-out template- # routes in routes.py.+ # Resolve every draft skill reference against the llma-skill store at its+ # pinned version, then materialize each into the bundle (SKILL.md ++ # companions) BEFORE sealing — so a frozen revision carries the exact+ # skill bytes and never re-resolves a possibly-changed skill at runtime.+ # Resolution is pure (no side effects) and runs to completion first, so a+ # missing/un-exportable/duplicate-alias ref fails the freeze before any+ # bundle write, never leaving the draft half-materialized. Alias+ # uniqueness is re-checked here because refs can reach the column via fork+ # or raw write, bypassing the `skill_refs` endpoint's validation.+ # (Custom-tool template pinning stays disabled pending a registry rethink+ # — see the commented-out template routes in routes.py.)+ resolved_skills = [resolve_skill_ref(self.team, ref) for ref in skill_refs]+ aliases = {r.alias for r in resolved_skills}+ if len(aliases) != len(resolved_skills):+ raise ValidationError("Each skill reference must have a unique 'alias' within the revision.")+ provenance_by_alias: dict[str, dict] = {+ r.alias: {"from_template": r.from_template, "version": r.version, "source_version_id": r.source_version_id}+ for r in resolved_skills+ }+ # Migration guard for pre-store agents: a revision forked from one authored+ # before the store became canonical carries inline skill entries in its+ # spec with no store provenance. Discriminate on `source_version_id`, NOT+ # `from_template`: `from_template` is author-writable on a draft spec (via+ # partial_update), so trusting it lets an author spoof provenance and make+ # the sweep silently drop the inline content this guard protects.+ # `source_version_id` is only ever server-stamped at freeze and is rejected+ # by the write spec schema (`additionalProperties: false`), so it can't be+ # forged. Detect from the spec (stable record) not the bundle, so a folder+ # left by a failed prior freeze — absent from the spec — is swept on retry+ # rather than misclassified as legacy. An unreferenced inline skill is+ # refused: silently dropping it would lose real content.+ legacy_orphans = sorted(+ sid+ for s in ((revision.spec or {}).get("skills") or [])+ if (sid := s.get("id")) and not s.get("source_version_id") and sid not in aliases+ )+ if legacy_orphans:+ raise ValidationError(+ f"Revision carries inline skill(s) {legacy_orphans} not backed by a store reference "+ "(authored before the skill store became canonical). Recreate them in the skill store and set "+ "`skill_refs` before freezing — otherwise the freeze would silently drop them."+ )+ # Materialize the resolved refs into the bundle, then seal. Skills are+ # store-only — nothing else writes `skills/` — so the frozen bundle must+ # hold exactly the current refs: sweep any folder not in `aliases`, then+ # (re-)write each resolved skill. This whole block is skipped if a prior+ # freeze already sealed the bundle (its HTTP response was lost): the+ # janitor refuses edits to a sealed bundle, and its `freeze` is idempotent+ # — it re-derives the sha + spec from what's already sealed.+ try:+ manifest = janitor_client.manifest(str(revision.id))+ # Only `skills/<alias>/<file>` paths whose alias matches the janitor's+ # skill-id regex count — keeps Django's sweep set identical to the set+ # the janitor derives as skills, so a stray `skills/README.md` can't be+ # misread as an alias.+ bundle_aliases = {+ parts[1]+ for f in manifest.get("files", [])+ if len(parts := f["path"].split("/")) >= 3 and parts[0] == "skills" and _SKILL_ALIAS_RE.match(parts[1])+ }+ # Write the resolved skills BEFORE sweeping leftovers: a failure+ # mid-flight then leaves the bundle with extra folders, never missing a+ # current ref, and a retry is a clean full replace. Sweeping first would+ # leave a window where the draft has neither the old nor the new skill.+ for resolved in resolved_skills:+ janitor_client.put_skill(str(revision.id), resolved.alias, resolved.put_skill_payload())+ for stale in bundle_aliases - aliases:+ try:+ janitor_client.delete_skill(str(revision.id), stale)+ except JanitorClientError as e:+ # A folder with no `SKILL.md` (e.g. companion-only cruft) 404s on+ # delete — it isn't a skill the janitor will remove, so treat it+ # as already-swept rather than re-failing the freeze every retry.+ if e.status_code != 404:+ raise+ except JanitorClientError as e:+ # A 409 from an edit means the bundle is already sealed — fall through+ # to the idempotent freeze below. Any other error is a real failure.+ if not _is_sealed_bundle_conflict(e):+ raise JanitorUpstreamError(e) from eresult = self._call(janitor_client.freeze, str(revision.id))- revision.state = "ready"- revision.bundle_sha256 = result["bundle_sha256"]+ # Pin resolved versions back into `skill_refs` so an unpinned ref becomes a+ # concrete pin after its first freeze. A fork copies `skill_refs` verbatim,+ # so without this an unpinned ref would re-resolve "latest" on the fork's+ # freeze — drifting away from the bytes the parent shipped. `source_version_id`+ # makes the pin immortal (resolve_skill_ref prefers it over `version`).+ pinned_refs = [+ {**ref, "version": r.version, "source_version_id": r.source_version_id}+ for ref, r in zip(skill_refs, resolved_skills)+ ]+ fields: dict[str, Any] = {+ "state": "ready",+ "bundle_sha256": result["bundle_sha256"],+ "skill_refs": pinned_refs,+ }derived_spec = result.get("derived_spec")if derived_spec is not None:- revision.spec = derived_spec- revision.save(update_fields=["state", "bundle_sha256", "spec"])- else:- revision.save(update_fields=["state", "bundle_sha256"])- revision.refresh_from_db()+ stamp_skill_provenance(derived_spec, provenance_by_alias)+ fields["spec"] = derived_spec+ # Conditional draft→ready flip: only the first freeze of a draft wins, so+ # two concurrent freezes can't both stamp the row, and a `set_skill_refs`+ # that raced in can't leave `skill_refs` describing skills the sealed+ # bundle doesn't contain (this write reasserts the materialized set).+ updated = AgentRevision.all_teams.filter(pk=revision.pk, state="draft").update(**fields)+ # Read back from the writer: a replica read under lag could still show+ # `draft` right after our UPDATE and trip the conflict check below.+ revision.refresh_from_db(using=WRITER_DB)+ if not updated and revision.state not in ("ready", "live"):+ raise ValidationError(f"Revision is in state '{revision.state}'; only a 'draft' can be frozen.")return Response({**result,@@ -2327,6 +2487,9 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):state="draft",bundle_uri=source.bundle_uri, # same bundle root; janitor scopes by revision_idspec=source.spec,+ # Carry store-skill references forward so a forked draft keeps (and can+ # re-resolve / re-pin) the same skills — they're the only skill source.+ skill_refs=source.skill_refs,# Secrets are per-revision: carry the parent's encrypted env forward# so the author isn't forced to re-enter every secret on each new# draft. The ciphertext copies verbatim (same EncryptedFields keydiff --git a/products/agent_platform/backend/tests/test_freeze_skill_refs.py b/products/agent_platform/backend/tests/test_freeze_skill_refs.pynew file mode 100644index 000000000000..daa4f3f206cf--- /dev/null+++ b/products/agent_platform/backend/tests/test_freeze_skill_refs.py@@ -0,0 +1,390 @@+from __future__ import annotations++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from rest_framework.test import APIClient++from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.skills.backend.models.skills import LLMSkill, LLMSkillFile++from ..logic.janitor_client import JanitorClientError+from ..models import AgentApplication, AgentRevision+++class TestFreezeResolvesSkillRefs(APIBaseTest):+ databases = {+ "default",+ "persons_db_writer",+ "persons_db_reader",+ "agent_platform_db_writer",+ "agent_platform_db_reader",+ }++ def setUp(self) -> None:+ super().setUp()+ self.skill = LLMSkill.objects.create(+ team=self.team,+ name="triage-helper",+ description="Decide which inbound tickets need a human.",+ body="The triage body.",+ )+ LLMSkillFile.objects.create(skill=self.skill, path="references/api.md", content="# API")+ self.application = AgentApplication.all_teams.create(+ team_id=self.team.id, slug="freeze-agent", name="Freeze agent", description=""+ )+ self.revision = AgentRevision.all_teams.create(+ application=self.application,+ spec={"model": "x", "triggers": []},+ skill_refs=[{"from_template": "triage-helper", "alias": "triage"}],+ state="draft",+ bundle_uri="fs://test/",+ )+ self.url = (+ f"/api/projects/{self.team.id}/agent_applications/{self.application.id}"+ f"/revisions/{self.revision.id}/freeze/"+ )++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_materializes_skill_and_stamps_provenance(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.manifest.return_value = {"files": [{"path": "agent.md"}]}+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "triage", "path": "skills/triage/SKILL.md", "description": "d"}],+ "tools": [],+ },+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)++ # The store skill was materialized into the bundle via the janitor with+ # the rendered SKILL.md (frontmatter + body) and its companion file.+ client.put_skill.assert_called_once()+ call_rev, call_alias, payload = client.put_skill.call_args.args+ self.assertEqual(call_rev, str(self.revision.id))+ self.assertEqual(call_alias, "triage")+ self.assertIn("name: triage-helper", payload["body"])+ self.assertIn("The triage body.", payload["body"])+ self.assertEqual(payload["files"], [{"path": "references/api.md", "content": "# API"}])++ # The frozen spec records provenance back to the pinned store version.+ self.revision.refresh_from_db()+ frozen_skill = self.revision.spec["skills"][0]+ self.assertEqual(frozen_skill["from_template"], "triage-helper")+ self.assertEqual(frozen_skill["version"], 1)+ self.assertEqual(frozen_skill["source_version_id"], str(self.skill.id))+ self.assertEqual(self.revision.state, "ready")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_fails_loud_on_missing_skill(self, mock_janitor: MagicMock) -> None:+ self.revision.skill_refs = [{"from_template": "ghost", "alias": "g"}]+ self.revision.save(update_fields=["skill_refs"])++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 400, res.content)+ mock_janitor.return_value.freeze.assert_not_called()+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "draft")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_sweeps_stale_skill_aliases(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ # A prior freeze materialized `skills/old/` from a store ref (its carried+ # spec entry keeps server-stamped `source_version_id` provenance); the+ # author has since dropped it from refs, leaving just `triage`, so `old`+ # must be swept.+ self.revision.spec = {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "old", "path": "skills/old/SKILL.md", "source_version_id": "019e0000-0000-0000"}],+ }+ self.revision.save(update_fields=["spec"])+ client.manifest.return_value = {+ "files": [{"path": "agent.md"}, {"path": "skills/old/SKILL.md"}, {"path": "skills/triage/SKILL.md"}]+ }+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {"model": "x", "triggers": [], "skills": [], "tools": []},+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ client.delete_skill.assert_called_once_with(str(self.revision.id), "old")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_fails_loud_on_legacy_inline_skill(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ # Models a pre-store agent forked + re-frozen: the carried spec lists an+ # inline skill with no `from_template` provenance and no backing ref. The+ # freeze must refuse rather than silently strip it. (Detected from the+ # spec, the stable authoring record — not the volatile bundle.)+ self.revision.skill_refs = []+ self.revision.spec = {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "legacy", "path": "skills/legacy/SKILL.md"}],+ }+ self.revision.save(update_fields=["skill_refs", "spec"])++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 400, res.content)+ self.assertIn("legacy", str(res.content))+ # Fail loud BEFORE any destructive janitor call or seal.+ client.delete_skill.assert_not_called()+ client.freeze.assert_not_called()+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "draft")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_legacy_guard_not_bypassed_by_spoofed_from_template(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.delete_skill = MagicMock(return_value={"ok": True})+ # `from_template` is author-writable on a draft spec, so an attacker could+ # add a fake one to a legacy inline entry to slip it past the guard and have+ # the sweep silently drop it. The discriminant is the server-only+ # `source_version_id`, which the write schema rejects — so the spoof still+ # refuses.+ self.revision.skill_refs = []+ self.revision.spec = {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "legacy", "path": "skills/legacy/SKILL.md", "from_template": "spoofed"}],+ }+ self.revision.save(update_fields=["skill_refs", "spec"])++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 400, res.content)+ self.assertIn("legacy", str(res.content))+ client.delete_skill.assert_not_called()+ client.freeze.assert_not_called()++ @property+ def _detail_url(self) -> str:+ return f"/api/projects/{self.team.id}/agent_applications/{self.application.id}/revisions/{self.revision.id}/"++ def test_spec_write_preserves_server_skills_and_round_trips_source_version_id(self) -> None:+ # A forked draft carries server-derived skills[] (with the stamped, write-schema+ # -rejected `source_version_id`). Editing an unrelated spec field must NOT 400,+ # and an author can't change/spoof skills[] — it's pinned to the server value.+ self.revision.spec = {+ "model": "faux/old",+ "triggers": [],+ "skills": [{"id": "triage", "path": "skills/triage/SKILL.md", "source_version_id": "019e-real"}],+ }+ self.revision.save(update_fields=["spec"])++ res = self.client.patch(+ self._detail_url,+ {+ "spec": {+ "model": "faux/new",+ "triggers": [],+ # Author attempt to inject/spoof a skill — must be ignored.+ "skills": [{"id": "evil", "path": "skills/evil/SKILL.md", "source_version_id": "019e-fake"}],+ }+ },+ format="json",+ )+ self.assertEqual(res.status_code, 200, res.content)+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.spec["model"], "faux/new")+ # skills[] is the preserved server value, not the author's spoof.+ self.assertEqual([s["id"] for s in self.revision.spec["skills"]], ["triage"])+ self.assertEqual(self.revision.spec["skills"][0]["source_version_id"], "019e-real")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_tolerates_404_when_sweeping_a_skill_md_less_folder(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ # A stale companion-only folder has no SKILL.md, so the janitor 404s on delete.+ # The sweep must treat that as already-gone, not wedge the freeze.+ client.delete_skill = MagicMock(side_effect=JanitorClientError(404, "skill_not_found", body={}))+ client.manifest.return_value = {+ "files": [{"path": "skills/triage/SKILL.md"}, {"path": "skills/ghost/references/x.md"}]+ }+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {"model": "x", "triggers": [], "skills": [], "tools": []},+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ client.delete_skill.assert_called_once_with(str(self.revision.id), "ghost")+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "ready")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_pins_unpinned_ref_version_back_into_skill_refs(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ client.manifest.return_value = {"files": [{"path": "agent.md"}]}+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {"model": "x", "triggers": [], "skills": [], "tools": []},+ }+ # The default ref omits `version` (tracks latest). After freeze the row's+ # skill_refs must carry the resolved version + source_version_id so a fork+ # inherits a concrete pin instead of re-resolving latest.+ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ self.revision.refresh_from_db()+ pinned = self.revision.skill_refs[0]+ self.assertEqual(pinned["from_template"], "triage-helper")+ self.assertEqual(pinned["version"], self.skill.version)+ self.assertEqual(pinned["source_version_id"], str(self.skill.id))++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_sweeps_leftover_folder_without_misclassifying_as_legacy(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ client.put_skill = MagicMock(return_value={"ok": True})+ client.delete_skill = MagicMock(return_value={"ok": True})+ # A `skills/leftover/` folder from a prior *failed* freeze is in the bundle+ # but NOT in the spec (the failed attempt never saved derived_spec). It must+ # be swept on retry, not misclassified as a legacy inline skill and refused.+ client.manifest.return_value = {+ "files": [{"path": "agent.md"}, {"path": "skills/leftover/SKILL.md"}, {"path": "skills/triage/SKILL.md"}]+ }+ client.freeze.return_value = {+ "bundle_sha256": "a" * 64,+ "derived_spec": {"model": "x", "triggers": [], "skills": [], "tools": []},+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ client.delete_skill.assert_called_once_with(str(self.revision.id), "leftover")+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "ready")++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_short_circuits_on_already_sealed_bundle(self, mock_janitor: MagicMock) -> None:+ client = mock_janitor.return_value+ # A prior freeze sealed the bundle but its HTTP response was lost; the row+ # is still draft. On retry, the janitor refuses edits (409 revision_not_draft)+ # — freeze must skip materialization and stamp from the idempotent freeze.+ client.manifest.return_value = {"files": [{"path": "skills/triage/SKILL.md"}]}+ client.delete_skill = MagicMock(return_value={"ok": True})+ client.put_skill = MagicMock(+ side_effect=JanitorClientError(409, "sealed", body={"error": "revision_not_draft", "state": "ready"})+ )+ client.freeze.return_value = {+ "bundle_sha256": "b" * 64,+ "idempotent": True,+ "derived_spec": {+ "model": "x",+ "triggers": [],+ "skills": [{"id": "triage", "path": "skills/triage/SKILL.md", "description": "d"}],+ "tools": [],+ },+ }++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 200, res.content)+ client.freeze.assert_called_once_with(str(self.revision.id))+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "ready")+ self.assertEqual(self.revision.bundle_sha256, "b" * 64)++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_freeze_rejects_more_than_max_skill_refs(self, mock_janitor: MagicMock) -> None:+ # The serializer caps refs at 50, but fork / raw write can smuggle more into+ # the column — freeze must re-bound the count before fanning out.+ self.revision.skill_refs = [{"from_template": "triage-helper", "alias": f"a{i}"} for i in range(51)]+ self.revision.save(update_fields=["skill_refs"])++ res = self.client.post(self.url)+ self.assertEqual(res.status_code, 400, res.content)+ mock_janitor.return_value.freeze.assert_not_called()+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "draft")++ @property+ def _skill_refs_url(self) -> str:+ return (+ f"/api/projects/{self.team.id}/agent_applications/{self.application.id}"+ f"/revisions/{self.revision.id}/skill_refs/"+ )++ def test_set_skill_refs_replaces_the_list(self) -> None:+ res = self.client.put(+ self._skill_refs_url,+ {+ "skill_refs": [+ {"from_template": "triage-helper", "alias": "a"},+ {"from_template": "triage-helper", "alias": "b", "version": 2},+ ]+ },+ format="json",+ )+ self.assertEqual(res.status_code, 200, res.content)+ self.revision.refresh_from_db()+ self.assertEqual([r["alias"] for r in self.revision.skill_refs], ["a", "b"])+ self.assertEqual(self.revision.skill_refs[1]["version"], 2)++ def test_set_skill_refs_rejects_duplicate_alias(self) -> None:+ res = self.client.put(+ self._skill_refs_url,+ {"skill_refs": [{"from_template": "x", "alias": "dup"}, {"from_template": "y", "alias": "dup"}]},+ format="json",+ )+ self.assertEqual(res.status_code, 400, res.content)++ def test_set_skill_refs_blocked_on_non_draft(self) -> None:+ self.revision.state = "ready"+ self.revision.save(update_fields=["state"])+ res = self.client.put(+ self._skill_refs_url,+ {"skill_refs": [{"from_template": "triage-helper", "alias": "a"}]},+ format="json",+ )+ self.assertEqual(res.status_code, 400, res.content)++ def _bearer_client(self, scopes: list[str]) -> APIClient:+ raw = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="agent-key", user=self.user, secure_value=hash_key_value(raw), scopes=scopes+ )+ client = APIClient() # no session — only the Bearer token authenticates+ client.credentials(HTTP_AUTHORIZATION=f"Bearer {raw}")+ return client++ def test_freeze_denied_for_token_without_llm_skill_read(self) -> None:+ # A token with agents:write but no llm_skill:read must not be able to+ # materialize (and thus read) store-skill content via the bundle.+ client = self._bearer_client(["agents:read", "agents:write"])+ res = client.post(self.url)+ self.assertEqual(res.status_code, 403, res.content)+ self.revision.refresh_from_db()+ self.assertEqual(self.revision.state, "draft")++ def test_set_skill_refs_denied_for_token_without_llm_skill_read(self) -> None:+ client = self._bearer_client(["agents:read", "agents:write"])+ res = client.put(+ self._skill_refs_url,+ {"skill_refs": [{"from_template": "triage-helper", "alias": "a"}]},+ format="json",+ )+ self.assertEqual(res.status_code, 403, res.content)++ def test_set_skill_refs_allowed_for_token_with_llm_skill_read(self) -> None:+ client = self._bearer_client(["agents:read", "agents:write", "llm_skill:read"])+ res = client.put(+ self._skill_refs_url,+ {"skill_refs": [{"from_template": "triage-helper", "alias": "a"}]},+ format="json",+ )+ self.assertEqual(res.status_code, 200, res.content)+ self.revision.refresh_from_db()+ self.assertEqual([r["alias"] for r in self.revision.skill_refs], ["a"])diff --git a/products/agent_platform/backend/tests/test_skill_resolution.py b/products/agent_platform/backend/tests/test_skill_resolution.pynew file mode 100644index 000000000000..e18bd6504dd4--- /dev/null+++ b/products/agent_platform/backend/tests/test_skill_resolution.py@@ -0,0 +1,85 @@+from posthog.test.base import BaseTest++from rest_framework.exceptions import ValidationError++from products.agent_platform.backend.logic.skill_resolution import resolve_skill_ref, stamp_skill_provenance+from products.skills.backend.models.skills import LLMSkill, LLMSkillFile+++class TestResolveSkillRef(BaseTest):+ def _make_skill(self, name="triage-helper", version=1, is_latest=True, body="Body text here.", files=None):+ skill = LLMSkill.objects.create(+ team=self.team,+ name=name,+ description="Decide which inbound tickets need a human.",+ body=body,+ version=version,+ is_latest=is_latest,+ )+ for path, content in (files or {}).items():+ LLMSkillFile.objects.create(skill=skill, path=path, content=content)+ return skill++ def test_resolves_latest_with_rendered_frontmatter_and_companions(self):+ skill = self._make_skill(files={"references/api.md": "# API\nsee here"})++ resolved = resolve_skill_ref(self.team, {"from_template": "triage-helper", "alias": "triage"})++ self.assertEqual(resolved.alias, "triage")+ # body is the *rendered* SKILL.md so the janitor reads the frontmatter+ # description, not the first prose line.+ self.assertIn("name: triage-helper", resolved.body)+ self.assertIn("Decide which inbound tickets need a human.", resolved.body)+ self.assertIn("Body text here.", resolved.body)+ self.assertEqual(resolved.files, [{"path": "references/api.md", "content": "# API\nsee here"}])+ self.assertEqual(resolved.version, 1)+ self.assertEqual(resolved.source_version_id, str(skill.id))++ def test_pins_specific_version_not_latest(self):+ self._make_skill(name="pinned", version=1, is_latest=False, body="v1 body")+ self._make_skill(name="pinned", version=2, is_latest=True, body="v2 body")++ resolved = resolve_skill_ref(self.team, {"from_template": "pinned", "alias": "p", "version": 1})++ self.assertEqual(resolved.version, 1)+ self.assertIn("v1 body", resolved.body)++ def test_source_version_id_pin_resolves_even_when_archived(self):+ # A pinned version stays the immortal anchor: archiving the skill (soft-delete)+ # must not break a fork's re-freeze against the exact version it shipped.+ skill = self._make_skill(name="archived-skill", body="pinned body")+ skill_id = str(skill.id)+ LLMSkill.objects.filter(id=skill.id).update(deleted=True)++ resolved = resolve_skill_ref(+ self.team,+ {"from_template": "archived-skill", "alias": "a", "source_version_id": skill_id},+ )+ self.assertEqual(resolved.source_version_id, skill_id)+ self.assertIn("pinned body", resolved.body)++ def test_archived_skill_without_pin_fails_loud(self):+ # Without a source_version_id pin, an archived skill is gone (resolves latest).+ skill = self._make_skill(name="gone", body="x")+ LLMSkill.objects.filter(id=skill.id).update(deleted=True)+ with self.assertRaises(ValidationError):+ resolve_skill_ref(self.team, {"from_template": "gone", "alias": "g"})++ def test_missing_skill_fails_loud(self):+ with self.assertRaises(ValidationError):+ resolve_skill_ref(self.team, {"from_template": "does-not-exist", "alias": "x"})++ def test_malformed_ref_fails_loud(self):+ with self.assertRaises(ValidationError):+ resolve_skill_ref(self.team, {"alias": "x"})++ def test_stamp_provenance_matches_by_alias(self):+ derived_spec = {"skills": [{"id": "triage", "path": "skills/triage/SKILL.md", "description": "d"}]}+ stamp_skill_provenance(+ derived_spec,+ {"triage": {"from_template": "triage-helper", "version": 3, "source_version_id": "abc"}},+ )+ skill = derived_spec["skills"][0]+ self.assertEqual(skill["from_template"], "triage-helper")+ self.assertEqual(skill["version"], 3)+ self.assertEqual(skill["source_version_id"], "abc")diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.tsindex a374360734ad..0f9bdd597c2a 100644--- a/products/agent_platform/frontend/generated/api.schemas.ts+++ b/products/agent_platform/frontend/generated/api.schemas.ts@@ -221,6 +221,29 @@ export const AgentRevisionApiSpecFrameworkPromptOmitItem = {ReasoningHint: 'reasoning_hint',} as const+/**+ * One reference to a versioned skill in the llma-skill store, pinned into+ * this agent's bundle at freeze.+ */+export interface SkillRefApi {+ /**+ * Name of the skill in the llma-skill store to pin into this agent. Resolved at freeze to the chosen `version` and materialized into the bundle.+ * @maxLength 64+ */+ from_template: string+ /**+ * Folder the resolved skill is materialized under in the bundle (`skills/<alias>/`). Lowercase letters, digits, hyphens or underscores, starting and ending with a letter or digit; must be unique within the revision.+ * @maxLength 64+ * @pattern ^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$+ */+ alias: string+ /**+ * Specific published version to pin. Omit to pin the store's latest version at freeze time.+ * @minimum 1+ */+ version?: number+}+export type AgentRevisionApiSpecTriggersItem =| {type: 'slack'@@ -394,7 +417,7 @@ export type AgentRevisionApiSpecToolsItem =kind: 'custom_template'from_template: stringalias: string- /** @minimum 0 */+ /** @minimum 1 */version?: number}| {@@ -452,8 +475,9 @@ export type AgentRevisionApiSpecSkillsItem = {description?: stringfrom_template?: stringalias?: string- /** @minimum 0 */+ /** @minimum 1 */version?: number+ source_version_id?: string}export type AgentRevisionApiSpecIdentityProvidersItem =@@ -582,6 +606,8 @@ export interface AgentRevisionApi {/** @nullable */readonly bundle_sha256: string | nullspec?: AgentRevisionApiSpec+ /** Store-skill references for this draft, set via the `skill_refs` action and resolved into the bundle at freeze. Preserved as the authoring record on the frozen revision (and carried forward when forking a new draft); resolved provenance is stamped onto `spec.skills[].source_version_id`. */+ readonly skill_refs: readonly SkillRefApi[]/** @nullable */readonly created_by_id: number | null/**@@ -775,7 +801,7 @@ export type PatchedAgentRevisionApiSpecToolsItem =kind: 'custom_template'from_template: stringalias: string- /** @minimum 0 */+ /** @minimum 1 */version?: number}| {@@ -833,8 +859,9 @@ export type PatchedAgentRevisionApiSpecSkillsItem = {description?: stringfrom_template?: stringalias?: string- /** @minimum 0 */+ /** @minimum 1 */version?: number+ source_version_id?: string}export type PatchedAgentRevisionApiSpecIdentityProvidersItem =@@ -985,6 +1012,8 @@ export interface PatchedAgentRevisionApi {/** @nullable */readonly bundle_sha256?: string | nullspec?: PatchedAgentRevisionApiSpec+ /** Store-skill references for this draft, set via the `skill_refs` action and resolved into the bundle at freeze. Preserved as the authoring record on the frozen revision (and carried forward when forking a new draft); resolved provenance is stamped onto `spec.skills[].source_version_id`. */+ readonly skill_refs?: readonly SkillRefApi[]/** @nullable */readonly created_by_id?: number | null/**@@ -1005,17 +1034,6 @@ export interface WriteAgentMdRequestApi {export type WriteTypedBundleRequestApiSpec = { [key: string]: unknown }-/**- * Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored- * at the canonical `skills/<skill_id>/SKILL.md` path in the bundle.- */-export interface WriteSkillRequestApi {- /** One-line summary shown in the skill index; the model uses it to decide when to load the skill. */- description: string- /** The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`. */- body: string-}-export type WriteToolRequestApiArgsSchema = { [key: string]: unknown }/**@@ -1029,11 +1047,11 @@ export interface WriteToolRequestApi {/*** Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed- * payload.+ * payload. Skills are not authored here: they come from the llma-skill store+ * via `skill_refs` and are materialized into the bundle at freeze.*/export interface WriteTypedBundleRequestApi {agent_md: string- skills?: WriteSkillRequestApi[]tools?: WriteToolRequestApi[]spec: WriteTypedBundleRequestApiSpec}@@ -1102,6 +1120,14 @@ export interface SetEnvRequestApi {env: SetEnvRequestApiEnv}+/**+ * Body for PUT /revisions/<id>/skill_refs/ — full-replace the draft's references.+ */+export interface SetSkillRefsRequestApi {+ /** The complete set of store-skill references for this draft; replaces any existing references. */+ skill_refs: SkillRefApi[]+}+export interface AgentRevisionSlackManifestResponseApi {revision_id: string/** Slack app manifest (JSON) ready to paste into https://api.slack.com/apps?new_app=1 → 'From an app manifest'. Scopes and event subscriptions are derived from the agent's slack trigger config + tools. */diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.tsindex 4cb633517859..cb29f5e7a99e 100644--- a/products/agent_platform/frontend/generated/api.ts+++ b/products/agent_platform/frontend/generated/api.ts@@ -66,8 +66,8 @@ import type {PreviewProxyInvokeRequestApi,SetEnvKeyRequestApi,SetEnvRequestApi,+ SetSkillRefsRequestApi,WriteAgentMdRequestApi,- WriteSkillRequestApi,WriteSpecRequestApi,WriteToolRequestApi,WriteTypedBundleRequestApi,@@ -1082,107 +1082,31 @@ export const agentApplicationsRevisionsSetEnvCreate = async (})}-export const getAgentApplicationsRevisionsSkillsUpdateUrl = (+export const getAgentApplicationsRevisionsSkillRefsUpdateUrl = (projectId: string,applicationId: string,- id: string,- skillId: string+ id: string) => {- return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/skills/${skillId}/`+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/skill_refs/`}/**- * Revisions of an agent. Created in `draft`, promoted through- * `ready → live` once the bundle has been uploaded + frozen.- *- * URLs (nested under an application):- *- * Model CRUD:- * GET .../revisions/ list- * POST .../revisions/ create draft- * GET .../revisions/<id>/ retrieve- * PATCH .../revisions/<id>/ update spec (draft only)- *- * Lifecycle:- * POST .../revisions/<id>/promote/ ready → live- * POST .../revisions/<id>/archive/ → archived- * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)- * POST .../revisions/<id>/clone_from/ copy bundle from another rev- * POST .../revisions/new_draft/ create draft + clone_from atomically- *- * Bundle authoring (proxied to the janitor):- * GET .../revisions/<id>/manifest/ list paths + sha256- * GET .../revisions/<id>/file/?path=… read one file- * PUT .../revisions/<id>/file/?path=… write one file (draft)- * DELETE .../revisions/<id>/file/?path=… delete one file (draft)- * GET .../revisions/<id>/bundle/ bulk pull all files- * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)+ * Full-replace the draft's store-skill references. They are resolved+ * and materialized into the bundle at freeze, not here — this only records+ * which skills (and pinned versions) the freeze should pull in.*/-export const agentApplicationsRevisionsSkillsUpdate = async (+export const agentApplicationsRevisionsSkillRefsUpdate = async (projectId: string,applicationId: string,id: string,- skillId: string,- writeSkillRequestApi: WriteSkillRequestApi,+ setSkillRefsRequestApi: SetSkillRefsRequestApi,options?: RequestInit): Promise<AgentRevisionApi> => {- return apiMutator<AgentRevisionApi>(- getAgentApplicationsRevisionsSkillsUpdateUrl(projectId, applicationId, id, skillId),- {- ...options,- method: 'PUT',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(writeSkillRequestApi),- }- )-}--export const getAgentApplicationsRevisionsSkillsDestroyUrl = (- projectId: string,- applicationId: string,- id: string,- skillId: string-) => {- return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/skills/${skillId}/`-}--/**- * Revisions of an agent. Created in `draft`, promoted through- * `ready → live` once the bundle has been uploaded + frozen.- *- * URLs (nested under an application):- *- * Model CRUD:- * GET .../revisions/ list- * POST .../revisions/ create draft- * GET .../revisions/<id>/ retrieve- * PATCH .../revisions/<id>/ update spec (draft only)- *- * Lifecycle:- * POST .../revisions/<id>/promote/ ready → live- * POST .../revisions/<id>/archive/ → archived- * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)- * POST .../revisions/<id>/clone_from/ copy bundle from another rev- * POST .../revisions/new_draft/ create draft + clone_from atomically- *- * Bundle authoring (proxied to the janitor):- * GET .../revisions/<id>/manifest/ list paths + sha256- * GET .../revisions/<id>/file/?path=… read one file- * PUT .../revisions/<id>/file/?path=… write one file (draft)- * DELETE .../revisions/<id>/file/?path=… delete one file (draft)- * GET .../revisions/<id>/bundle/ bulk pull all files- * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)- */-export const agentApplicationsRevisionsSkillsDestroy = async (- projectId: string,- applicationId: string,- id: string,- skillId: string,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getAgentApplicationsRevisionsSkillsDestroyUrl(projectId, applicationId, id, skillId), {+ return apiMutator<AgentRevisionApi>(getAgentApplicationsRevisionsSkillRefsUpdateUrl(projectId, applicationId, id), {...options,- method: 'DELETE',+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(setSkillRefsRequestApi),})}diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.tsindex c408a508f2fe..3c5479a302a2 100644--- a/products/agent_platform/frontend/generated/api.zod.ts+++ b/products/agent_platform/frontend/generated/api.zod.ts@@ -146,8 +146,6 @@ export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTexport const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000-export const agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin = 0-export const agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault = {}export const agentApplicationsRevisionsCreateBodySpecToolsItemFourRequiredDefault = falseexport const agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsDefault = 5000@@ -165,8 +163,6 @@ export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovaexport const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []-export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0-export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault = `posthog`@@ -499,10 +495,7 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({kind: zod.literal('custom_template'),from_template: zod.string(),alias: zod.string(),- version: zod- .number()- .min(agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin)- .optional(),+ version: zod.number().min(1).optional(),}),zod.object({kind: zod.literal('client'),@@ -591,10 +584,8 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({description: zod.string().optional(),from_template: zod.string().optional(),alias: zod.string().optional(),- version: zod- .number()- .min(agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin)- .optional(),+ version: zod.number().min(1).optional(),+ source_version_id: zod.string().optional(),})).default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),@@ -764,8 +755,6 @@ export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTexport const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000export const agentApplicationsRevisionsUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000-export const agentApplicationsRevisionsUpdateBodySpecToolsItemThreeVersionMin = 0-export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourArgsSchemaDefault = {}export const agentApplicationsRevisionsUpdateBodySpecToolsItemFourRequiredDefault = falseexport const agentApplicationsRevisionsUpdateBodySpecToolsItemFourTimeoutMsDefault = 5000@@ -783,8 +772,6 @@ export const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovaexport const agentApplicationsRevisionsUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000export const agentApplicationsRevisionsUpdateBodySpecMcpsDefault = []-export const agentApplicationsRevisionsUpdateBodySpecSkillsItemVersionMin = 0-export const agentApplicationsRevisionsUpdateBodySpecSkillsDefault = []export const agentApplicationsRevisionsUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`@@ -1117,10 +1104,7 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({kind: zod.literal('custom_template'),from_template: zod.string(),alias: zod.string(),- version: zod- .number()- .min(agentApplicationsRevisionsUpdateBodySpecToolsItemThreeVersionMin)- .optional(),+ version: zod.number().min(1).optional(),}),zod.object({kind: zod.literal('client'),@@ -1209,10 +1193,8 @@ export const AgentApplicationsRevisionsUpdateBody = /* @__PURE__ */ zod.object({description: zod.string().optional(),from_template: zod.string().optional(),alias: zod.string().optional(),- version: zod- .number()- .min(agentApplicationsRevisionsUpdateBodySpecSkillsItemVersionMin)- .optional(),+ version: zod.number().min(1).optional(),+ source_version_id: zod.string().optional(),})).default(agentApplicationsRevisionsUpdateBodySpecSkillsDefault),@@ -1405,8 +1387,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalexport const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin = 0-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault = {}export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourRequiredDefault = falseexport const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsDefault = 5000@@ -1424,8 +1404,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoexport const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []-export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0-export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`@@ -1772,10 +1750,7 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.okind: zod.literal('custom_template'),from_template: zod.string(),alias: zod.string(),- version: zod- .number()- .min(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin)- .optional(),+ version: zod.number().min(1).optional(),}),zod.object({kind: zod.literal('client'),@@ -1866,10 +1841,8 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.odescription: zod.string().optional(),from_template: zod.string().optional(),alias: zod.string().optional(),- version: zod- .number()- .min(agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin)- .optional(),+ version: zod.number().min(1).optional(),+ source_version_id: zod.string().optional(),})).default(agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault),@@ -2040,24 +2013,6 @@ export const AgentApplicationsRevisionsAgentMdUpdateBody = /* @__PURE__ */ zodexport const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod.object({agent_md: zod.string(),- skills: zod- .array(- zod- .object({- description: zod- .string()- .describe(- 'One-line summary shown in the skill index; the model uses it to decide when to load the skill.'- ),- body: zod- .string()- .describe("The skill's full markdown body, stored at `skills\/<skill_id>\/SKILL.md`."),- })- .describe(- 'Body shape for PUT \/revisions\/<id>\/skills\/<skill_id>\/. The body is stored\nat the canonical `skills\/<skill_id>\/SKILL.md` path in the bundle.'- )- )- .optional(),tools: zod.array(zod@@ -2071,7 +2026,9 @@ export const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod.optional(),spec: zod.record(zod.string(), zod.unknown()),})- .describe('Body shape for PUT \/revisions\/<id>\/bundle\/ — the full-replace typed\npayload.')+ .describe(+ 'Body shape for PUT \/revisions\/<id>\/bundle\/ — the full-replace typed\npayload. Skills are not authored here: they come from the llma-skill store\nvia `skill_refs` and are materialized into the bundle at freeze.'+ )/*** Copy every file from `source_revision_id` into this revision.@@ -2140,42 +2097,52 @@ export const AgentApplicationsRevisionsSetEnvCreateBody = /* @__PURE__ */ zod)/**- * Revisions of an agent. Created in `draft`, promoted through- * `ready → live` once the bundle has been uploaded + frozen.- *- * URLs (nested under an application):- *- * Model CRUD:- * GET .../revisions/ list- * POST .../revisions/ create draft- * GET .../revisions/<id>/ retrieve- * PATCH .../revisions/<id>/ update spec (draft only)- *- * Lifecycle:- * POST .../revisions/<id>/promote/ ready → live- * POST .../revisions/<id>/archive/ → archived- * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)- * POST .../revisions/<id>/clone_from/ copy bundle from another rev- * POST .../revisions/new_draft/ create draft + clone_from atomically- *- * Bundle authoring (proxied to the janitor):- * GET .../revisions/<id>/manifest/ list paths + sha256- * GET .../revisions/<id>/file/?path=… read one file- * PUT .../revisions/<id>/file/?path=… write one file (draft)- * DELETE .../revisions/<id>/file/?path=… delete one file (draft)- * GET .../revisions/<id>/bundle/ bulk pull all files- * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)+ * Full-replace the draft's store-skill references. They are resolved+ * and materialized into the bundle at freeze, not here — this only records+ * which skills (and pinned versions) the freeze should pull in.*/-export const AgentApplicationsRevisionsSkillsUpdateBody = /* @__PURE__ */ zod+export const agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemFromTemplateMax = 64++export const agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasMax = 64++export const agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasRegExp = new RegExp(+ '^[a-z0-9](?:[a-z0-9_-]\*[a-z0-9])?$'+)++export const AgentApplicationsRevisionsSkillRefsUpdateBody = /* @__PURE__ */ zod.object({- description: zod- .string()- .describe('One-line summary shown in the skill index; the model uses it to decide when to load the skill.'),- body: zod.string().describe("The skill's full markdown body, stored at `skills\/<skill_id>\/SKILL.md`."),+ skill_refs: zod+ .array(+ zod+ .object({+ from_template: zod+ .string()+ .max(agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemFromTemplateMax)+ .describe(+ 'Name of the skill in the llma-skill store to pin into this agent. Resolved at freeze to the chosen `version` and materialized into the bundle.'+ ),+ alias: zod+ .string()+ .max(agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasMax)+ .regex(agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasRegExp)+ .describe(+ 'Folder the resolved skill is materialized under in the bundle (`skills\/<alias>\/`). Lowercase letters, digits, hyphens or underscores, starting and ending with a letter or digit; must be unique within the revision.'+ ),+ version: zod+ .number()+ .min(1)+ .optional()+ .describe(+ "Specific published version to pin. Omit to pin the store's latest version at freeze time."+ ),+ })+ .describe(+ "One reference to a versioned skill in the llma-skill store, pinned into\nthis agent's bundle at freeze."+ )+ )+ .describe('The complete set of store-skill references for this draft; replaces any existing references.'),})- .describe(- 'Body shape for PUT \/revisions\/<id>\/skills\/<skill_id>\/. The body is stored\nat the canonical `skills\/<skill_id>\/SKILL.md` path in the bundle.'- )+ .describe("Body for PUT \/revisions\/<id>\/skill_refs\/ — full-replace the draft's references.")/*** Revisions of an agent. Created in `draft`, promoted throughdiff --git a/products/agent_platform/services/agent-janitor/src/api/typed-bundle.ts b/products/agent_platform/services/agent-janitor/src/api/typed-bundle.tsindex d1ba8b3b82ae..d27aacc9b803 100644--- a/products/agent_platform/services/agent-janitor/src/api/typed-bundle.ts+++ b/products/agent_platform/services/agent-janitor/src/api/typed-bundle.ts@@ -9,7 +9,7 @@** Resources:* - `agent_md` ← the system prompt (string)- * - `skills/<id>` ← { description, body } (stored at skills/<id>/SKILL.md)+ * - `skills/<id>` ← { description, body, files? } (SKILL.md + companions under skills/<id>/)* - `tools/<id>` ← { description, args_schema, source }* - `spec` ← author-facing slice (no skills[]/tools[])*@@ -35,6 +35,7 @@ import {RevisionState,RevisionStore,skillBodyPath,+ skillCompanionPath,syncBundleToStore,toolCompiledPath,TypedBundleSchema,@@ -53,7 +54,21 @@ const ResourceIdParamSchema = z.max(64).regex(RESOURCE_ID_REGEX, { message: 'id must be lowercase letters, digits, hyphens, or underscores' })-const SkillPutBodySchema = TypedSkillSchema.omit({ id: true })+// A skill companion file (e.g. `references/api.md`, `scripts/setup.sh`) shipped+// alongside SKILL.md. `path` is relative to the skill folder; it's resolved ++// safety-checked against `skillCompanionPath` in the handler. Limits mirror the+// llma-skill store (≤50 files, ≤1 MB each) so a store skill round-trips cleanly.+const SkillFilePutSchema = z.object({+ path: z.string().min(1).max(255),+ content: z.string().max(1_000_000),+})+const SkillPutBodySchema = TypedSkillSchema.omit({ id: true }).extend({+ // Store skills allow a ≤1 MB body and render_skill_md prepends frontmatter,+ // so allow headroom above the store cap. (Limits mirror the llma-skill store+ // so a resolved store skill round-trips cleanly into the bundle.)+ body: z.string().max(1_100_000),+ files: z.array(SkillFilePutSchema).max(50).default([]),+})const ToolPutBodySchema = TypedToolSchema.omit({ id: true })const AgentMdPutBodySchema = z.object({@@ -64,7 +79,7 @@ const SpecPutBodySchema = z.object({spec: TypedSpecSchema,})-const TypedBundlePutBodySchema = TypedBundleSchema+const TypedBundlePutBodySchema = TypedBundleSchema.omit({ skills: true })export interface TypedBundleRouterOpts {revisions: RevisionStore@@ -195,12 +210,26 @@ export function buildTypedBundleRouter(opts: TypedBundleRouterOpts): Router {return}const id = idCheck.data- // Clear the skill folder first so a re-PUT also sweeps any stray- // legacy files (e.g. old `skills/<id>/files/*` companions) before- // writing the fresh SKILL.md body.+ // Resolve + safety-check every companion path BEFORE touching the+ // store, so invalid input can't half-clear an existing skill folder.+ let companions: { path: string; content: string }[]+ try {+ companions = parsed.data.files.map((f) => ({+ path: skillCompanionPath(id, f.path),+ content: f.content,+ }))+ } catch (e) {+ res.status(400).json({ error: 'invalid_skill_file_path', message: (e as Error).message })+ return+ }+ // Clear the skill folder first so a re-PUT sweeps SKILL.md plus any+ // stale companions before writing the fresh body + companion set.await deleteSkillFiles(req.params.id, opts.bundles, id)await opts.bundles.write(req.params.id, skillBodyPath(id), parsed.data.body)- res.json({ ok: true, skill_id: id })+ for (const c of companions) {+ await opts.bundles.write(req.params.id, c.path, c.content)+ }+ res.json({ ok: true, skill_id: id, files_written: companions.length })}))diff --git a/products/agent_platform/services/agent-janitor/src/server.test.ts b/products/agent_platform/services/agent-janitor/src/server.test.tsindex a49cef390ecd..198a528bedda 100644--- a/products/agent_platform/services/agent-janitor/src/server.test.ts+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts@@ -772,6 +772,44 @@ describe('janitor HTTP', () => {expect(paths).toEqual(['agent.md', 'skills/research.md'])})+ it('PUT /revisions/:id/skills/:id writes SKILL.md + companion files', async () => {+ const { app, bundles, revisionId } = await mkRevisionApp()+ const res = await request(app)+ .put(`/revisions/${revisionId}/skills/triage`)+ .send({+ description: 'triage inbound',+ body: '---\nname: triage\n---\nthe body',+ files: [{ path: 'references/api.md', content: '# API' }],+ })+ expect(res.status).toBe(200)+ expect(res.body).toMatchObject({ ok: true, skill_id: 'triage', files_written: 1 })+ expect(await bundles.readText(revisionId, 'skills/triage/SKILL.md')).toContain('the body')+ expect(await bundles.readText(revisionId, 'skills/triage/references/api.md')).toBe('# API')+ })++ it('PUT /revisions/:id/skills/:id rejects a companion path escaping the skill folder', async () => {+ const { app, bundles, revisionId } = await mkRevisionApp()+ const res = await request(app)+ .put(`/revisions/${revisionId}/skills/triage`)+ .send({ description: 'd', body: 'b', files: [{ path: '../escape.md', content: 'x' }] })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('invalid_skill_file_path')+ // Invalid input must not have cleared/written anything.+ expect(await bundles.exists(revisionId, 'skills/triage/SKILL.md')).toBe(false)+ })++ it('PUT /revisions/:id/skills/:id re-PUT sweeps stale companions', async () => {+ const { app, bundles, revisionId } = await mkRevisionApp()+ await request(app)+ .put(`/revisions/${revisionId}/skills/triage`)+ .send({ description: 'd', body: 'b', files: [{ path: 'old.md', content: '1' }] })+ await request(app)+ .put(`/revisions/${revisionId}/skills/triage`)+ .send({ description: 'd', body: 'b2', files: [{ path: 'new.md', content: '2' }] })+ expect(await bundles.exists(revisionId, 'skills/triage/old.md')).toBe(false)+ expect(await bundles.readText(revisionId, 'skills/triage/new.md')).toBe('2')+ })+// The single-file `/file` and bulk `/bundle` (with `mode`) endpoints// were removed alongside the typed bundle rollout. End-to-end coverage// of the typed endpoints lives indiff --git a/products/agent_platform/services/agent-shared/src/spec/spec.ts b/products/agent_platform/services/agent-shared/src/spec/spec.tsindex dbdf15b6b8f0..3c94f94d97d4 100644--- a/products/agent_platform/services/agent-shared/src/spec/spec.ts+++ b/products/agent_platform/services/agent-shared/src/spec/spec.ts@@ -602,7 +602,10 @@ export const SkillRefSchema = z.object({*/from_template: z.string().optional(),alias: z.string().optional(),- version: z.number().int().nonnegative().optional(),+ version: z.number().int().min(1).optional(),+ // Immutable per-version row id of the resolved store skill — the exact+ // provenance anchor, stamped at freeze. Optional so older frozen specs parse.+ source_version_id: z.string().optional(),})/**diff --git a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.tsindex 353777fc243f..b6a08fbe738f 100644--- a/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts+++ b/products/agent_platform/services/agent-shared/src/storage/typed-bundle.ts@@ -27,8 +27,31 @@ import { BundleEntry, BundleStore } from './bundle'// ─── Canonical S3 paths ──────────────────────────────────────────────export const AGENT_MD_PATH = 'agent.md'+export const SKILL_BODY_FILENAME = 'SKILL.md'export function skillBodyPath(skillId: string): string {- return `skills/${skillId}/SKILL.md`+ return `skills/${skillId}/${SKILL_BODY_FILENAME}`+}++/**+ * Resolve a skill companion file's relative path to its canonical bundle path+ * (`skills/<id>/<rel>`), rejecting anything that would escape the skill folder+ * or collide with the reserved `SKILL.md` body. Mirrors the runtime guard in+ * `@posthog/load-skill`'s `resolveSkillFile` so what we write is exactly what+ * the loader will later accept. Throws on invalid input.+ */+export function skillCompanionPath(skillId: string, relPath: string): string {+ const rel = relPath.replace(/\\/g, '/')+ if (!rel || rel.startsWith('/')) {+ throw new Error(`skill file "${relPath}" must be a non-empty relative path inside the skill folder.`)+ }+ const segments = rel.split('/')+ if (segments.some((s) => s === '..' || s === '.' || s === '')) {+ throw new Error(`skill file "${relPath}" must not contain traversal or empty segments.`)+ }+ if (rel === SKILL_BODY_FILENAME) {+ throw new Error(`skill file "${relPath}" is reserved — the body is written from the skill's \`body\`.`)+ }+ return `skills/${skillId}/${rel}`}export function toolSourcePath(toolId: string): string {return `tools/${toolId}/source.ts`@@ -303,16 +326,19 @@ export function stripDerivedSpecFields(spec: Record<string, unknown>): TypedSpec* - tool compilation (calling `compileAndWriteTool` per tool)* - persisting `bundle.spec` onto the revision row*/-export async function syncBundleToStore(revisionId: string, store: BundleStore, bundle: TypedBundle): Promise<void> {+export async function syncBundleToStore(+ revisionId: string,+ store: BundleStore,+ bundle: Omit<TypedBundle, 'skills'>+): Promise<void> {const entries = await store.list(revisionId)const existing = new Set(entries.map((e) => e.path))- // Build the set of paths we WILL write so we know what to delete.+ // Build the set of paths we WILL write so we know what to delete. Skills are+ // NOT managed here — they're materialized from the store at freeze and live+ // only in the frozen bundle, so the full-replace never touches `skills/`.const willWrite = new Set<string>()willWrite.add(AGENT_MD_PATH)- for (const skill of bundle.skills) {- willWrite.add(skillBodyPath(skill.id))- }for (const tool of bundle.tools) {willWrite.add(toolSourcePath(tool.id))willWrite.add(toolSchemaPath(tool.id))@@ -320,23 +346,19 @@ export async function syncBundleToStore(revisionId: string, store: BundleStore,}// Delete anything in the canonical layout that's NOT in the new payload.- // We DON'T touch paths outside the canonical layout — those are either- // future-resource buckets or legacy junk the migrator hasn't cleaned up.+ // We DON'T touch paths outside the canonical layout (future-resource buckets+ // or legacy junk) and we DON'T touch `skills/` (freeze-owned).for (const path of existing) {if (willWrite.has(path)) {continue}- if (path === AGENT_MD_PATH || path.startsWith('skills/') || path.startsWith('tools/')) {+ if (path === AGENT_MD_PATH || path.startsWith('tools/')) {await store.delete(revisionId, path)}}- // Write agent.md + skill bodies. Tools are written by the caller after- // the compile step succeeds.+ // Write agent.md. Tools are written by the caller after the compile step.await store.write(revisionId, AGENT_MD_PATH, bundle.agent_md)- for (const skill of bundle.skills) {- await store.write(revisionId, skillBodyPath(skill.id), skill.body)- }}/**@@ -364,7 +386,9 @@ export async function deleteToolFiles(revisionId: string, store: BundleStore, to}/**- * Delete one skill's folder (`skills/<id>/` — currently just SKILL.md).+ * Delete one skill's folder (`skills/<id>/` — SKILL.md plus any companion+ * files), so a re-PUT fully replaces the skill rather than leaving stale+ * companions behind.*/export async function deleteSkillFiles(revisionId: string, store: BundleStore, skillId: string): Promise<void> {const entries = await store.list(revisionId, `skills/${skillId}/`)diff --git a/products/agent_platform/services/agent-tests/src/cases/dynamic-skills.test.ts b/products/agent_platform/services/agent-tests/src/cases/dynamic-skills.test.tsindex 67beb7b3b269..18243617eba3 100644--- a/products/agent_platform/services/agent-tests/src/cases/dynamic-skills.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/dynamic-skills.test.ts@@ -63,6 +63,40 @@ describe('dynamic skill loading: real e2e', () => {expect(parsed.body).toContain('ask questions')})+ it('model loads a skill companion file via the file param', async () => {+ // Multi-file skills (the shape a store skill materializes into the bundle):+ // SKILL.md plus companion files under skills/<id>/. load-skill fetches a+ // companion when given `file`.+ c.setScript([+ fauxCallTool('@posthog/load-skill', { id: 'research', file: 'references/deep.md' }),+ fauxText('used the companion'),+ ])+ await c.deployAgent({+ slug: 'skill-companion-agent',+ spec: {+ skills: [{ id: 'research', path: 'skills/research/SKILL.md', description: 'How to research' }],+ },+ files: {+ 'agent.md': 'you have a research skill with companion docs.',+ 'skills/research/SKILL.md': 'See references/deep.md for the deep dive.',+ 'skills/research/references/deep.md': 'DEEP DIVE: triangulate three independent sources.',+ },+ })+ const res = await request(c.ingress).post('/agents/skill-companion-agent/run').send({ message: 'go' })+ await c.drain()+ const session = await c.queue.get(res.body.session_id)+ expect(session!.state).toBe('completed')+ const toolResult = session!.conversation[2] as unknown as {+ role: 'toolResult'+ content: Array<{ text: string }>+ }+ expect(toolResult.role).toBe('toolResult')+ const parsed = JSON.parse(toolResult.content[0].text) as { id: string; path: string; body: string }+ expect(parsed.id).toBe('research')+ expect(parsed.path).toBe('skills/research/references/deep.md')+ expect(parsed.body).toContain('triangulate three independent sources')+ })+it('@posthog/load-skill errors when the id is unknown', async () => {c.setScript([fauxCallTool('@posthog/load-skill', { id: 'ghost' }), fauxText('oops')])await c.deployAgent({diff --git a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.tsindex 420796121384..055c4870100c 100644--- a/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts+++ b/products/agent_platform/services/agent-tests/src/cases/typed-bundle-authoring.test.ts@@ -101,22 +101,18 @@ describe('typed bundle authoring API: real e2e', () => {})describe('PUT /bundle full payload → GET /bundle round-trip', () => {- it('returns the exact payload back, plus server-derived compiled.js stamps', async () => {+ it('round-trips agent_md/tools/spec and leaves skills (managed via /skills/<id>) intact', async () => {const rid = await newDraft(c)+ // Skills are store-backed now — authored via the single-resource+ // `/skills/<id>` PUT (and at freeze from `skill_refs`), never through+ // the full `/bundle` payload. Seed one to prove the full PUT below+ // doesn't manage or clobber it.+ await request(c.janitor).put(`/revisions/${rid}/skills/notify`).send({+ description: 'How to ping ops.',+ body: '# notify',+ })const payload = {agent_md: 'system prompt',- skills: [- {- id: 'research',- description: 'When to deep-dive.',- body: '# research\nDo your homework.',- },- {- id: 'notify',- description: 'How to ping ops.',- body: '# notify',- },- ],tools: [{id: 'echo',@@ -143,10 +139,10 @@ describe('typed bundle authoring API: real e2e', () => {const get = await request(c.janitor).get(`/revisions/${rid}/bundle`)expect(get.status).toBe(200)expect(get.body.bundle.agent_md).toBe('system prompt')- expect(get.body.bundle.skills.map((s: { id: string }) => s.id).sort()).toEqual(['notify', 'research'])expect(get.body.bundle.tools).toHaveLength(1)expect(get.body.bundle.tools[0].id).toBe('echo')- // Skill body roundtripped.+ // The skill set before the full PUT survives — `/bundle` doesn't own skills.+ expect(get.body.bundle.skills.map((s: { id: string }) => s.id)).toEqual(['notify'])const notify = get.body.bundle.skills.find((s: { id: string; body: string }) => s.id === 'notify')expect(notify.body).toBe('# notify')@@ -316,7 +312,7 @@ describe('typed bundle authoring API: real e2e', () => {// ─── Full-replace PUT /bundle ────────────────────────────────────describe('PUT /bundle is a true full replace', () => {- it('skills not in payload are deleted', async () => {+ it('a full /bundle replace does NOT manage skills — they are owned by /skills/<id> + freeze', async () => {const rid = await newDraft(c)for (const id of ['a', 'b', 'c']) {await request(c.janitor)@@ -326,25 +322,19 @@ describe('typed bundle authoring API: real e2e', () => {body: `# ${id}`,})}- await request(c.janitor)- .put(`/revisions/${rid}/bundle`)- .send({- agent_md: 'top',- skills: [- { id: 'a', description: 'updated', body: '# new a' },- { id: 'd', description: 'd', body: '# d' },- ],- tools: [],- spec: defaultSpec(),- })+ // A full replace that omits skills (the only shape the PUT body accepts —+ // `skills` was dropped from the payload schema). Skills are NOT swept by+ // this; they are store-backed and only freeze reconciles them to skill_refs.+ await request(c.janitor).put(`/revisions/${rid}/bundle`).send({+ agent_md: 'top',+ tools: [],+ spec: defaultSpec(),+ })const get = await request(c.janitor).get(`/revisions/${rid}/bundle`)const ids = get.body.bundle.skills.map((s: { id: string }) => s.id).sort()- expect(ids).toEqual(['a', 'd'])- const a = get.body.bundle.skills.find((s: { id: string }) => s.id === 'a')- expect(a.body).toBe('# new a')- // S3 doesn't keep orphaned files behind.- expect(await c.bundle.exists(rid, 'skills/b/SKILL.md')).toBe(false)- expect(await c.bundle.exists(rid, 'skills/c/SKILL.md')).toBe(false)+ expect(ids).toEqual(['a', 'b', 'c'])+ expect(await c.bundle.exists(rid, 'skills/b/SKILL.md')).toBe(true)+ expect(await c.bundle.exists(rid, 'skills/c/SKILL.md')).toBe(true)})it('tools not in payload are deleted (source + compiled + schema)', async () => {@@ -750,16 +740,15 @@ export default {const rid = await newDraft(c, 'sre-roundtrip')- // 1. ACCEPTED — the typed PUT /bundle takes the SKILL.md bodies.- const put = await request(c.janitor)- .put(`/revisions/${rid}/bundle`)- .send({- agent_md: await readFile(join(exampleRoot, 'agent.md'), 'utf-8'),- skills,- tools: [],- spec: defaultSpec(),- })- expect(put.status).toBe(200)+ // 1. ACCEPTED — each skill is authored through the single-resource+ // `/skills/<id>` PUT (the store-backed authoring path; the full+ // `/bundle` payload no longer carries skills).+ for (const s of skills) {+ const put = await request(c.janitor)+ .put(`/revisions/${rid}/skills/${s.id}`)+ .send({ description: s.description, body: s.body })+ expect(put.status).toBe(200)+ }// 2. STORED — each body lands at exactly `skills/<id>/SKILL.md` in S3.for (const s of skills) {diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.mdindex 3455d7ea47f6..032f6eeb4422 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/README.md@@ -125,7 +125,9 @@ Through the authoring MCP (preferred — same as other example bundles):agent-applications-create slug=agent-builder name="Agent Builder"agent-applications-revisions-create application_id=<id># write bundle resources via the granular per-resource tools:-# agent-applications-revisions-agent-md-update / -skills-update / -tools-update+# agent-applications-revisions-agent-md-update / -tools-update+# skills come from the store: llm-skills-create / -search, then+# agent-applications-revisions-skill-refs-setagent-applications-revisions-partial-update revision_id=<rid> spec=<contents of spec.json>agent-applications-revisions-validate-create revision_id=<rid>agent-applications-revisions-freeze-create revision_id=<rid>diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.mdindex 15d02cd97dde..a3dda3e4ee75 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/agent.md@@ -99,10 +99,11 @@ one, refuse and explain why.revision id must come from a prior tool call result or a usermessage. Hallucinated references are the most common way towaste a user's time.-5. **Confirm before destructive edits.** `skills-destroy` /- `tools-destroy` remove bundle content for good, and `archive`- clears a live revision. Tell the user the reversibility cost in- one sentence before calling.+5. **Confirm before destructive edits.** `tools-destroy` removes a+ custom tool's source for good, and `archive` clears a live+ revision. (Skills live in the store — dropping a `skill_refs` entry+ just unlinks it; the skill itself stays.) Tell the user the+ reversibility cost in one sentence before calling.6. **You can read but cannot bypass principal scope.** If theuser has read-only OAuth scope and asks you to promote, theAPI will 403 you — explain that the constraint is their token,@@ -227,21 +228,22 @@ you already have. Slug lookup costs an extra `list` call internally.**Write (PostHog MCP `posthog__agent-applications-*` — load `skills/authoring-new-agents` or `skills/editing-agents-safely` before reaching for these; the table omits the `posthog__` prefix for width):**-| Tool | Use when |-| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `agent-applications-create` | mint a brand-new agent. Requires `name` + `slug`. No revisions until you create one. |-| `agent-applications-partial-update` | edit `name` / `description` on an existing agent. Env block + live revision are managed elsewhere. |-| `agent-applications-revisions-create` | open a fresh draft revision under an application. Body shape mirrors `AgentRevision`. |-| `agent-applications-revisions-new-draft-create` | one-shot: create a draft + clone every file from a `source_revision_id` in one call. The default way to "edit live". |-| `agent-applications-revisions-partial-update` | replace `spec` on a draft revision (triggers, tools, model, limits, auth…). Only `state=draft` accepts spec edits. |-| `agent-applications-revisions-agent-md-update` | overwrite `agent.md` (the system prompt) on a draft. |-| `agent-applications-revisions-skills-update` / `-skills-destroy` | upsert or delete one skill body + its files on a draft. |-| `agent-applications-revisions-tools-update` / `-tools-destroy` | upsert or delete one custom tool (source + schema) on a draft. |-| `agent-applications-revisions-validate-create` | pre-flight check on any revision state. Surfaces missing entrypoints, unknown tool ids, missing trigger-required secrets. Always run before freeze. |-| `agent-applications-revisions-freeze-create` | flip `draft → ready` and stamp `bundle_sha256`. Idempotent. |-| `agent-applications-revisions-promote-create` | flip `ready → live` and update the parent's `live_revision`. Requires user consent (rule #3). Gated server-side on missing trigger-required secrets — promote will refuse with a clear error if `application.encrypted_env` is missing a key the spec's triggers need. |-| `agent-applications-revisions-archive-create` | archive any revision. Clears `live_revision` if the archived one was live. Destructive — see rule #5. |-| `agent-applications-env-keys-list` / `-get` | inventory which secrets are set / probe one (names only, never values). For setting secrets, use the `set_secret` client tool — never the raw env API. |+| Tool | Use when |+| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `agent-applications-create` | mint a brand-new agent. Requires `name` + `slug`. No revisions until you create one. |+| `agent-applications-partial-update` | edit `name` / `description` on an existing agent. Env block + live revision are managed elsewhere. |+| `agent-applications-revisions-create` | open a fresh draft revision under an application. Body shape mirrors `AgentRevision`. |+| `agent-applications-revisions-new-draft-create` | one-shot: create a draft + clone every file from a `source_revision_id` in one call. The default way to "edit live". |+| `agent-applications-revisions-partial-update` | replace `spec` on a draft revision (triggers, tools, model, limits, auth…). Only `state=draft` accepts spec edits. |+| `agent-applications-revisions-agent-md-update` | overwrite `agent.md` (the system prompt) on a draft. |+| `llm-skills-search` / `llm-skills-create` | find or author a skill in the llma-skill store (the canonical place skills live). |+| `agent-applications-revisions-skill-refs-set` | set the draft's `skill_refs` (which store skills it pins, by name + alias + optional version). Resolved into the bundle at freeze. |+| `agent-applications-revisions-tools-update` / `-tools-destroy` | upsert or delete one custom tool (source + schema) on a draft. |+| `agent-applications-revisions-validate-create` | pre-flight check on any revision state. Surfaces missing entrypoints, unknown tool ids, missing trigger-required secrets. Always run before freeze. |+| `agent-applications-revisions-freeze-create` | flip `draft → ready` and stamp `bundle_sha256`. Idempotent. |+| `agent-applications-revisions-promote-create` | flip `ready → live` and update the parent's `live_revision`. Requires user consent (rule #3). Gated server-side on missing trigger-required secrets — promote will refuse with a clear error if `application.encrypted_env` is missing a key the spec's triggers need. |+| `agent-applications-revisions-archive-create` | archive any revision. Clears `live_revision` if the archived one was live. Destructive — see rule #5. |+| `agent-applications-env-keys-list` / `-get` | inventory which secrets are set / probe one (names only, never values). For setting secrets, use the `set_secret` client tool — never the raw env API. |### Trigger-required secretsdiff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.mdindex 8494627fda6e..e21e21b7a784 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/auditing-the-fleet/SKILL.md@@ -31,7 +31,7 @@ single-agent flow:`promote` / `archive` need explicit consent (a `principal`approval) and are out of scope for the sweep itself. Your writesurface this run is: `new-draft-create`, the bundle edit tools- (`agent-md-update`, `skills-update`, `tools-update`,+ (`agent-md-update`, `skill-refs-set`, `tools-update`,`partial-update`), and `validate-create`. Stop at validate. Do**not** `freeze` — a frozen revision reads as "ready to ship", andthese are unreviewed.@@ -108,7 +108,8 @@ For each fix:(`source_revision_id`) — clones every file so your edit issurgical.2. Apply the **smallest** change that addresses the root cause:- - prompt/loop bug → `agent-md-update` or `skills-update`+ - prompt/loop bug → `agent-md-update`, or revise the skill in the+ store (`llm-skills-create` a new version) and `skill-refs-set`- missing/over-broad tool, wrong limit, wrong model/reasoning →`partial-update` on the spec- keep each draft to **one** root cause. Don't bundle unrelated@@ -169,8 +170,9 @@ it. There is no Slack post step — the Agent Builder doesn't post to Slack.- **No promotes / freezes / archives.** Proposals only. (Re-statingbecause it's the one rule that, broken, touches production.)- **No edits to the live revision in place.** Always branch a draft.-- **No deletions** (`skills-destroy` / `tools-destroy`) — destructive- and unreviewed is the worst combination.+- **No deletions** (`tools-destroy`) — destructive and unreviewed is+ the worst combination. (Dropping a `skill_refs` entry is fine — it+ only unlinks; the store skill stays.)- **No raw secrets.** If an agent's problem is a missing/expiredcredential, that's a recommendation for a human, never a value youset.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.mdindex 0ef606050079..21a425ed7d34 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/authoring-new-agents/SKILL.md@@ -183,14 +183,15 @@ provider + scopes.The authoring surface is **typed resources, not file paths**. Younever write a path; you upsert a typed object via one of these calls:-| Resource | Tool | Body shape |-| ------------- | ------------------------------------------------------- | -------------------------------------------------- |-| System prompt | `posthog__agent-applications-revisions-agent-md-update` | `{ content }` |-| Spec | `posthog__agent-applications-revisions-partial-update` | `{ spec }` (author-facing slice — no skills/tools) |-| One skill | `posthog__agent-applications-revisions-skills-update` | `{ description, body, files? }` |-| Delete skill | `posthog__agent-applications-revisions-skills-destroy` | (no body) |-| One tool | `posthog__agent-applications-revisions-tools-update` | `{ description, args_schema, source }` |-| Delete tool | `posthog__agent-applications-revisions-tools-destroy` | (no body) |+| Resource | Tool | Body shape |+| -------------- | ------------------------------------------------------- | ------------------------------------------------------ |+| System prompt | `posthog__agent-applications-revisions-agent-md-update` | `{ content }` |+| Spec | `posthog__agent-applications-revisions-partial-update` | `{ spec }` (author-facing slice — no skills/tools) |+| Author a skill | `posthog__llm-skills-create` | `{ name, description, body, files? }` (in the store) |+| Find skills | `posthog__llm-skills-search` | `{ search? }` |+| Pin skills | `posthog__agent-applications-revisions-skill-refs-set` | `{ skill_refs: [{ from_template, alias, version? }] }` |+| One tool | `posthog__agent-applications-revisions-tools-update` | `{ description, args_schema, source }` |+| Delete tool | `posthog__agent-applications-revisions-tools-destroy` | (no body) |**`spec.skills[]` and `spec.tools[]` are server-derived at freeze.**You can't write them via `partial-update`. The janitor scans the typed@@ -281,10 +282,11 @@ diagnostic — it tells you the exact shape you missed. Do NOT retryby tweaking the export style; the contract is `{actions: {default:fn}}` and nothing else.-Use the **single-resource** typed PUTs (`skills-update`,-`tools-update`, `agent-md-update`) for individual edits. There is no-bulk bundle-replace verb — edit the one resource that changed rather-than rewriting the whole bundle.+Use the **single-resource** typed PUTs (`tools-update`,+`agent-md-update`) and `skill-refs-set` for individual edits. There is+no bulk bundle-replace verb — edit the one resource that changed rather+than rewriting the whole bundle. Skills are authored in the store+(`llm-skills-create`) and pinned with `skill-refs-set`, never inline.## Phase 6 — validatediff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.mdindex 17dbd9f5a3a8..e20a585c10c3 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/editing-agents-safely/SKILL.md@@ -53,20 +53,21 @@ sees it.Choose the right verb:-| Verb | When | Reversibility |-| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |-| `posthog__agent-applications-revisions-partial-update` | Change `spec` fields (model, limits, triggers, tools[], identity_providers, mcps) — merges into the spec | Easy — the next update overwrites |-| `posthog__agent-applications-revisions-spec-update` | Replace the whole `spec` at once (a large rewrite) | Easy — overwrites the spec |-| `posthog__agent-applications-revisions-agent-md-update` | Overwrite `agent.md` (the system prompt) | Easy — re-write |-| `posthog__agent-applications-revisions-skills-update` | Upsert one skill (body + companion files) | Easy — re-write |-| `posthog__agent-applications-revisions-skills-destroy` | Delete one skill | **Hard** — content gone unless you have it |-| `posthog__agent-applications-revisions-tools-update` | Upsert one custom tool (source + schema) | Easy — re-write |-| `posthog__agent-applications-revisions-tools-destroy` | Delete one custom tool | **Hard** — content gone unless you have it |--These are all `posthog__agent-applications-*` MCP tools — there's-no bulk bundle-replace verb, which is deliberate: edit the one thing-that changed (`agent-md-update` / `skills-update` / `tools-update`)-rather than rewriting the whole bundle.+| Verb | When | Reversibility |+| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| `posthog__agent-applications-revisions-partial-update` | Change `spec` fields (model, limits, triggers, tools[], identity_providers, mcps) — merges into the spec | Easy — the next update overwrites |+| `posthog__agent-applications-revisions-spec-update` | Replace the whole `spec` at once (a large rewrite) | Easy — overwrites the spec |+| `posthog__agent-applications-revisions-agent-md-update` | Overwrite `agent.md` (the system prompt) | Easy — re-write |+| `posthog__llm-skills-search` / `posthog__llm-skills-create` | Find or author a skill in the llma-skill store | Easy — the store keeps every version |+| `posthog__agent-applications-revisions-skill-refs-set` | Set which store skills the draft pins (`skill_refs`) | Easy — re-set the list; nothing is deleted |+| `posthog__agent-applications-revisions-tools-update` | Upsert one custom tool (source + schema) | Easy — re-write |+| `posthog__agent-applications-revisions-tools-destroy` | Delete one custom tool | **Hard** — content gone unless you have it |++These are all `posthog__*` MCP tools — there's no bulk bundle-replace+verb, which is deliberate: edit the one thing that changed+(`agent-md-update` / `skill-refs-set` / `tools-update`) rather than+rewriting the whole bundle. Skills aren't authored on the agent at all —+they live in the store and the agent only references them.After any `spec` write, `posthog__agent-applications-revisions-retrieve` toconfirm what actually persisted.diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.mdindex 80a89bcb0c02..6f9b225993ad 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/skills/safety-and-boundaries/SKILL.md@@ -133,8 +133,10 @@ only when a concrete external client demands them.### 6. Confirm before destructive bundle edits-`skills-destroy` / `tools-destroy` delete bundle content with no undo,-and `archive` clears a live revision.+`tools-destroy` deletes a custom tool's source with no undo, and+`archive` clears a live revision. (Skills are store references —+`skill-refs-set` only changes which skills the agent pins; it never+deletes skill content.)Before either:diff --git a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.jsonindex d88586f32253..cf9c7c7492e8 100644--- a/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json+++ b/products/agent_platform/services/agent-tests/src/examples/agent-builder/spec.json@@ -220,8 +220,9 @@"agent-applications-revisions-clone-from-create","agent-applications-revisions-partial-update","agent-applications-revisions-agent-md-update",- "agent-applications-revisions-skills-update",- "agent-applications-revisions-skills-destroy",+ "agent-applications-revisions-skill-refs-set",+ "llm-skills-search",+ "llm-skills-create","agent-applications-revisions-tools-update","agent-applications-revisions-tools-destroy","agent-applications-revisions-spec-update",diff --git a/products/agent_platform/services/agent-tools/src/registry.ts b/products/agent_platform/services/agent-tools/src/registry.tsindex 3fbeab056df4..baf24a372de8 100644--- a/products/agent_platform/services/agent-tools/src/registry.ts+++ b/products/agent_platform/services/agent-tools/src/registry.ts@@ -42,8 +42,7 @@ import {posthogAgentApplicationsRevisionsPartialUpdateV1,posthogAgentApplicationsRevisionsPromoteV1,posthogAgentApplicationsRevisionsRetrieveV1,- posthogAgentApplicationsRevisionsSkillsDestroyV1,- posthogAgentApplicationsRevisionsSkillsUpdateV1,+ posthogAgentApplicationsRevisionsSkillRefsSetV1,posthogAgentApplicationsRevisionsSlackManifestV1,posthogAgentApplicationsRevisionsSystemPromptV1,posthogAgentApplicationsRevisionsToolsDestroyV1,@@ -53,6 +52,8 @@ import {posthogAgentApplicationsSessionsListV1,posthogAgentApplicationsSessionsRetrieveV1,posthogAgentApplicationsSetEnvV1,+ posthogLlmSkillsCreateV1,+ posthogLlmSkillsSearchV1,} from './tools/posthog-agent-management.v1'import { posthogListProjectsV1 } from './tools/posthog-projects.v1'import { posthogQueryV1 } from './tools/posthog-query.v1'@@ -132,8 +133,9 @@ export const ALL_TOOLS: NativeTool[] = [posthogAgentApplicationsRevisionsNewDraftV1,posthogAgentApplicationsRevisionsPartialUpdateV1,posthogAgentApplicationsRevisionsAgentMdUpdateV1,- posthogAgentApplicationsRevisionsSkillsUpdateV1,- posthogAgentApplicationsRevisionsSkillsDestroyV1,+ posthogLlmSkillsSearchV1,+ posthogLlmSkillsCreateV1,+ posthogAgentApplicationsRevisionsSkillRefsSetV1,posthogAgentApplicationsRevisionsToolsUpdateV1,posthogAgentApplicationsRevisionsToolsDestroyV1,posthogAgentApplicationsRevisionsValidateV1,diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.tsindex 20bc19d6d9e3..bef95e992376 100644--- a/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-agent-management.v1.ts@@ -561,59 +561,92 @@ export const posthogAgentApplicationsRevisionsAgentMdUpdateV1 = defineNativeTool},})-export const posthogAgentApplicationsRevisionsSkillsUpdateV1 = defineNativeTool({- id: '@posthog/agent-applications-revisions-skills-update',+// Skills are authored in the llma-skill store (the canonical source) and an+// agent *references* them — there is no inline skill authoring. An agent's+// skills are `skill_refs` resolved into the bundle at freeze. Find/author store+// skills with `@posthog/llm-skills-search` / `@posthog/llm-skills-create`, then+// attach them with `@posthog/agent-applications-revisions-skill-refs-set`.+export const posthogAgentApplicationsRevisionsSkillRefsSetV1 = defineNativeTool({+ id: '@posthog/agent-applications-revisions-skill-refs-set',description:- "Upsert one skill in a draft revision. Body shape `{ description, body, files? }`. `description` is the model-facing 'when to load' hint surfaced in the skill index. `body` is the skill markdown. `files[]` is optional companion docs (path relative to `skills/<id>/files/`). Skill id is the URL path.",+ "Set the complete list of store-skill references on a draft revision (full replace). Each ref is `{ from_template, alias, version? }`: `from_template` is the skill NAME in the llma-skill store, `alias` is the folder it's materialized under in the bundle (`skills/<alias>/`), `version` optionally pins a published version (omit to pin the latest at freeze). At freeze the referenced skills are resolved and baked into the bundle. Find skills with `@posthog/llm-skills-search`; author a new one with `@posthog/llm-skills-create`. Draft-only.",args: Type.Object({project_id: ProjectIdArg,...agentRefFields,revision_id: Type.String({ description: 'Revision UUID (must be `state=draft`).' }),- skill_id: Type.String({ description: 'Skill slug (lowercase alphanumeric, hyphens, underscores).' }),- description: Type.String({ description: 'Short summary the model uses to decide when to load.' }),- body: Type.String({ description: 'Skill markdown body.' }),- files: Type.Optional(- Type.Array(Type.Object({ path: Type.String(), content: Type.String() }), {- description: 'Optional companion files. path is relative to `skills/<id>/files/`.',- })+ skill_refs: Type.Array(+ Type.Object({+ from_template: Type.String({ description: 'Skill name in the llma-skill store to pin.' }),+ alias: Type.String({+ description:+ 'Bundle folder the skill is materialized under (lowercase letters, digits, hyphens, underscores); unique within the revision.',+ }),+ version: Type.Optional(+ Type.Integer({ description: 'Pinned published version. Omit to pin the latest at freeze.' })+ ),+ }),+ { description: 'The complete set of references; replaces any existing ones.' }),}),- returns: Type.Object({ ok: Type.Boolean(), skill_id: Type.String() }),+ returns: Type.Record(Type.String(), Type.Unknown()),requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },cost_hint: 'cheap',async run(args, ctx) {const id = await resolveApplicationId(ctx, args)return callPosthogApi(ctx, {method: 'PUT',- path: projectPath(- args.project_id,- `/agent_applications/${id}/revisions/${args.revision_id}/skills/${args.skill_id}/`- ),- body: { description: args.description, body: args.body, files: args.files ?? [] },+ path: projectPath(args.project_id, `/agent_applications/${id}/revisions/${args.revision_id}/skill_refs/`),+ body: { skill_refs: args.skill_refs },})},})-export const posthogAgentApplicationsRevisionsSkillsDestroyV1 = defineNativeTool({- id: '@posthog/agent-applications-revisions-skills-destroy',- description: 'Delete one skill (body + every companion file). Draft-only.',+export const posthogLlmSkillsSearchV1 = defineNativeTool({+ id: '@posthog/llm-skills-search',+ description:+ 'Search the llma-skill store for reusable skills in this project. Returns name, description, version, category per match. Use to find a skill to attach to an agent (via `@posthog/agent-applications-revisions-skill-refs-set`) before authoring a new one.',args: Type.Object({project_id: ProjectIdArg,- ...agentRefFields,- revision_id: Type.String({ description: 'Revision UUID (must be `state=draft`).' }),- skill_id: Type.String({ description: 'Skill slug.' }),+ search: Type.Optional(+ Type.String({ description: 'Free-text search over name + description. Omit to list all skills.' })+ ),}),- returns: Type.Object({ ok: Type.Boolean(), skill_id: Type.String() }),- requires: { provider: { id: 'posthog', scopes: ['agents:write'] } },+ returns: Type.Object({ results: Type.Array(Type.Record(Type.String(), Type.Unknown())) }),+ requires: { provider: { id: 'posthog', scopes: ['llm_skill:read'] } },+ cost_hint: 'cheap',+ async run(args, ctx) {+ const data = await callPosthogApi<ListResponse<Record<string, unknown>>>(ctx, {+ method: 'GET',+ path: projectPath(args.project_id, '/llm_skills/'),+ query: args.search ? { search: args.search } : undefined,+ })+ return { results: data.results }+ },+})++export const posthogLlmSkillsCreateV1 = defineNativeTool({+ id: '@posthog/llm-skills-create',+ description:+ 'Author a new skill in the llma-skill store — the canonical place skills live. Provide `name` (stable id across versions), `description` (when-to-load hint shown in the agent skill index), `body` (SKILL.md markdown), and optional `files` (companion docs). Returns the created skill. Attach it to an agent with `@posthog/agent-applications-revisions-skill-refs-set`.',+ args: Type.Object({+ project_id: ProjectIdArg,+ name: Type.String({ description: 'Skill name — stable identifier across versions.' }),+ description: Type.String({ description: 'When-to-load hint shown in the agent skill index.' }),+ body: Type.String({ description: 'SKILL.md markdown body.' }),+ files: Type.Optional(+ Type.Array(Type.Object({ path: Type.String(), content: Type.String() }), {+ description: 'Optional companion files (path relative to the skill folder).',+ })+ ),+ }),+ returns: Type.Record(Type.String(), Type.Unknown()),+ requires: { provider: { id: 'posthog', scopes: ['llm_skill:write'] } },cost_hint: 'cheap',async run(args, ctx) {- const id = await resolveApplicationId(ctx, args)return callPosthogApi(ctx, {- method: 'DELETE',- path: projectPath(- args.project_id,- `/agent_applications/${id}/revisions/${args.revision_id}/skills/${args.skill_id}/`- ),+ method: 'POST',+ path: projectPath(args.project_id, '/llm_skills/'),+ body: { name: args.name, description: args.description, body: args.body, files: args.files ?? [] },})},})diff --git a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.tsindex 527dea994291..b64784dd8389 100644--- a/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts+++ b/products/agent_platform/services/agent-tools/src/tools/posthog-spec-schema.v1.ts@@ -79,7 +79,7 @@ const SECTION_NOTES: Record<string, string[]> = {],tools: ['`tools[]` is a discriminated union on `kind` (`native` | `custom` | `client`). For valid `native` ids call `@posthog/agent-applications-native-tools-list` — the validator rejects unknown ids.',- 'Skill and custom-tool *content* is uploaded via the bundle file tools (`-skills-update` / `-tools-update`), not inline in the spec.',+ 'Skills come from the llma-skill store: author/find with `@posthog/llm-skills-create` / `@posthog/llm-skills-search`, then reference them with `@posthog/agent-applications-revisions-skill-refs-set` (they are NOT authored inline). Custom-tool *content* is uploaded via `-tools-update`, not inline in the spec.',],secrets: ['`secrets[]` entries are a bare string (resolvable, no egress authority) or `{ name, allowed_hosts }` (required to let `@posthog/http-request` send the secret to those hosts).',diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex dc0f2b15138b..d11df3083ec4 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -104,14 +104,23 @@ def get_skill_by_name_from_db(skill_name: str,version: int | None = None,version_id: str | None = None,+ *,+ include_archived: bool = False,) -> LLMSkill | None:queryset = get_active_skill_queryset(team).filter(name=skill_name)if version_id is not None:- queryset = queryset.filter(id=version_id)+ # `include_archived` honours a pin to one immutable version row even after+ # the skill was archived (soft-deleted across all versions) — so a frozen+ # agent's fork can still re-freeze against the exact version it shipped.+ rows = (+ LLMSkill.objects.filter(team=team, name=skill_name, id=version_id)+ if include_archived+ else queryset.filter(id=version_id)+ )if version is not None:- queryset = queryset.filter(version=version)- return queryset.order_by("created_at", "id").first()+ rows = rows.filter(version=version)+ return rows.order_by("created_at", "id").first()if version is None:return queryset.filter(is_latest=True).order_by("-version", "-created_at", "-id").first()diff --git a/pyproject.toml b/pyproject.tomlindex 993c42ad9628..8a4c96c42400 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -516,6 +516,7 @@ ignore_imports = ["products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.internal_jwt","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.janitor_client","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.posthog_identity_app",+ "products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.skill_resolution","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.spec_schema","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.models","products.mcp_analytics.backend.presentation.views -> products.mcp_analytics.backend.logic",diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yamlindex e28970e68960..c2fc5849e339 100644--- a/services/mcp/definitions/agent_platform.yaml+++ b/services/mcp/definitions/agent_platform.yaml@@ -234,9 +234,11 @@ tools:idempotent: falsetitle: Full-replace the typed bundledescription: >- Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in- the payload is deleted. For incremental edits use the single-resource PUTs- (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled+ Body shape is `{ agent_md, tools, spec }` — **full replace**, anything not in the payload is deleted. Skills+ are NOT authored here: they come from the llma-skill store via `skill_refs` and are materialized at freeze+ (set them with `agent-applications-revisions-skill-refs-update`). For incremental edits use the+ single-resource PUTs (`agent-applications-revisions-agent-md-update`,+ `agent-applications-revisions-tools-update`). Each tool source is AST-checked + esbuild-compiledsynchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this.Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate →freeze → promote workflow.@@ -404,35 +406,25 @@ tools:agent-applications-revisions-set-env-create:operation: agent_applications_revisions_set_env_createenabled: false- agent-applications-revisions-skills-destroy:- operation: agent_applications_revisions_skills_destroy+ agent-applications-revisions-skill-refs-update:+ operation: agent_applications_revisions_skill_refs_updateenabled: truescopes:- agents:writeannotations:readOnly: false- destructive: true- idempotent: true- title: Delete one skill- description: >- Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist.- Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch- → validate → freeze → promote workflow.- agent-applications-revisions-skills-update:- operation: agent_applications_revisions_skills_update- enabled: true- scopes:- - agents:write- annotations:- readOnly: false- destructive: true+ destructive: falseidempotent: true- title: Upsert one skill- description: >- Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is- stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only. Playbook: read the- `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote- workflow.+ title: Set a draft's store-skill references+ description: >+ Full-replace the draft revision's store-skill references (`skill_refs`). Each ref is `{ from_template,+ alias, version? }`: `from_template` is the skill NAME in the llma-skill store, `alias` is the folder it's+ materialized under in the bundle (`skills/<alias>/`, lowercase letters/digits/hyphens/underscores, unique+ within the revision), and optional `version` pins a published version (omit to pin the latest at freeze). At+ freeze each referenced skill is resolved and baked into the immutable bundle, so a frozen agent never+ re-resolves a changed skill. Find skills with `skill-list`; author a new one with `skill-create`. Not+ destructive — it only changes which skills the draft pins, never deletes skill content. Draft-only.+ Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource`.agent-applications-revisions-slack-manifest:operation: agent_applications_revisions_slack_manifestenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 21d4fa277c09..fef669b12ee6 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -427,7 +427,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-bundle-update": {- "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.",+ "description": "Body shape is `{ agent_md, tools, spec }` — **full replace**, anything not in the payload is deleted. Skills are NOT authored here: they come from the llma-skill store via `skill_refs` and are materialized at freeze (set them with `agent-applications-revisions-skill-refs-update`). For incremental edits use the single-resource PUTs (`agent-applications-revisions-agent-md-update`, `agent-applications-revisions-tools-update`). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Full-replace the typed bundle",@@ -591,30 +591,15 @@},"feature_flag": "agent-platform"},- "agent-applications-revisions-skills-destroy": {- "description": "Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.",+ "agent-applications-revisions-skill-refs-update": {+ "description": "Full-replace the draft revision's store-skill references (`skill_refs`). Each ref is `{ from_template, alias, version? }`: `from_template` is the skill NAME in the llma-skill store, `alias` is the folder it's materialized under in the bundle (`skills/<alias>/`, lowercase letters/digits/hyphens/underscores, unique within the revision), and optional `version` pins a published version (omit to pin the latest at freeze). At freeze each referenced skill is resolved and baked into the immutable bundle, so a frozen agent never re-resolves a changed skill. Find skills with `skill-list`; author a new one with `skill-create`. Not destructive — it only changes which skills the draft pins, never deletes skill content. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource`.","category": "Agent stack","feature": "agent_platform",- "summary": "Delete one skill",- "title": "Delete one skill",+ "summary": "Set a draft's store-skill references",+ "title": "Set a draft's store-skill references","required_scopes": ["agents:write"],"annotations": {- "destructiveHint": true,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- },- "feature_flag": "agent-platform"- },- "agent-applications-revisions-skills-update": {- "description": "Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.",- "category": "Agent stack",- "feature": "agent_platform",- "summary": "Upsert one skill",- "title": "Upsert one skill",- "required_scopes": ["agents:write"],- "annotations": {- "destructiveHint": true,+ "destructiveHint": false,"idempotentHint": true,"openWorldHint": true,"readOnlyHint": falsediff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex a3fe8ef5809e..dddfb10e1958 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -427,7 +427,7 @@"feature_flag": "agent-platform"},"agent-applications-revisions-bundle-update": {- "description": "Body shape matches the GET response: `{ agent_md, skills, tools, spec }`. **Full replace** — anything not in the payload is deleted. For incremental edits use the single-resource PUTs (`agent-applications-revisions-skills-update`, etc.). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.",+ "description": "Body shape is `{ agent_md, tools, spec }` — **full replace**, anything not in the payload is deleted. Skills are NOT authored here: they come from the llma-skill store via `skill_refs` and are materialized at freeze (set them with `agent-applications-revisions-skill-refs-update`). For incremental edits use the single-resource PUTs (`agent-applications-revisions-agent-md-update`, `agent-applications-revisions-tools-update`). Each tool source is AST-checked + esbuild-compiled synchronously; a bad shape returns 422 before any S3 writes. Only `state=draft` revisions accept this. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.","category": "Agent stack","feature": "agent_platform","summary": "Full-replace the typed bundle",@@ -591,30 +591,15 @@},"feature_flag": "agent-platform"},- "agent-applications-revisions-skills-destroy": {- "description": "Removes the skill folder (`skills/<id>/`, holding its `SKILL.md`). Returns 404 if the skill doesn't exist. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.",+ "agent-applications-revisions-skill-refs-update": {+ "description": "Full-replace the draft revision's store-skill references (`skill_refs`). Each ref is `{ from_template, alias, version? }`: `from_template` is the skill NAME in the llma-skill store, `alias` is the folder it's materialized under in the bundle (`skills/<alias>/`, lowercase letters/digits/hyphens/underscores, unique within the revision), and optional `version` pins a published version (omit to pin the latest at freeze). At freeze each referenced skill is resolved and baked into the immutable bundle, so a frozen agent never re-resolves a changed skill. Find skills with `skill-list`; author a new one with `skill-create`. Not destructive — it only changes which skills the draft pins, never deletes skill content. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource`.","category": "Agent stack","feature": "agent_platform",- "summary": "Delete one skill",- "title": "Delete one skill",+ "summary": "Set a draft's store-skill references",+ "title": "Set a draft's store-skill references","required_scopes": ["agents:write"],"annotations": {- "destructiveHint": true,- "idempotentHint": true,- "openWorldHint": true,- "readOnlyHint": false- },- "feature_flag": "agent-platform"- },- "agent-applications-revisions-skills-update": {- "description": "Body `{ description, body }`. Creates the skill if it doesn't exist, replaces it if it does. The `body` is stored at `skills/<skill_id>/SKILL.md`. Skill id comes from the URL. Draft-only. Playbook: read the `editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promote workflow.",- "category": "Agent stack",- "feature": "agent_platform",- "summary": "Upsert one skill",- "title": "Upsert one skill",- "required_scopes": ["agents:write"],- "annotations": {- "destructiveHint": true,+ "destructiveHint": false,"idempotentHint": true,"openWorldHint": true,"readOnlyHint": falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 43d92cb63b35..5a57dda65d34 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -8262,7 +8262,7 @@ export namespace Schemas {kind: 'custom_template';from_template: string;alias: string;- /** @minimum 0 */+ /** @minimum 1 */version?: number;} | {kind: 'client';@@ -8317,8 +8317,9 @@ export namespace Schemas {description?: string;from_template?: string;alias?: string;- /** @minimum 0 */+ /** @minimum 1 */version?: number;+ source_version_id?: string;};export type AgentRevisionSpecIdentityProvidersItem = {@@ -8470,6 +8471,29 @@ export namespace Schemas {Archived: 'archived',} as const;+ /**+ * One reference to a versioned skill in the llma-skill store, pinned into+ * this agent's bundle at freeze.+ */+ export interface SkillRef {+ /**+ * Name of the skill in the llma-skill store to pin into this agent. Resolved at freeze to the chosen `version` and materialized into the bundle.+ * @maxLength 64+ */+ from_template: string;+ /**+ * Folder the resolved skill is materialized under in the bundle (`skills/<alias>/`). Lowercase letters, digits, hyphens or underscores, starting and ending with a letter or digit; must be unique within the revision.+ * @maxLength 64+ * @pattern ^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$+ */+ alias: string;+ /**+ * Specific published version to pin. Omit to pin the store's latest version at freeze time.+ * @minimum 1+ */+ version?: number;+ }+export interface AgentRevision {readonly id: string;readonly application: string;@@ -8481,6 +8505,8 @@ export namespace Schemas {/** @nullable */readonly bundle_sha256: string | null;spec?: AgentRevisionSpec;+ /** Store-skill references for this draft, set via the `skill_refs` action and resolved into the bundle at freeze. Preserved as the authoring record on the frozen revision (and carried forward when forking a new draft); resolved provenance is stamped onto `spec.skills[].source_version_id`. */+ readonly skill_refs: readonly SkillRef[];/** @nullable */readonly created_by_id: number | null;/**@@ -34838,7 +34864,7 @@ export namespace Schemas {kind: 'custom_template';from_template: string;alias: string;- /** @minimum 0 */+ /** @minimum 1 */version?: number;} | {kind: 'client';@@ -34893,8 +34919,9 @@ export namespace Schemas {description?: string;from_template?: string;alias?: string;- /** @minimum 0 */+ /** @minimum 1 */version?: number;+ source_version_id?: string;};export type PatchedAgentRevisionSpecIdentityProvidersItem = {@@ -35041,6 +35068,8 @@ export namespace Schemas {/** @nullable */readonly bundle_sha256?: string | null;spec?: PatchedAgentRevisionSpec;+ /** Store-skill references for this draft, set via the `skill_refs` action and resolved into the bundle at freeze. Preserved as the authoring record on the frozen revision (and carried forward when forking a new draft); resolved provenance is stamped onto `spec.skills[].source_version_id`. */+ readonly skill_refs?: readonly SkillRef[];/** @nullable */readonly created_by_id?: number | null;/**@@ -46670,6 +46699,14 @@ export namespace Schemas {env: SetEnvRequestEnv;}+ /**+ * Body for PUT /revisions/<id>/skill_refs/ — full-replace the draft's references.+ */+ export interface SetSkillRefsRequest {+ /** The complete set of store-skill references for this draft; replaces any existing references. */+ skill_refs: SkillRef[];+ }+/*** * `trace` - trace* * `debug` - debug@@ -51918,17 +51955,6 @@ export namespace Schemas {content: string;}- /**- * Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored- * at the canonical `skills/<skill_id>/SKILL.md` path in the bundle.- */- export interface WriteSkillRequest {- /** One-line summary shown in the skill index; the model uses it to decide when to load the skill. */- description: string;- /** The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`. */- body: string;- }-export type WriteSpecRequestSpec = { [key: string]: unknown };/**@@ -51954,11 +51980,11 @@ export namespace Schemas {/*** Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed- * payload.+ * payload. Skills are not authored here: they come from the llma-skill store+ * via `skill_refs` and are materialized into the bundle at freeze.*/export interface WriteTypedBundleRequest {agent_md: string;- skills?: WriteSkillRequest[];tools?: WriteToolRequest[];spec: WriteTypedBundleRequestSpec;}diff --git a/services/mcp/src/generated/agent_platform/api.ts b/services/mcp/src/generated/agent_platform/api.tsindex 99b542c56990..663a81c63f0b 100644--- a/services/mcp/src/generated/agent_platform/api.ts+++ b/services/mcp/src/generated/agent_platform/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 35 enabled ops+ * PostHog API - MCP 34 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -198,8 +198,6 @@ export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTexport const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000export const agentApplicationsRevisionsCreateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000-export const agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin = 0-export const agentApplicationsRevisionsCreateBodySpecToolsItemFourArgsSchemaDefault = {}export const agentApplicationsRevisionsCreateBodySpecToolsItemFourRequiredDefault = falseexport const agentApplicationsRevisionsCreateBodySpecToolsItemFourTimeoutMsDefault = 5000@@ -217,8 +215,6 @@ export const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovaexport const agentApplicationsRevisionsCreateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000export const agentApplicationsRevisionsCreateBodySpecMcpsDefault = []-export const agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin = 0-export const agentApplicationsRevisionsCreateBodySpecSkillsDefault = []export const agentApplicationsRevisionsCreateBodySpecIdentityProvidersItemOneIdDefault = `posthog`@@ -551,10 +547,7 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({kind: zod.literal('custom_template'),from_template: zod.string(),alias: zod.string(),- version: zod- .number()- .min(agentApplicationsRevisionsCreateBodySpecToolsItemThreeVersionMin)- .optional(),+ version: zod.number().min(1).optional(),}),zod.object({kind: zod.literal('client'),@@ -643,10 +636,8 @@ export const AgentApplicationsRevisionsCreateBody = /* @__PURE__ */ zod.object({description: zod.string().optional(),from_template: zod.string().optional(),alias: zod.string().optional(),- version: zod- .number()- .min(agentApplicationsRevisionsCreateBodySpecSkillsItemVersionMin)- .optional(),+ version: zod.number().min(1).optional(),+ source_version_id: zod.string().optional(),})).default(agentApplicationsRevisionsCreateBodySpecSkillsDefault),@@ -884,8 +875,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalexport const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMin = 60000export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemTwoApprovalPolicyTtlMsMax = 604800000-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin = 0-export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourArgsSchemaDefault = {}export const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourRequiredDefault = falseexport const agentApplicationsRevisionsPartialUpdateBodySpecToolsItemFourTimeoutMsDefault = 5000@@ -903,8 +892,6 @@ export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoexport const agentApplicationsRevisionsPartialUpdateBodySpecMcpsItemToolsItemTwoApprovalPolicyTtlMsMax = 604800000export const agentApplicationsRevisionsPartialUpdateBodySpecMcpsDefault = []-export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin = 0-export const agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault = []export const agentApplicationsRevisionsPartialUpdateBodySpecIdentityProvidersItemOneIdDefault = `posthog`@@ -1251,10 +1238,7 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.okind: zod.literal('custom_template'),from_template: zod.string(),alias: zod.string(),- version: zod- .number()- .min(agentApplicationsRevisionsPartialUpdateBodySpecToolsItemThreeVersionMin)- .optional(),+ version: zod.number().min(1).optional(),}),zod.object({kind: zod.literal('client'),@@ -1345,10 +1329,8 @@ export const AgentApplicationsRevisionsPartialUpdateBody = /* @__PURE__ */ zod.odescription: zod.string().optional(),from_template: zod.string().optional(),alias: zod.string().optional(),- version: zod- .number()- .min(agentApplicationsRevisionsPartialUpdateBodySpecSkillsItemVersionMin)- .optional(),+ version: zod.number().min(1).optional(),+ source_version_id: zod.string().optional(),})).default(agentApplicationsRevisionsPartialUpdateBodySpecSkillsDefault),@@ -1567,24 +1549,6 @@ export const AgentApplicationsRevisionsBundleUpdateParams = /* @__PURE__ */ zod.export const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod.object({agent_md: zod.string(),- skills: zod- .array(- zod- .object({- description: zod- .string()- .describe(- 'One-line summary shown in the skill index; the model uses it to decide when to load the skill.'- ),- body: zod- .string()- .describe("The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`."),- })- .describe(- 'Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored\nat the canonical `skills/<skill_id>/SKILL.md` path in the bundle.'- )- )- .optional(),tools: zod.array(zod@@ -1598,7 +1562,9 @@ export const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod.optional(),spec: zod.record(zod.string(), zod.unknown()),})- .describe('Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed\npayload.')+ .describe(+ 'Body shape for PUT /revisions/<id>/bundle/ — the full-replace typed\npayload. Skills are not authored here: they come from the llma-skill store\nvia `skill_refs` and are materialized into the bundle at freeze.'+ )/*** Copy every file from `source_revision_id` into this revision.@@ -1767,35 +1733,11 @@ export const AgentApplicationsRevisionsPromoteCreateParams = /* @__PURE__ */ zod})/**- * Revisions of an agent. Created in `draft`, promoted through- * `ready → live` once the bundle has been uploaded + frozen.- *- * URLs (nested under an application):- *- * Model CRUD:- * GET .../revisions/ list- * POST .../revisions/ create draft- * GET .../revisions/<id>/ retrieve- * PATCH .../revisions/<id>/ update spec (draft only)- *- * Lifecycle:- * POST .../revisions/<id>/promote/ ready → live- * POST .../revisions/<id>/archive/ → archived- * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)- * POST .../revisions/<id>/clone_from/ copy bundle from another rev- * POST .../revisions/new_draft/ create draft + clone_from atomically- *- * Bundle authoring (proxied to the janitor):- * GET .../revisions/<id>/manifest/ list paths + sha256- * GET .../revisions/<id>/file/?path=… read one file- * PUT .../revisions/<id>/file/?path=… write one file (draft)- * DELETE .../revisions/<id>/file/?path=… delete one file (draft)- * GET .../revisions/<id>/bundle/ bulk pull all files- * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)+ * Full-replace the draft's store-skill references. They are resolved+ * and materialized into the bundle at freeze, not here — this only records+ * which skills (and pinned versions) the freeze should pull in.*/-export const agentApplicationsRevisionsSkillsUpdatePathSkillIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')--export const AgentApplicationsRevisionsSkillsUpdateParams = /* @__PURE__ */ zod.object({+export const AgentApplicationsRevisionsSkillRefsUpdateParams = /* @__PURE__ */ zod.object({application_id: zod.string(),id: zod.string().describe('A UUID string identifying this agent revision.'),project_id: zod@@ -1803,59 +1745,50 @@ export const AgentApplicationsRevisionsSkillsUpdateParams = /* @__PURE__ */ zod..describe("Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."),- skill_id: zod.string().regex(agentApplicationsRevisionsSkillsUpdatePathSkillIdRegExp),})-export const AgentApplicationsRevisionsSkillsUpdateBody = /* @__PURE__ */ zod- .object({- description: zod- .string()- .describe('One-line summary shown in the skill index; the model uses it to decide when to load the skill.'),- body: zod.string().describe("The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`."),- })- .describe(- 'Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored\nat the canonical `skills/<skill_id>/SKILL.md` path in the bundle.'- )+export const agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemFromTemplateMax = 64-/**- * Revisions of an agent. Created in `draft`, promoted through- * `ready → live` once the bundle has been uploaded + frozen.- *- * URLs (nested under an application):- *- * Model CRUD:- * GET .../revisions/ list- * POST .../revisions/ create draft- * GET .../revisions/<id>/ retrieve- * PATCH .../revisions/<id>/ update spec (draft only)- *- * Lifecycle:- * POST .../revisions/<id>/promote/ ready → live- * POST .../revisions/<id>/archive/ → archived- * POST .../revisions/<id>/freeze/ draft → ready (stamps sha256)- * POST .../revisions/<id>/clone_from/ copy bundle from another rev- * POST .../revisions/new_draft/ create draft + clone_from atomically- *- * Bundle authoring (proxied to the janitor):- * GET .../revisions/<id>/manifest/ list paths + sha256- * GET .../revisions/<id>/file/?path=… read one file- * PUT .../revisions/<id>/file/?path=… write one file (draft)- * DELETE .../revisions/<id>/file/?path=… delete one file (draft)- * GET .../revisions/<id>/bundle/ bulk pull all files- * PUT .../revisions/<id>/bundle/ bulk push (replace|merge)- */-export const agentApplicationsRevisionsSkillsDestroyPathSkillIdRegExp = new RegExp('^[a-z0-9][a-z0-9_-]*$')+export const agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasMax = 64-export const AgentApplicationsRevisionsSkillsDestroyParams = /* @__PURE__ */ zod.object({- application_id: zod.string(),- id: zod.string().describe('A UUID string identifying this agent revision.'),- project_id: zod- .string()- .describe(- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."- ),- skill_id: zod.string().regex(agentApplicationsRevisionsSkillsDestroyPathSkillIdRegExp),-})+export const agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasRegExp = new RegExp(+ '^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$'+)++export const AgentApplicationsRevisionsSkillRefsUpdateBody = /* @__PURE__ */ zod+ .object({+ skill_refs: zod+ .array(+ zod+ .object({+ from_template: zod+ .string()+ .max(agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemFromTemplateMax)+ .describe(+ 'Name of the skill in the llma-skill store to pin into this agent. Resolved at freeze to the chosen `version` and materialized into the bundle.'+ ),+ alias: zod+ .string()+ .max(agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasMax)+ .regex(agentApplicationsRevisionsSkillRefsUpdateBodySkillRefsItemAliasRegExp)+ .describe(+ 'Folder the resolved skill is materialized under in the bundle (`skills/<alias>/`). Lowercase letters, digits, hyphens or underscores, starting and ending with a letter or digit; must be unique within the revision.'+ ),+ version: zod+ .number()+ .min(1)+ .optional()+ .describe(+ "Specific published version to pin. Omit to pin the store's latest version at freeze time."+ ),+ })+ .describe(+ "One reference to a versioned skill in the llma-skill store, pinned into\nthis agent's bundle at freeze."+ )+ )+ .describe('The complete set of store-skill references for this draft; replaces any existing references.'),+ })+ .describe("Body for PUT /revisions/<id>/skill_refs/ — full-replace the draft's references.")/*** Build a Slack app manifest for this revision's slack trigger.diff --git a/services/mcp/src/tools/agentPlatform/playbookTools.ts b/services/mcp/src/tools/agentPlatform/playbookTools.tsindex 518cd7ea6cdc..4fa0af8bbe38 100644--- a/services/mcp/src/tools/agentPlatform/playbookTools.ts+++ b/services/mcp/src/tools/agentPlatform/playbookTools.ts@@ -32,8 +32,7 @@ export const PLAYBOOK_TOOLS: Partial<Record<PlaybookId, readonly string[]>> = {'agent-applications-revisions-clone-from-create','agent-applications-revisions-agent-md-update','agent-applications-revisions-spec-update',- 'agent-applications-revisions-skills-update',- 'agent-applications-revisions-skills-destroy',+ 'agent-applications-revisions-skill-refs-update','agent-applications-revisions-tools-update','agent-applications-revisions-tools-destroy','agent-applications-revisions-bundle-update',diff --git a/services/mcp/src/tools/generated/agent_platform.ts b/services/mcp/src/tools/generated/agent_platform.tsindex 1cd45de9fd1b..51859b24c2fd 100644--- a/services/mcp/src/tools/generated/agent_platform.ts+++ b/services/mcp/src/tools/generated/agent_platform.ts@@ -34,9 +34,8 @@ import {AgentApplicationsRevisionsPartialUpdateParams,AgentApplicationsRevisionsPromoteCreateParams,AgentApplicationsRevisionsRetrieveParams,- AgentApplicationsRevisionsSkillsDestroyParams,- AgentApplicationsRevisionsSkillsUpdateBody,- AgentApplicationsRevisionsSkillsUpdateParams,+ AgentApplicationsRevisionsSkillRefsUpdateBody,+ AgentApplicationsRevisionsSkillRefsUpdateParams,AgentApplicationsRevisionsSlackManifestParams,AgentApplicationsRevisionsSpecUpdateBody,AgentApplicationsRevisionsSpecUpdateParams,@@ -332,9 +331,6 @@ const agentApplicationsRevisionsBundleUpdate = (): ToolBase<if (params.agent_md !== undefined) {body['agent_md'] = params.agent_md}- if (params.skills !== undefined) {- body['skills'] = params.skills- }if (params.tools !== undefined) {body['tools'] = params.tools}@@ -595,48 +591,25 @@ const agentApplicationsRevisionsRetrieve = (): ToolBase<},})-const AgentApplicationsRevisionsSkillsDestroySchema = AgentApplicationsRevisionsSkillsDestroyParams.omit({+const AgentApplicationsRevisionsSkillRefsUpdateSchema = AgentApplicationsRevisionsSkillRefsUpdateParams.omit({project_id: true,-})+}).extend(AgentApplicationsRevisionsSkillRefsUpdateBody.shape)-const agentApplicationsRevisionsSkillsDestroy = (): ToolBase<- typeof AgentApplicationsRevisionsSkillsDestroySchema,- unknown-> => ({- name: 'agent-applications-revisions-skills-destroy',- schema: AgentApplicationsRevisionsSkillsDestroySchema,- handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSkillsDestroySchema>) => {- const projectId = await context.stateManager.getProjectId()- const result = await context.api.request<unknown>({- method: 'DELETE',- path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/skills/${encodeURIComponent(String(params.skill_id))}/`,- })- return result- },-})--const AgentApplicationsRevisionsSkillsUpdateSchema = AgentApplicationsRevisionsSkillsUpdateParams.omit({- project_id: true,-}).extend(AgentApplicationsRevisionsSkillsUpdateBody.shape)--const agentApplicationsRevisionsSkillsUpdate = (): ToolBase<- typeof AgentApplicationsRevisionsSkillsUpdateSchema,+const agentApplicationsRevisionsSkillRefsUpdate = (): ToolBase<+ typeof AgentApplicationsRevisionsSkillRefsUpdateSchema,Schemas.AgentRevision> => ({- name: 'agent-applications-revisions-skills-update',- schema: AgentApplicationsRevisionsSkillsUpdateSchema,- handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSkillsUpdateSchema>) => {+ name: 'agent-applications-revisions-skill-refs-update',+ schema: AgentApplicationsRevisionsSkillRefsUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof AgentApplicationsRevisionsSkillRefsUpdateSchema>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}- if (params.description !== undefined) {- body['description'] = params.description- }- if (params.body !== undefined) {- body['body'] = params.body+ if (params.skill_refs !== undefined) {+ body['skill_refs'] = params.skill_refs}const result = await context.api.request<Schemas.AgentRevision>({method: 'PUT',- path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/skills/${encodeURIComponent(String(params.skill_id))}/`,+ path: `/api/projects/${encodeURIComponent(String(projectId))}/agent_applications/${encodeURIComponent(String(params.application_id))}/revisions/${encodeURIComponent(String(params.id))}/skill_refs/`,body,})return result@@ -901,8 +874,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'agent-applications-revisions-partial-update': agentApplicationsRevisionsPartialUpdate,'agent-applications-revisions-promote-create': agentApplicationsRevisionsPromoteCreate,'agent-applications-revisions-retrieve': agentApplicationsRevisionsRetrieve,- 'agent-applications-revisions-skills-destroy': agentApplicationsRevisionsSkillsDestroy,- 'agent-applications-revisions-skills-update': agentApplicationsRevisionsSkillsUpdate,+ 'agent-applications-revisions-skill-refs-update': agentApplicationsRevisionsSkillRefsUpdate,'agent-applications-revisions-slack-manifest': agentApplicationsRevisionsSlackManifest,'agent-applications-revisions-spec-update': agentApplicationsRevisionsSpecUpdate,'agent-applications-revisions-system-prompt': agentApplicationsRevisionsSystemPrompt,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.jsonindex 6fa5eaeeef42..b5dcf7c1207b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-bundle-update.json@@ -11,24 +11,6 @@"description": "A UUID string identifying this agent revision.","type": "string"},- "skills": {- "items": {- "description": "Body shape for PUT /revisions/<id>/skills/<skill_id>/. The body is stored\nat the canonical `skills/<skill_id>/SKILL.md` path in the bundle.",- "properties": {- "body": {- "description": "The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`.",- "type": "string"- },- "description": {- "description": "One-line summary shown in the skill index; the model uses it to decide when to load the skill.",- "type": "string"- }- },- "required": ["description", "body"],- "type": "object"- },- "type": "array"- },"spec": {"additionalProperties": {},"propertyNames": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.jsonindex 507180f08760..2603091c61e7 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-create.json@@ -341,8 +341,11 @@"path": {"type": "string"},+ "source_version_id": {+ "type": "string"+ },"version": {- "minimum": 0,+ "minimum": 1,"type": "number"}},@@ -448,7 +451,7 @@"type": "string"},"version": {- "minimum": 0,+ "minimum": 1,"type": "number"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.jsonindex 61b6d0115e06..70ce76ef3428 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-partial-update.json@@ -344,8 +344,11 @@"path": {"type": "string"},+ "source_version_id": {+ "type": "string"+ },"version": {- "minimum": 0,+ "minimum": 1,"type": "number"}},@@ -451,7 +454,7 @@"type": "string"},"version": {- "minimum": 0,+ "minimum": 1,"type": "number"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skill-refs-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skill-refs-update.jsonnew file mode 100644index 000000000000..b0cf8025b2d4--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skill-refs-update.json@@ -0,0 +1,41 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "application_id": {+ "type": "string"+ },+ "id": {+ "description": "A UUID string identifying this agent revision.",+ "type": "string"+ },+ "skill_refs": {+ "description": "The complete set of store-skill references for this draft; replaces any existing references.",+ "items": {+ "description": "One reference to a versioned skill in the llma-skill store, pinned into\nthis agent's bundle at freeze.",+ "properties": {+ "alias": {+ "description": "Folder the resolved skill is materialized under in the bundle (`skills/<alias>/`). Lowercase letters, digits, hyphens or underscores, starting and ending with a letter or digit; must be unique within the revision.",+ "maxLength": 64,+ "pattern": "^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$",+ "type": "string"+ },+ "from_template": {+ "description": "Name of the skill in the llma-skill store to pin into this agent. Resolved at freeze to the chosen `version` and materialized into the bundle.",+ "maxLength": 64,+ "type": "string"+ },+ "version": {+ "description": "Specific published version to pin. Omit to pin the store's latest version at freeze time.",+ "minimum": 1,+ "type": "number"+ }+ },+ "required": ["from_template", "alias"],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": ["application_id", "id", "skill_refs"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-destroy.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-destroy.jsondeleted file mode 100644index 636af44180eb..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-destroy.json+++ /dev/null@@ -1,18 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "properties": {- "application_id": {- "type": "string"- },- "id": {- "description": "A UUID string identifying this agent revision.",- "type": "string"- },- "skill_id": {- "pattern": "^[a-z0-9][a-z0-9_-]*$",- "type": "string"- }- },- "required": ["application_id", "id", "skill_id"],- "type": "object"-}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-update.jsondeleted file mode 100644index b1c9639705c3..000000000000--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/agent-applications-revisions-skills-update.json+++ /dev/null@@ -1,26 +0,0 @@-{- "$schema": "https://json-schema.org/draft/2020-12/schema",- "properties": {- "application_id": {- "type": "string"- },- "body": {- "description": "The skill's full markdown body, stored at `skills/<skill_id>/SKILL.md`.",- "type": "string"- },- "description": {- "description": "One-line summary shown in the skill index; the model uses it to decide when to load the skill.",- "type": "string"- },- "id": {- "description": "A UUID string identifying this agent revision.",- "type": "string"- },- "skill_id": {- "pattern": "^[a-z0-9][a-z0-9_-]*$",- "type": "string"- }- },- "required": ["application_id", "id", "skill_id", "description", "body"],- "type": "object"-}diff --git a/tach.toml b/tach.tomlindex cf8ff347eb9b..da1c2f5e9719 100644--- a/tach.toml+++ b/tach.toml@@ -133,6 +133,7 @@ layer = "modules"path = "products.agent_platform"depends_on = ["posthog",+ "products.skills",]layer = "modules"