: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): add draft bundle edit endpoints (#65693)
Dylan Martin9e323575ad96
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 39ffc1c20c02..04c1b6b9c9f9 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -547,6 +547,9 @@ SPECTACULAR_SETTINGS = {# subset enums keep their own auto-resolved names."SignalSourceProduct": "products.signals.backend.enums.SIGNAL_SOURCE_PRODUCT_VALUES","SignalSourceType": "products.signals.backend.enums.SIGNAL_SOURCE_TYPE_VALUES",+ # AgentRevision.state (model ChoiceField) and RevisionNotDraftError.state (the+ # bundle-edit 409 body) share one choice set — pin them to a single named enum.+ "AgentRevisionStateEnum": ["draft", "ready", "live", "archived"],"CustomPropertyDisplayTypeEnum": ["text","number",diff --git a/products/agent_platform/backend/logic/skill_editing.py b/products/agent_platform/backend/logic/skill_editing.pynew file mode 100644index 000000000000..a1ef8ec65fdc--- /dev/null+++ b/products/agent_platform/backend/logic/skill_editing.py@@ -0,0 +1,198 @@+"""Store-backed editing of a draft revision's referenced skills.++Skills are store-only: freeze resolves ``AgentRevision.skill_refs`` against the+llma-skill store, materializes the pinned bytes into the bundle, and sweeps any+``skills/`` folder that isn't a current ref (see the freeze action). Writing a+skill's markdown into the draft bundle therefore can't stick — it would be+overwritten (ref alias) or deleted (orphan) at the next freeze. Instead an edit+publishes a new version of the store skill and the caller re-pins the draft's+ref to it, so the next freeze materializes exactly the edited bytes and the+store stays the single source of truth.+"""++from typing import Any++from rest_framework import status+from rest_framework.exceptions import APIException, PermissionDenied, ValidationError++from posthog.models import Team, User+from posthog.rbac.user_access_control import UserAccessControl++from products.skills.backend.api.skill_serializers import validate_skill_body_size, validate_skill_name_value+from products.skills.backend.api.skill_services import (+ LLMSkillDuplicateNameConflictError,+ LLMSkillNotFoundError,+ LLMSkillVersionConflictError,+ LLMSkillVersionLimitError,+ create_skill,+ get_skill_by_name_from_db,+ publish_skill_version,+)+from products.skills.backend.marketplace.packaging import SkillImportError, parse_skill_md+from products.skills.backend.models import LLMSkill+++class SkillStoreConflict(APIException):+ """The store skill changed between read and publish — caller should reload+ the latest version and retry. Plain string detail on purpose: exceptions_hog+ can't render dict details (see JanitorUpstreamError)."""++ status_code = status.HTTP_409_CONFLICT+ default_detail = "The skill changed in the store since you loaded it. Reload the latest version and try again."+ default_code = "skill_store_conflict"+++def assert_skills_writable(+ names: list[str],+ *,+ scopes: list[str] | None,+ user_access_control: UserAccessControl,+) -> None:+ """Authorize the caller to publish new versions of every named store skill.++ The write-side mirror of ``assert_skill_refs_readable``: these edits mutate+ ``llm_skill`` rows shared across every agent that references them, so they+ must honour the same boundary ``LLMSkillViewSet`` enforces on PATCH and+ create — the ``llm_skill:write`` API scope for token callers, plus+ editor-level access to the skills resource for everyone. Without this an+ ``agents:write`` caller could rewrite or mint shared skills through the+ agent authoring surface. ``scopes`` is ``None`` for session auth, which+ carries no API scopes.++ Skill access is governed at the RESOURCE level, for creates and updates+ alike: ``LLMSkill`` has no model→resource mapping (``model_to_resource``+ returns ``None`` for it), so ``check_access_level_for_object`` passes+ unconditionally and must not be mistaken for a boundary. The resource-level+ check is what ``LLMSkillViewSet`` actually enforces — it honours both+ team-wide lockdowns and member-specific grants on the inherited+ ``llm_analytics`` resource.+ """+ if not names:+ return+ if scopes is not None and not ({"*", "llm_skill:write"} & set(scopes)):+ raise PermissionDenied(+ "Editing store-backed skills requires the `llm_skill:write` scope in addition to `agents:write`."+ )+ if not user_access_control.check_access_level_for_resource("llm_skill", "editor"):+ raise PermissionDenied(+ "You do not have editor access to skills in the skill store, so you cannot publish or create "+ "store-backed skills through the agent surface. Ask a skill admin for editor access to skills."+ )+++def store_skill_exists(team: Team, name: str) -> bool:+ """Whether an active (non-archived) store skill with this name exists."""+ return get_skill_by_name_from_db(team, name) is not None+++# Mirrors LLMSkillPublishSerializer.description's max_length — the store caps+# it in its serializers, not the service layer, so this direct-service path+# must re-apply it.+_MAX_SKILL_DESCRIPTION_CHARS = 4096+++def validate_store_write(body: str | None, description: str | None, *, new_skill_name: str | None = None) -> None:+ """Re-apply the store's serializer-level rules. The skills API enforces body+ size, description length, and name format in `LLMSkill*Serializer`s; this+ path calls the services directly, so without these gates an agent editor+ could write rows the store's own API would reject (Django's request cap is+ 20 MB, well above the store's 1 MB body limit, and `create_skill` doesn't+ validate name format). Pure — safe to run up-front for all-or-nothing bulk+ validation and again at the publish/create choke points.++ ``new_skill_name`` is only for names about to be CREATED: the store's name+ rules (≤64 chars, hyphens not underscores, reserved-name blocklist) are+ stricter than the janitor's alias regex, and an existing skill's name needs+ no re-check."""+ if new_skill_name is not None:+ validate_skill_name_value(new_skill_name)+ if body is not None:+ validate_skill_body_size(body)+ if description is not None and len(description) > _MAX_SKILL_DESCRIPTION_CHARS:+ raise ValidationError(f"Skill description must be {_MAX_SKILL_DESCRIPTION_CHARS} characters or fewer.")+++def _publish_next_version(team: Team, *, user: User, skill_name: str, fields: dict[str, Any]) -> LLMSkill:+ """Publish ``fields`` on top of the store's latest version, mapping the+ service errors to API-shaped ones. Publishing targets latest — an edit means+ "move the skill forward", even when the draft's ref pins an older version;+ the caller re-pins the ref to the returned row.+ """+ validate_store_write(fields.get("body"), fields.get("description"))+ latest = get_skill_by_name_from_db(team, skill_name)+ if latest is None:+ raise ValidationError(+ f"Skill '{skill_name}' was not found in the skill store. It may have been archived — "+ "remove the reference or recreate the skill."+ )+ try:+ return publish_skill_version(team, user=user, skill_name=skill_name, base_version=latest.version, **fields)+ except LLMSkillNotFoundError:+ raise ValidationError(f"Skill '{skill_name}' was not found in the skill store.")+ except LLMSkillVersionConflictError:+ raise SkillStoreConflict()+ except LLMSkillVersionLimitError as e:+ raise ValidationError(+ f"Skill '{skill_name}' has reached the maximum of {e.max_version} versions. "+ "Archive and recreate the skill to continue publishing."+ )+++def publish_skill_body(+ team: Team,+ *,+ user: User,+ skill_name: str,+ body: str,+ description: str | None = None,+) -> LLMSkill:+ """Publish ``body`` (and optionally ``description``) as a new version of the+ named store skill; omitted fields carry forward from the current version."""+ return _publish_next_version(+ team, user=user, skill_name=skill_name, fields={"body": body, "description": description}+ )+++def publish_skill_md_edit(team: Team, *, user: User, skill_name: str, content: str) -> LLMSkill:+ """Publish edited SKILL.md content as a new version of the named store skill.++ The bundle's SKILL.md is ``render_skill_md`` output (frontmatter + body), so+ an edited file normally round-trips through ``parse_skill_md`` — frontmatter+ fields (description, license, compatibility, allowed-tools, metadata) update+ the store alongside the body. Content without a frontmatter block is+ accepted as body-only (the other fields carry forward), but a block that+ *looks* like frontmatter and fails to parse is rejected — storing it as body+ would double the frontmatter on the next freeze render.+ """+ parsed: dict[str, Any] | None+ try:+ parsed = parse_skill_md(content)+ except SkillImportError as e:+ if content.startswith("---"):+ raise ValidationError(f"SKILL.md frontmatter is invalid: {e}")+ parsed = None+ if parsed is None:+ fields: dict[str, Any] = {"body": content}+ else:+ fields = {+ "body": parsed["body"],+ # An empty parsed field means the frontmatter dropped it — carry the+ # current value forward rather than blanking a shared field.+ "description": parsed["description"] or None,+ "license": parsed["license"] or None,+ "compatibility": parsed["compatibility"] or None,+ "allowed_tools": parsed["allowed_tools"] or None,+ "metadata": parsed["metadata"] or None,+ }+ return _publish_next_version(team, user=user, skill_name=skill_name, fields=fields)+++def create_store_skill(team: Team, *, user: User, name: str, description: str, body: str) -> LLMSkill:+ """Create a brand-new store skill (v1) for a bulk-imported skill id."""+ validate_store_write(body, description, new_skill_name=name)+ try:+ return create_skill(team, user=user, name=name, description=description, body=body)+ except LLMSkillDuplicateNameConflictError:+ # A concurrent create won the race — surface as a conflict so the caller+ # retries and takes the publish-new-version path instead.+ raise SkillStoreConflict(f"A skill named '{name}' was just created in the store. Retry the import.")diff --git a/products/agent_platform/backend/presentation/serializers.py b/products/agent_platform/backend/presentation/serializers.pyindex d6bb502cc4ea..bc37328e410e 100644--- a/products/agent_platform/backend/presentation/serializers.py+++ b/products/agent_platform/backend/presentation/serializers.py@@ -22,7 +22,7 @@ from rest_framework import serializersfrom posthog.models import User-from ..models import AgentApplication, AgentRevision+from ..models import REVISION_STATE_CHOICES, AgentApplication, AgentRevision# Opaque random slug: leading letter (DNS-label-safe) + lowercase alphanumerics.# No dashes, so it can't be misread as the `<slug>-<revHex>` revision form, and@@ -441,6 +441,111 @@ class WriteAgentMdRequestSerializer(serializers.Serializer):content = serializers.CharField(allow_blank=True, trim_whitespace=False)+class UpdateBundleFileRequestSerializer(serializers.Serializer):+ """Body shape for PUT /revisions/<id>/bundle/file/.++ Edits one `.md` file on a draft revision. `agent.md` writes go to the+ draft bundle. `skills/<id>/SKILL.md` writes are store-backed: the edit+ publishes a new version of the referenced skill-store skill and re-pins+ the draft's `skill_refs` entry to it — skills are materialized from the+ store at freeze, so the store is the single source of truth. Tool+ source / schema editing is out of scope here; use the per-tool endpoint.+ """++ path = serializers.CharField(+ allow_blank=False,+ trim_whitespace=False,+ help_text=(+ "Canonical bundle path. Must be `agent.md` or `skills/<id>/SKILL.md` "+ "where `<id>` is a skill-reference alias on this revision."+ ),+ )+ content = serializers.CharField(+ allow_blank=True,+ trim_whitespace=False,+ help_text=(+ "The new file contents. For `agent.md`, written verbatim to the draft bundle. For a skill, "+ "published as a new version of the referenced store skill — shared with every agent that "+ "references it. SKILL.md frontmatter (description, license, allowed-tools, metadata) is "+ "honoured when present; body-only content carries those fields forward."+ ),+ )+++class ImportBundleSkillSerializer(serializers.Serializer):+ """One skill entry in a bulk-import payload.++ Skills are store-backed: each entry publishes to (or creates) a skill in+ the skill store and pins a `skill_refs` entry on the draft. The optional+ `description` is honoured when supplied; when omitted on an existing+ skill, the current store description is preserved. Skill `id` must match+ the canonical resource-id regex used by the janitor.+ """++ id = serializers.CharField(+ allow_blank=False,+ trim_whitespace=False,+ help_text="Skill id. Lowercase letters, digits, hyphens, or underscores; must start and end with `[a-z0-9]`.",+ )+ description = serializers.CharField(+ required=False,+ allow_blank=False,+ trim_whitespace=False,+ help_text="One-line summary shown in the skill index. Required when creating a new skill; optional when updating one.",+ )+ body = serializers.CharField(+ allow_blank=True,+ trim_whitespace=False,+ help_text="The skill's markdown body, published as a new version of the store skill.",+ )+++class ImportBundleRequestSerializer(serializers.Serializer):+ """Body shape for POST /revisions/<id>/bundle/import/.++ Bulk-paste hatch for migrating an existing multi-file agent. Either+ `agent_md` or `skills` (or both) may be present. Skills merge by `id`+ into the skill store: an id already referenced by the draft publishes a+ new version of its store skill; a new id attaches (or creates) the store+ skill of that name and appends a pinned `skill_refs` entry. Skills NOT+ mentioned are left alone — the import is safe to retry.+ """++ agent_md = serializers.CharField(+ required=False,+ allow_blank=True,+ trim_whitespace=False,+ help_text="New `agent.md` contents. When omitted, the existing agent.md is left alone.",+ )+ skills = serializers.ListField(+ child=ImportBundleSkillSerializer(),+ required=False,+ default=list,+ help_text=(+ "Per-skill payloads merged into the skill store by id and pinned onto the draft's "+ "skill references. When omitted, no skills are touched."+ ),+ )+++class RevisionNotDraftErrorSerializer(serializers.Serializer):+ """409 body returned when a bundle edit targets a non-draft revision.++ Distinct from a 400 on purpose: the frozen bundle sha is the source of+ truth once a revision leaves `draft`, so the fix is to clone a new draft,+ not to correct the payload. Callers switch on `error`."""++ error = serializers.CharField(help_text="Machine-readable error code — always `revision_not_draft`.")+ # Reuses the model's full choice set so drf-spectacular collapses this onto+ # the existing revision-state enum instead of minting a colliding `state`+ # enum (draft never actually appears in a 409 body).+ state = serializers.ChoiceField(+ choices=REVISION_STATE_CHOICES,+ help_text="The revision's current state (never `draft` — a draft would have accepted the edit).",+ )+ detail = serializers.CharField(help_text="Human-readable explanation of the conflict.")++class WriteSpecRequestSerializer(serializers.Serializer):"""Body shape for PUT /revisions/<id>/spec/. The body's `spec` objectis the author-facing slice (skills/tools are server-derived at freeze)."""diff --git a/products/agent_platform/backend/presentation/views.py b/products/agent_platform/backend/presentation/views.pyindex 633ba8e82d4f..4e87ce7e5b04 100644--- a/products/agent_platform/backend/presentation/views.py+++ b/products/agent_platform/backend/presentation/views.py@@ -76,6 +76,15 @@ from ..logic.internal_jwt import AgentInternalAudience, encode_agent_internal_jwfrom ..logic.janitor_client import JanitorClient, JanitorClientError, default_clientfrom ..logic.kernel_skills import all_kernel_skill_ids, kernel_skills_forfrom ..logic.posthog_identity_app import provision_posthog_identity_apps+from ..logic.skill_editing import (+ LLMSkill,+ assert_skills_writable,+ create_store_skill,+ publish_skill_body,+ publish_skill_md_edit,+ store_skill_exists,+ validate_store_write,+)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, AgentRevision@@ -86,12 +95,15 @@ from .serializers import (CloneFromRequestSerializer,DecideApprovalRequestSerializer,DryRunToolRequestSerializer,+ ImportBundleRequestSerializer,NewDraftRevisionRequestSerializer,PreviewProxyInvokeRequestSerializer,PromoteRevisionRequestSerializer,+ RevisionNotDraftErrorSerializer,SetEnvKeyRequestSerializer,SetEnvRequestSerializer,SetSkillRefsRequestSerializer,+ UpdateBundleFileRequestSerializer,WriteAgentMdRequestSerializer,WriteSpecRequestSerializer,WriteToolRequestSerializer,@@ -123,6 +135,21 @@ def _janitor() -> JanitorClient:return default_client()+# Mirrors `RESOURCE_ID_REGEX` in+# services/agent-shared/src/storage/typed-bundle.ts. The janitor enforces this+# regex on every PUT /skills/<id>; pre-checking on the Django side turns a+# noisy janitor 400 into a clean reject before we make any upstream calls,+# and is cheap. Keep these two in sync (per agent-shared CLAUDE.md rule 3).+# Also classifies `skills/<id>/` folders in the freeze sweep, keeping Django's+# sweep set identical to the set the janitor derives as skills.+# Always use `.fullmatch()`: Python's `$` matches before a trailing newline+# (JS's `$` does not), so `.match()` would accept `"abc\n"` and mint a store+# skill + ref alias the janitor later rejects at freeze.+_RESOURCE_ID_REGEX = re.compile(r"[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?")+# Canonical bundle path for one skill's markdown body. Same fullmatch rule.+_SKILL_BODY_PATH_REGEX = re.compile(r"skills/([a-z0-9](?:[a-z0-9_-]*[a-z0-9])?)/SKILL\.md")++def _decode_env_map(raw: str | None) -> dict[str, str]:"""Decode a decrypted `encrypted_env` JSON blob into a `{KEY: value}` map.@@ -217,12 +244,6 @@ 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.@@ -1746,6 +1767,8 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):# code in a sandbox — treat it as a write-scoped op so the scope# gates arbitrary compute, not just data reads."dry_run_tool",+ "update_bundle_file",+ "import_bundle","cron_fire","set_env",# env_keys_key handles GET/PUT/DELETE on /env_keys/<KEY>/ — bundled@@ -2221,6 +2244,259 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):revision: AgentRevision = self.get_object()return Response(self._call(_janitor().delete_tool, str(revision.id), tool_id))+ # ── editable .md surface: per-file PUT + bulk import ────────────────+ # Author surface for the configuration-pane editor and the bulk-paste+ # migration dialog. `agent.md` writes proxy to the draft bundle via the+ # janitor. Skill writes are store-backed: freeze materializes+ # `skill_refs` from the skill store and sweeps everything else out of+ # `skills/`, so a draft-bundle write could never stick — instead an+ # edit publishes a new version of the referenced store skill and+ # re-pins the draft's ref to it (see logic/skill_editing.py). Both+ # endpoints are draft-only — once a revision is frozen+ # (ready/live/archived) the stamped bundle sha is the source of truth+ # and neither the bundle nor the refs may move underneath it.++ _BUNDLE_EDIT_409_RESPONSE = OpenApiResponse(+ response=RevisionNotDraftErrorSerializer,+ description="The revision is frozen (ready/live/archived); clone a new draft and edit that instead.",+ )++ def _require_draft_or_409(self, revision: AgentRevision) -> Response | None:+ if revision.state == "draft":+ return None+ return Response(+ {+ "error": "revision_not_draft",+ "state": revision.state,+ "detail": (+ f"Cannot edit the bundle on a '{revision.state}' revision. Clone a new draft and edit it instead."+ ),+ },+ status=status.HTTP_409_CONFLICT,+ )++ def _locked_repin_skill_refs(+ self,+ revision: AgentRevision,+ published_by_alias: dict[str, LLMSkill],+ appended_refs: list[dict[str, Any]] | None = None,+ ) -> Response | None:+ """Re-pin edited refs (and append new ones) under a row lock, re-checking+ draft state — a concurrent freeze could have sealed the revision since+ the unlocked gate, and writing refs onto a frozen row would desync the+ column from the sealed bundle (mirrors `set_skill_refs`). Returns the+ 409 response when frozen, None on success. Store versions already+ published stay valid either way — they're append-only and merely go+ unreferenced.+ """+ with transaction.atomic(using=WRITER_DB):+ locked = AgentRevision.all_teams.using(WRITER_DB).select_for_update().get(pk=revision.pk)+ if locked.state != "draft":+ return self._require_draft_or_409(locked)+ refs = [dict(r) for r in (locked.skill_refs or [])]+ for ref in refs:+ alias = ref.get("alias")+ if not isinstance(alias, str):+ continue+ published = published_by_alias.get(alias)+ if published is not None:+ ref["version"] = published.version+ ref["source_version_id"] = str(published.id)+ refs.extend(appended_refs or [])+ locked.skill_refs = refs+ locked.save(update_fields=["skill_refs"])+ return None++ def _publish_referenced_skill_edit(+ self, request: Request, revision: AgentRevision, alias: str, content: str+ ) -> Response | None:+ """Publish edited SKILL.md content as a new store version and re-pin the+ draft's ref to it. Returns the 409 response if the revision froze+ concurrently, None on success."""+ if alias in all_kernel_skill_ids():+ raise ValidationError(+ f"Skill '{alias}' is a platform kernel skill — its content is code-locked and cannot be edited."+ )+ ref = next((r for r in (revision.skill_refs or []) if r.get("alias") == alias), None)+ name = ref.get("from_template") if ref else None+ if not isinstance(name, str) or not name:+ raise ValidationError(+ f"Skill '{alias}' is not referenced by this revision. Add it via the skill_refs "+ "endpoint or bundle/import/ first."+ )+ assert_skills_writable(+ [name],+ scopes=get_authenticator_scopes(getattr(request, "successful_authenticator", None)),+ user_access_control=self.user_access_control,+ )+ published = publish_skill_md_edit(self.team, user=cast(User, request.user), skill_name=name, content=content)+ return self._locked_repin_skill_refs(revision, {alias: published})++ @extend_schema(+ request=UpdateBundleFileRequestSerializer,+ responses={200: AgentRevisionSerializer, 409: _BUNDLE_EDIT_409_RESPONSE},+ )+ @action(detail=True, methods=["put"], url_path="bundle/file")+ def update_bundle_file(self, request: Request, **kwargs) -> Response:+ """Update one `.md` file on a draft revision.++ `agent.md` writes go to the draft bundle. `skills/<id>/SKILL.md`+ writes are store-backed — skills are materialized from the skill+ store at freeze, so the edit publishes a new version of the+ referenced store skill and re-pins the draft's `skill_refs` entry+ to it. `<id>` must be a ref alias on this revision; add new skills+ via `bundle/import/` or `skill_refs`. Tool source / schema editing+ is out of scope here — use the per-tool endpoints. Returns the+ updated revision so the caller can refresh in one round-trip.+ """+ revision: AgentRevision = self.get_object()+ # Gate on draft state before validating the payload so a non-draft+ # revision always returns 409, never a 400 that hides the real reason+ # the request can't proceed.+ if (resp := self._require_draft_or_409(revision)) is not None:+ return resp++ body = UpdateBundleFileRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)++ path = body.validated_data["path"]+ content = body.validated_data["content"]++ if path == "agent.md":+ self._call(_janitor().put_agent_md, str(revision.id), content)+ elif (match := _SKILL_BODY_PATH_REGEX.fullmatch(path)) is not None:+ if (resp := self._publish_referenced_skill_edit(request, revision, match.group(1), content)) is not None:+ return resp+ else:+ raise ValidationError(+ f"Path '{path}' is not editable through this endpoint. "+ "Only 'agent.md' and 'skills/<id>/SKILL.md' are supported."+ )++ revision.refresh_from_db()+ return Response(AgentRevisionSerializer(revision, context=self.get_serializer_context()).data)++ @extend_schema(+ request=ImportBundleRequestSerializer,+ responses={200: AgentRevisionSerializer, 409: _BUNDLE_EDIT_409_RESPONSE},+ )+ @action(detail=True, methods=["post"], url_path="bundle/import")+ def import_bundle(self, request: Request, **kwargs) -> Response:+ """Bulk-merge a set of `.md` files into a draft revision.++ Sets `agent_md` on the draft bundle if present. `skills[]` are+ store-backed and merge by `id`: an id already referenced by the+ draft publishes a new version of its store skill; an unreferenced+ id attaches the store skill of that name (publishing the payload's+ body to it), or creates it when no such skill exists — and each+ ref is (re-)pinned to the published version. Skills not mentioned+ are left alone, so the import is safe to retry. Draft-only;+ non-draft revisions return 409 untouched.+ """+ revision: AgentRevision = self.get_object()+ # Gate on draft state before validating the payload so a non-draft+ # revision always returns 409, never a 400 that hides the real reason+ # the request can't proceed.+ if (resp := self._require_draft_or_409(revision)) is not None:+ return resp++ body = ImportBundleRequestSerializer(data=request.data)+ body.is_valid(raise_exception=True)++ agent_md = body.validated_data.get("agent_md")+ skills = body.validated_data.get("skills") or []++ # Validate everything up-front so a single bad entry rejects the whole+ # request before anything is published — callers expect "all-or-nothing"+ # semantics for the bulk paste. (Store publishes are append-only, so a+ # mid-flight failure can't corrupt existing versions, but half an+ # import is still a state the UI can't easily explain.)+ seen_ids: set[str] = set()+ for skill in skills:+ skill_id = skill["id"]+ if not _RESOURCE_ID_REGEX.fullmatch(skill_id):+ raise ValidationError(+ f"Skill id '{skill_id}' is invalid. Use lowercase letters, "+ "digits, hyphens, or underscores; must start and end with [a-z0-9]."+ )+ if skill_id in seen_ids:+ raise ValidationError(f"Skill id '{skill_id}' appears more than once in the import payload.")+ seen_ids.add(skill_id)+ kernel_collisions = sorted(seen_ids & all_kernel_skill_ids())+ if kernel_collisions:+ raise ValidationError(+ f"Skill id(s) {kernel_collisions} collide with platform kernel skills — pick different ids."+ )++ # Plan each entry against the refs and the store: an id already+ # referenced by the draft targets its ref's store skill; anything else+ # targets (or creates) the store skill of the same name and appends a+ # ref. New store skills must carry a description — there's no current+ # version to fall back to.+ refs_by_alias = {r.get("alias"): r for r in (revision.skill_refs or [])}+ plan: list[tuple[dict[str, Any], str, bool]] = [] # (payload entry, store name, exists in store)+ for skill in skills:+ skill_id = skill["id"]+ ref = refs_by_alias.get(skill_id)+ name = ref.get("from_template") if ref is not None else skill_id+ if not isinstance(name, str) or not name:+ raise ValidationError(f"Skill reference '{skill_id}' on this revision is malformed.")+ exists = ref is not None or store_skill_exists(self.team, name)+ if not exists and not skill.get("description"):+ raise ValidationError(f"Skill '{skill_id}' is new — `description` is required when adding a skill.")+ # Store-side caps (body size, description length, name format for+ # creates) checked up-front too, so a bad entry mid-payload can't+ # leave earlier entries already published.+ validate_store_write(skill["body"], skill.get("description"), new_skill_name=None if exists else name)+ plan.append((skill, name, exists))++ appended_count = sum(1 for entry, _, _ in plan if entry["id"] not in refs_by_alias)+ if len(revision.skill_refs or []) + appended_count > MAX_SKILL_REFS:+ raise ValidationError(f"A revision may reference at most {MAX_SKILL_REFS} store skills.")++ if plan:+ assert_skills_writable(+ [name for _, name, _ in plan],+ scopes=get_authenticator_scopes(getattr(request, "successful_authenticator", None)),+ user_access_control=self.user_access_control,+ )++ published_by_alias: dict[str, LLMSkill] = {}+ appended_refs: list[dict[str, Any]] = []+ user = cast(User, request.user)+ for skill, name, exists in plan:+ skill_id = skill["id"]+ if exists:+ published = publish_skill_body(+ self.team, user=user, skill_name=name, body=skill["body"], description=skill.get("description")+ )+ else:+ published = create_store_skill(+ self.team, user=user, name=name, description=skill["description"], body=skill["body"]+ )+ published_by_alias[skill_id] = published+ if skill_id not in refs_by_alias:+ appended_refs.append(+ {+ "from_template": name,+ "alias": skill_id,+ "version": published.version,+ "source_version_id": str(published.id),+ }+ )++ if (+ published_by_alias+ and (resp := self._locked_repin_skill_refs(revision, published_by_alias, appended_refs)) is not None+ ):+ return resp++ if agent_md is not None:+ self._call(_janitor().put_agent_md, str(revision.id), agent_md)++ revision.refresh_from_db()+ return Response(AgentRevisionSerializer(revision, context=self.get_serializer_context()).data)+@extend_schema(request=DryRunToolRequestSerializer,responses=OpenApiResponse(@@ -2578,7 +2854,9 @@ class AgentRevisionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):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])+ if len(parts := f["path"].split("/")) >= 3+ and parts[0] == "skills"+ and _RESOURCE_ID_REGEX.fullmatch(parts[1])}# Write the resolved skills BEFORE sweeping leftovers: a failure# mid-flight then leaves the bundle with extra folders, never missing adiff --git a/products/agent_platform/backend/tests/test_bundle_editing.py b/products/agent_platform/backend/tests/test_bundle_editing.pynew file mode 100644index 000000000000..153d568b980e--- /dev/null+++ b/products/agent_platform/backend/tests/test_bundle_editing.py@@ -0,0 +1,623 @@+"""+PUT /revisions/<id>/bundle/file/ — single .md file update+POST /revisions/<id>/bundle/import/ — bulk import++`agent.md` writes proxy to the janitor (mocked here at the client boundary).+Skill writes are store-backed: they publish new llma-skill store versions and+re-pin the draft's `skill_refs` — asserted against real store rows. What we+assert is the Django-side contract: draft-only gating, path / id validation,+store versioning + ref pinning, and the llm_skill:write scope boundary.+"""++from __future__ import annotations++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework.test import APIClient++from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+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++from ee.models.rbac.access_control import AccessControl++from ..logic.kernel_skills import all_kernel_skill_ids+from ..models import AgentApplication, AgentRevision++NON_DRAFT_STATES = [("ready",), ("live",), ("archived",)]+++class TestBundleEditing(APIBaseTest):+ databases = {+ "default",+ "agent_platform_db_writer",+ "agent_platform_db_reader",+ }++ def setUp(self) -> None:+ super().setUp()+ self.application = AgentApplication.all_teams.create(+ team_id=self.team.id,+ slug="growth-agent",+ name="Growth agent",+ description="",+ )+ self.skill = LLMSkill.objects.create(+ team=self.team,+ name="growth-review",+ description="Original description",+ body="The original body.",+ )++ def _revision(self, state: str = "draft", skill_refs: list[dict] | None = None) -> AgentRevision:+ return AgentRevision.all_teams.create(+ application=self.application,+ team_id=self.team.id,+ state=state,+ spec={},+ skill_refs=(+ skill_refs if skill_refs is not None else [{"from_template": "growth-review", "alias": "growth-review"}]+ ),+ # `ready`/`live` rows in prod carry a stamped sha; supply one so the+ # row looks real even though we only need the state for the gate.+ bundle_sha256=("a" * 64) if state in {"ready", "live", "archived"} else None,+ )++ def _file_url(self, revision: AgentRevision) -> str:+ return (+ f"/api/projects/{self.team.id}/agent_applications/{self.application.id}"+ f"/revisions/{revision.id}/bundle/file/"+ )++ def _import_url(self, revision: AgentRevision) -> str:+ return (+ f"/api/projects/{self.team.id}/agent_applications/{self.application.id}"+ f"/revisions/{revision.id}/bundle/import/"+ )++ def _latest(self, name: str = "growth-review") -> LLMSkill:+ return LLMSkill.objects.get(team=self.team, name=name, is_latest=True, deleted=False)++ 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++ # ── single-file PUT ────────────────────────────────────────────────────++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_put_agent_md_on_draft(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")+ mock_janitor.return_value.put_agent_md.return_value = {"ok": True}++ res = self.client.put(+ self._file_url(revision),+ {"path": "agent.md", "content": "# New body"},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ self.assertEqual(res.json()["id"], str(revision.id))+ mock_janitor.return_value.put_agent_md.assert_called_once_with(str(revision.id), "# New body")+ # agent.md is a bundle write — nothing published to the store.+ self.assertEqual(LLMSkill.objects.count(), 1)++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_put_skill_body_publishes_store_version_and_repins(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")++ res = self.client.put(+ self._file_url(revision),+ {"path": "skills/growth-review/SKILL.md", "content": "## Edited body"},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ latest = self._latest()+ self.assertEqual(latest.version, 2)+ self.assertEqual(latest.body, "## Edited body")+ # Body-only content carries the description forward.+ self.assertEqual(latest.description, "Original description")+ revision.refresh_from_db()+ self.assertEqual(+ revision.skill_refs,+ [+ {+ "from_template": "growth-review",+ "alias": "growth-review",+ "version": 2,+ "source_version_id": str(latest.id),+ }+ ],+ )+ # The draft bundle is never written for a skill edit — freeze+ # materializes the store version.+ mock_janitor.return_value.put_skill.assert_not_called()+ mock_janitor.return_value.put_agent_md.assert_not_called()++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_put_skill_resolves_alias_to_store_template(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft", skill_refs=[{"from_template": "growth-review", "alias": "gr"}])++ res = self.client.put(+ self._file_url(revision),+ {"path": "skills/gr/SKILL.md", "content": "## Via alias"},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ latest = self._latest("growth-review")+ self.assertEqual(latest.version, 2)+ self.assertEqual(latest.body, "## Via alias")+ revision.refresh_from_db()+ self.assertEqual(revision.skill_refs[0]["alias"], "gr")+ self.assertEqual(revision.skill_refs[0]["version"], 2)+ self.assertEqual(revision.skill_refs[0]["source_version_id"], str(latest.id))++ def test_put_skill_frontmatter_updates_description(self) -> None:+ revision = self._revision("draft")+ content = "---\nname: growth-review\ndescription: New summary\n---\n## Edited\n"++ res = self.client.put(+ self._file_url(revision),+ {"path": "skills/growth-review/SKILL.md", "content": content},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ latest = self._latest()+ self.assertEqual(latest.description, "New summary")+ self.assertEqual(latest.body, "## Edited\n")++ def test_put_skill_invalid_frontmatter_returns_400(self) -> None:+ revision = self._revision("draft")+ content = "---\nname: [unclosed\n---\nbody"++ res = self.client.put(+ self._file_url(revision),+ {"path": "skills/growth-review/SKILL.md", "content": content},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(LLMSkill.objects.count(), 1)++ @parameterized.expand(NON_DRAFT_STATES)+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_put_file_409_on_non_draft(self, state: str, mock_janitor: MagicMock) -> None:+ revision = self._revision(state)++ res = self.client.put(+ self._file_url(revision),+ {"path": "agent.md", "content": "blocked"},+ format="json",+ )++ self.assertEqual(res.status_code, 409, res.content)+ payload = res.json()+ self.assertEqual(payload["error"], "revision_not_draft")+ self.assertEqual(payload["state"], state)+ mock_janitor.return_value.put_agent_md.assert_not_called()+ self.assertEqual(LLMSkill.objects.count(), 1)++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_put_file_rejects_tool_source_path(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")++ res = self.client.put(+ self._file_url(revision),+ {"path": "tools/foo/source.ts", "content": "export default {}"},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ mock_janitor.return_value.put_agent_md.assert_not_called()+ self.assertEqual(LLMSkill.objects.count(), 1)++ def test_put_file_unreferenced_skill_returns_400(self) -> None:+ revision = self._revision("draft")++ res = self.client.put(+ self._file_url(revision),+ {"path": "skills/never-added/SKILL.md", "content": "## Body"},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(LLMSkill.objects.count(), 1)++ def test_put_file_kernel_skill_is_code_locked(self) -> None:+ kernel_ids = sorted(all_kernel_skill_ids())+ if not kernel_ids:+ self.skipTest("no kernel skills shipped in this checkout")+ revision = self._revision("draft")++ res = self.client.put(+ self._file_url(revision),+ {"path": f"skills/{kernel_ids[0]}/SKILL.md", "content": "## Forged"},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(LLMSkill.objects.count(), 1)++ def test_put_skill_denied_for_token_without_llm_skill_write(self) -> None:+ # A token with agents:write but no llm_skill:write must not be able to+ # rewrite a shared store skill through the agent authoring surface.+ client = self._bearer_client(["agents:read", "agents:write"])+ revision = self._revision("draft")++ res = client.put(+ self._file_url(revision),+ {"path": "skills/growth-review/SKILL.md", "content": "## Sneaky"},+ format="json",+ )++ self.assertEqual(res.status_code, 403, res.content)+ self.assertEqual(self._latest().version, 1)+ revision.refresh_from_db()+ self.assertNotIn("source_version_id", revision.skill_refs[0])++ def test_put_skill_allowed_for_token_with_llm_skill_write(self) -> None:+ client = self._bearer_client(["agents:read", "agents:write", "llm_skill:write"])+ revision = self._revision("draft")++ res = client.put(+ self._file_url(revision),+ {"path": "skills/growth-review/SKILL.md", "content": "## Scoped edit"},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ self.assertEqual(self._latest().version, 2)++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_put_agent_md_needs_no_llm_skill_scope(self, mock_janitor: MagicMock) -> None:+ client = self._bearer_client(["agents:read", "agents:write"])+ revision = self._revision("draft")+ mock_janitor.return_value.put_agent_md.return_value = {"ok": True}++ res = client.put(+ self._file_url(revision),+ {"path": "agent.md", "content": "# Agents scope only"},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)++ # ── bulk import ────────────────────────────────────────────────────────++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_import_mixes_new_and_existing_skill(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")+ mock_janitor.return_value.put_agent_md.return_value = {"ok": True}++ res = self.client.post(+ self._import_url(revision),+ {+ "agent_md": "# Top-level",+ "skills": [+ {"id": "growth-review", "body": "updated body"},+ {"id": "fresh-skill", "description": "Brand new", "body": "## Hello"},+ ],+ },+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ existing = self._latest("growth-review")+ self.assertEqual(existing.version, 2)+ self.assertEqual(existing.body, "updated body")+ # Existing skill preserves the store description; new skill takes the payload's.+ self.assertEqual(existing.description, "Original description")+ fresh = self._latest("fresh-skill")+ self.assertEqual(fresh.version, 1)+ self.assertEqual(fresh.description, "Brand new")+ self.assertEqual(fresh.body, "## Hello")+ revision.refresh_from_db()+ self.assertEqual(+ revision.skill_refs,+ [+ {+ "from_template": "growth-review",+ "alias": "growth-review",+ "version": 2,+ "source_version_id": str(existing.id),+ },+ {+ "from_template": "fresh-skill",+ "alias": "fresh-skill",+ "version": 1,+ "source_version_id": str(fresh.id),+ },+ ],+ )+ mock_janitor.return_value.put_agent_md.assert_called_once_with(str(revision.id), "# Top-level")+ mock_janitor.return_value.put_skill.assert_not_called()++ def test_import_attaches_unreferenced_store_skill_by_name(self) -> None:+ LLMSkill.objects.create(team=self.team, name="lonely-skill", description="Lonely", body="old")+ revision = self._revision("draft", skill_refs=[])++ # No description needed — the store skill already exists under this name.+ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "lonely-skill", "body": "new body"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ latest = self._latest("lonely-skill")+ self.assertEqual(latest.version, 2)+ self.assertEqual(latest.body, "new body")+ revision.refresh_from_db()+ self.assertEqual(+ revision.skill_refs,+ [+ {+ "from_template": "lonely-skill",+ "alias": "lonely-skill",+ "version": 2,+ "source_version_id": str(latest.id),+ }+ ],+ )++ @parameterized.expand(NON_DRAFT_STATES)+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_import_409_on_non_draft(self, state: str, mock_janitor: MagicMock) -> None:+ revision = self._revision(state)++ res = self.client.post(+ self._import_url(revision),+ {"agent_md": "blocked", "skills": [{"id": "growth-review", "body": "blocked"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 409, res.content)+ payload = res.json()+ self.assertEqual(payload["error"], "revision_not_draft")+ self.assertEqual(payload["state"], state)+ mock_janitor.return_value.put_agent_md.assert_not_called()+ self.assertEqual(LLMSkill.objects.count(), 1)++ @parameterized.expand(+ [+ ("spaces", "Has Spaces"),+ # `$` matches before a trailing newline, so `.match()` would accept+ # this and mint a store skill the janitor rejects at freeze —+ # `.fullmatch()` must reject it here.+ ("trailing_newline", "abc\n"),+ ]+ )+ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_import_rejects_bad_skill_id_format(self, _name: str, bad_id: str, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {+ "agent_md": "# Never written",+ "skills": [{"id": bad_id, "description": "Bad", "body": "b"}],+ },+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ # All-or-nothing: nothing published, nothing written to the bundle.+ mock_janitor.return_value.put_agent_md.assert_not_called()+ self.assertEqual(LLMSkill.objects.count(), 1)+ revision.refresh_from_db()+ self.assertNotIn("source_version_id", revision.skill_refs[0])++ def test_import_rejects_oversized_body(self) -> None:+ # The store caps bodies at 1 MB in its serializers only; this path calls+ # the services directly, so dropping the logic-layer guard would let a+ # 20 MB request body publish oversized versions the skills API refuses.+ # The valid first entry must NOT publish either — size is checked+ # up-front with the rest of the all-or-nothing validation.+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {+ "skills": [+ {"id": "growth-review", "body": "fine"},+ {"id": "big-one", "description": "Too big", "body": "a" * 1_000_001},+ ]+ },+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(self._latest().version, 1)+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name="big-one").exists())++ def test_import_rejects_store_invalid_name_for_new_skill(self) -> None:+ # "my_skill" passes the janitor alias regex (underscores allowed) but+ # violates the store's name rules — creating it would mint a store row+ # the skills API itself refuses to create or address by name.+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "my_skill", "description": "New", "body": "b"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name="my_skill").exists())++ def test_import_rejects_duplicate_ids(self) -> None:+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {+ "skills": [+ {"id": "growth-review", "body": "one"},+ {"id": "growth-review", "body": "two"},+ ]+ },+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(self._latest().version, 1)++ def test_import_new_skill_requires_description(self) -> None:+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "brand-new", "body": "## Hello"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(LLMSkill.objects.count(), 1)++ def test_import_rejects_kernel_skill_id(self) -> None:+ kernel_ids = sorted(all_kernel_skill_ids())+ if not kernel_ids:+ self.skipTest("no kernel skills shipped in this checkout")+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": kernel_ids[0], "description": "Forged", "body": "b"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(LLMSkill.objects.count(), 1)++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_import_with_only_agent_md(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")+ mock_janitor.return_value.put_agent_md.return_value = {"ok": True}++ res = self.client.post(+ self._import_url(revision),+ {"agent_md": "# Only this"},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ mock_janitor.return_value.put_agent_md.assert_called_once_with(str(revision.id), "# Only this")+ self.assertEqual(LLMSkill.objects.count(), 1)+ revision.refresh_from_db()+ self.assertEqual(revision.skill_refs, [{"from_template": "growth-review", "alias": "growth-review"}])++ @patch("products.agent_platform.backend.presentation.views._janitor")+ def test_import_with_empty_skills_array(self, mock_janitor: MagicMock) -> None:+ revision = self._revision("draft")++ res = self.client.post(self._import_url(revision), {"skills": []}, format="json")++ self.assertEqual(res.status_code, 200, res.content)+ mock_janitor.return_value.put_agent_md.assert_not_called()+ self.assertEqual(LLMSkill.objects.count(), 1)++ def test_import_rejects_exceeding_max_refs(self) -> None:+ refs = [{"from_template": "growth-review", "alias": f"alias-{i}"} for i in range(50)]+ revision = self._revision("draft", skill_refs=refs)++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "one-more", "description": "Over the cap", "body": "b"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 400, res.content)+ self.assertEqual(LLMSkill.objects.count(), 1)++ def test_import_denied_for_token_without_llm_skill_write(self) -> None:+ client = self._bearer_client(["agents:read", "agents:write"])+ revision = self._revision("draft")++ res = client.post(+ self._import_url(revision),+ {"skills": [{"id": "growth-review", "body": "sneaky"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 403, res.content)+ self.assertEqual(self._latest().version, 1)++ def _lock_down_skills(self) -> None:+ # Grant-based skill access: demote the user to member and restrict the+ # skills resource (llm_skill inherits its access-control resource from+ # llm_analytics) to viewer team-wide, so only explicit grants can edit.+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()+ AccessControl.objects.create(team=self.team, resource="llm_analytics", resource_id=None, access_level="viewer")++ def test_import_of_new_skill_denied_without_resource_level_editor_access(self) -> None:+ # A brand-new id means the import CREATES a shared store skill, so it+ # must honour the same resource-level gate as LLMSkillViewSet's create —+ # not slip past because there's no object to check yet.+ self._lock_down_skills()+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "brand-new-skill", "description": "New", "body": "b"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 403, res.content)+ self.assertFalse(LLMSkill.objects.filter(team=self.team, name="brand-new-skill").exists())++ def test_import_of_existing_skill_denied_without_resource_level_editor_access(self) -> None:+ # An EXISTING skill with no object-specific rules must not slip past on+ # the object check's default ("editor") — the resource-level lockdown+ # applies to updates too, same as LLMSkillViewSet's PATCH.+ self._lock_down_skills()+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "growth-review", "body": "sneaky update"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 403, res.content)+ self.assertEqual(self._latest().version, 1)++ def test_import_of_existing_skill_allowed_via_member_grant(self) -> None:+ # A member locked out by the team-wide rule but holding a member-specific+ # editor grant (the shape skill access is actually granted in) can still+ # publish — the gate must not deny everyone in locked-down teams.+ self._lock_down_skills()+ AccessControl.objects.create(+ team=self.team,+ resource="llm_analytics",+ resource_id=None,+ access_level="editor",+ organization_member=self.organization_membership,+ )+ revision = self._revision("draft")++ res = self.client.post(+ self._import_url(revision),+ {"skills": [{"id": "growth-review", "body": "granted update"}]},+ format="json",+ )++ self.assertEqual(res.status_code, 200, res.content)+ self.assertEqual(self._latest().version, 2)diff --git a/products/agent_platform/frontend/generated/api.schemas.ts b/products/agent_platform/frontend/generated/api.schemas.tsindex fc3c8bcb0210..6c3e4ed74d3d 100644--- a/products/agent_platform/frontend/generated/api.schemas.ts+++ b/products/agent_platform/frontend/generated/api.schemas.ts@@ -330,6 +330,79 @@ export interface WriteTypedBundleRequestApi {spec: WriteTypedBundleRequestApiSpec}+/**+ * Body shape for PUT /revisions/<id>/bundle/file/.+ *+ * Edits one `.md` file on a draft revision. `agent.md` writes go to the+ * draft bundle. `skills/<id>/SKILL.md` writes are store-backed: the edit+ * publishes a new version of the referenced skill-store skill and re-pins+ * the draft's `skill_refs` entry to it — skills are materialized from the+ * store at freeze, so the store is the single source of truth. Tool+ * source / schema editing is out of scope here; use the per-tool endpoint.+ */+export interface UpdateBundleFileRequestApi {+ /** Canonical bundle path. Must be `agent.md` or `skills/<id>/SKILL.md` where `<id>` is a skill-reference alias on this revision. */+ path: string+ /** The new file contents. For `agent.md`, written verbatim to the draft bundle. For a skill, published as a new version of the referenced store skill — shared with every agent that references it. SKILL.md frontmatter (description, license, allowed-tools, metadata) is honoured when present; body-only content carries those fields forward. */+ content: string+}++/**+ * 409 body returned when a bundle edit targets a non-draft revision.+ *+ * Distinct from a 400 on purpose: the frozen bundle sha is the source of+ * truth once a revision leaves `draft`, so the fix is to clone a new draft,+ * not to correct the payload. Callers switch on `error`.+ */+export interface RevisionNotDraftErrorApi {+ /** Machine-readable error code — always `revision_not_draft`. */+ error: string+ /** The revision's current state (never `draft` — a draft would have accepted the edit).+ *+ * * `draft` - draft+ * * `ready` - ready+ * * `live` - live+ * * `archived` - archived */+ state: AgentRevisionStateEnumApi+ /** Human-readable explanation of the conflict. */+ detail: string+}++/**+ * One skill entry in a bulk-import payload.+ *+ * Skills are store-backed: each entry publishes to (or creates) a skill in+ * the skill store and pins a `skill_refs` entry on the draft. The optional+ * `description` is honoured when supplied; when omitted on an existing+ * skill, the current store description is preserved. Skill `id` must match+ * the canonical resource-id regex used by the janitor.+ */+export interface ImportBundleSkillApi {+ /** Skill id. Lowercase letters, digits, hyphens, or underscores; must start and end with `[a-z0-9]`. */+ id: string+ /** One-line summary shown in the skill index. Required when creating a new skill; optional when updating one. */+ description?: string+ /** The skill's markdown body, published as a new version of the store skill. */+ body: string+}++/**+ * Body shape for POST /revisions/<id>/bundle/import/.+ *+ * Bulk-paste hatch for migrating an existing multi-file agent. Either+ * `agent_md` or `skills` (or both) may be present. Skills merge by `id`+ * into the skill store: an id already referenced by the draft publishes a+ * new version of its store skill; a new id attaches (or creates) the store+ * skill of that name and appends a pinned `skill_refs` entry. Skills NOT+ * mentioned are left alone — the import is safe to retry.+ */+export interface ImportBundleRequestApi {+ /** New `agent.md` contents. When omitted, the existing agent.md is left alone. */+ agent_md?: string+ /** Per-skill payloads merged into the skill store by id and pinned onto the draft's skill references. When omitted, no skills are touched. */+ skills?: ImportBundleSkillApi[]+}+/*** Body shape for POST /revisions/<id>/clone_from/ — copy every file* from `source_revision_id` into this (draft) revision.diff --git a/products/agent_platform/frontend/generated/api.ts b/products/agent_platform/frontend/generated/api.tsindex 8557f0d32b9a..283ea28b7f92 100644--- a/products/agent_platform/frontend/generated/api.ts+++ b/products/agent_platform/frontend/generated/api.ts@@ -60,6 +60,7 @@ import type {CloneFromRequestApi,DecideApprovalRequestApi,DryRunToolRequestApi,+ ImportBundleRequestApi,NewDraftRevisionRequestApi,PaginatedAgentApplicationListApi,PaginatedAgentRevisionListApi,@@ -70,6 +71,7 @@ import type {SetEnvKeyRequestApi,SetEnvRequestApi,SetSkillRefsRequestApi,+ UpdateBundleFileRequestApi,WriteAgentMdRequestApi,WriteSpecRequestApi,WriteToolRequestApi,@@ -811,6 +813,82 @@ export const agentApplicationsRevisionsBundleUpdate = async (})}+export const getAgentApplicationsRevisionsBundleFileUpdateUrl = (+ projectId: string,+ applicationId: string,+ id: string+) => {+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/bundle/file/`+}++/**+ * Update one `.md` file on a draft revision.+ *+ * `agent.md` writes go to the draft bundle. `skills/<id>/SKILL.md`+ * writes are store-backed — skills are materialized from the skill+ * store at freeze, so the edit publishes a new version of the+ * referenced store skill and re-pins the draft's `skill_refs` entry+ * to it. `<id>` must be a ref alias on this revision; add new skills+ * via `bundle/import/` or `skill_refs`. Tool source / schema editing+ * is out of scope here — use the per-tool endpoints. Returns the+ * updated revision so the caller can refresh in one round-trip.+ */+export const agentApplicationsRevisionsBundleFileUpdate = async (+ projectId: string,+ applicationId: string,+ id: string,+ updateBundleFileRequestApi: UpdateBundleFileRequestApi,+ options?: RequestInit+): Promise<AgentRevisionApi> => {+ return apiMutator<AgentRevisionApi>(+ getAgentApplicationsRevisionsBundleFileUpdateUrl(projectId, applicationId, id),+ {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(updateBundleFileRequestApi),+ }+ )+}++export const getAgentApplicationsRevisionsBundleImportCreateUrl = (+ projectId: string,+ applicationId: string,+ id: string+) => {+ return `/api/projects/${projectId}/agent_applications/${applicationId}/revisions/${id}/bundle/import/`+}++/**+ * Bulk-merge a set of `.md` files into a draft revision.+ *+ * Sets `agent_md` on the draft bundle if present. `skills[]` are+ * store-backed and merge by `id`: an id already referenced by the+ * draft publishes a new version of its store skill; an unreferenced+ * id attaches the store skill of that name (publishing the payload's+ * body to it), or creates it when no such skill exists — and each+ * ref is (re-)pinned to the published version. Skills not mentioned+ * are left alone, so the import is safe to retry. Draft-only;+ * non-draft revisions return 409 untouched.+ */+export const agentApplicationsRevisionsBundleImportCreate = async (+ projectId: string,+ applicationId: string,+ id: string,+ importBundleRequestApi?: ImportBundleRequestApi,+ options?: RequestInit+): Promise<AgentRevisionApi> => {+ return apiMutator<AgentRevisionApi>(+ getAgentApplicationsRevisionsBundleImportCreateUrl(projectId, applicationId, id),+ {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(importBundleRequestApi),+ }+ )+}+export const getAgentApplicationsRevisionsCloneFromCreateUrl = (projectId: string,applicationId: string,diff --git a/products/agent_platform/frontend/generated/api.zod.ts b/products/agent_platform/frontend/generated/api.zod.tsindex f6c29bd5929e..e334d57fa1ee 100644--- a/products/agent_platform/frontend/generated/api.zod.ts+++ b/products/agent_platform/frontend/generated/api.zod.ts@@ -232,6 +232,85 @@ export const AgentApplicationsRevisionsBundleUpdateBody = /* @__PURE__ */ zod'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.')+/**+ * Update one `.md` file on a draft revision.+ *+ * `agent.md` writes go to the draft bundle. `skills/<id>/SKILL.md`+ * writes are store-backed — skills are materialized from the skill+ * store at freeze, so the edit publishes a new version of the+ * referenced store skill and re-pins the draft's `skill_refs` entry+ * to it. `<id>` must be a ref alias on this revision; add new skills+ * via `bundle/import/` or `skill_refs`. Tool source / schema editing+ * is out of scope here — use the per-tool endpoints. Returns the+ * updated revision so the caller can refresh in one round-trip.+ */+export const AgentApplicationsRevisionsBundleFileUpdateBody = /* @__PURE__ */ zod+ .object({+ path: zod+ .string()+ .describe(+ 'Canonical bundle path. Must be `agent.md` or `skills\/<id>\/SKILL.md` where `<id>` is a skill-reference alias on this revision.'+ ),+ content: zod+ .string()+ .describe(+ 'The new file contents. For `agent.md`, written verbatim to the draft bundle. For a skill, published as a new version of the referenced store skill — shared with every agent that references it. SKILL.md frontmatter (description, license, allowed-tools, metadata) is honoured when present; body-only content carries those fields forward.'+ ),+ })+ .describe(+ "Body shape for PUT \/revisions\/<id>\/bundle\/file\/.\n\nEdits one `.md` file on a draft revision. `agent.md` writes go to the\ndraft bundle. `skills\/<id>\/SKILL.md` writes are store-backed: the edit\npublishes a new version of the referenced skill-store skill and re-pins\nthe draft's `skill_refs` entry to it — skills are materialized from the\nstore at freeze, so the store is the single source of truth. Tool\nsource \/ schema editing is out of scope here; use the per-tool endpoint."+ )++/**+ * Bulk-merge a set of `.md` files into a draft revision.+ *+ * Sets `agent_md` on the draft bundle if present. `skills[]` are+ * store-backed and merge by `id`: an id already referenced by the+ * draft publishes a new version of its store skill; an unreferenced+ * id attaches the store skill of that name (publishing the payload's+ * body to it), or creates it when no such skill exists — and each+ * ref is (re-)pinned to the published version. Skills not mentioned+ * are left alone, so the import is safe to retry. Draft-only;+ * non-draft revisions return 409 untouched.+ */+export const AgentApplicationsRevisionsBundleImportCreateBody = /* @__PURE__ */ zod+ .object({+ agent_md: zod+ .string()+ .optional()+ .describe('New `agent.md` contents. When omitted, the existing agent.md is left alone.'),+ skills: zod+ .array(+ zod+ .object({+ id: zod+ .string()+ .describe(+ 'Skill id. Lowercase letters, digits, hyphens, or underscores; must start and end with `[a-z0-9]`.'+ ),+ description: zod+ .string()+ .optional()+ .describe(+ 'One-line summary shown in the skill index. Required when creating a new skill; optional when updating one.'+ ),+ body: zod+ .string()+ .describe("The skill's markdown body, published as a new version of the store skill."),+ })+ .describe(+ 'One skill entry in a bulk-import payload.\n\nSkills are store-backed: each entry publishes to (or creates) a skill in\nthe skill store and pins a `skill_refs` entry on the draft. The optional\n`description` is honoured when supplied; when omitted on an existing\nskill, the current store description is preserved. Skill `id` must match\nthe canonical resource-id regex used by the janitor.'+ )+ )+ .optional()+ .describe(+ "Per-skill payloads merged into the skill store by id and pinned onto the draft's skill references. When omitted, no skills are touched."+ ),+ })+ .describe(+ 'Body shape for POST \/revisions\/<id>\/bundle\/import\/.\n\nBulk-paste hatch for migrating an existing multi-file agent. Either\n`agent_md` or `skills` (or both) may be present. Skills merge by `id`\ninto the skill store: an id already referenced by the draft publishes a\nnew version of its store skill; a new id attaches (or creates) the store\nskill of that name and appends a pinned `skill_refs` entry. Skills NOT\nmentioned are left alone — the import is safe to retry.'+ )+/*** Copy every file from `source_revision_id` into this revision.*/diff --git a/pyproject.toml b/pyproject.tomlindex e516751b2624..442915d7f48c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -516,6 +516,7 @@ ignore_imports = ["products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.janitor_client","products.agent_platform.backend.presentation.views -> products.agent_platform.backend.logic.kernel_skills","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_editing","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",diff --git a/services/mcp/definitions/agent_platform.yaml b/services/mcp/definitions/agent_platform.yamlindex cb2b7e0a9ead..a69211688e58 100644--- a/services/mcp/definitions/agent_platform.yaml+++ b/services/mcp/definitions/agent_platform.yaml@@ -223,6 +223,12 @@ tools:app has no deployable version until another revision is promoted). Idempotent. Playbook: read the`editing-agents-safely` playbook via `agent-resolve-resource` for the branch → validate → freeze → promoteworkflow.+ agent-applications-revisions-bundle-file-update:+ operation: agent_applications_revisions_bundle_file_update+ enabled: false+ agent-applications-revisions-bundle-import-create:+ operation: agent_applications_revisions_bundle_import_create+ enabled: falseagent-applications-revisions-bundle-retrieve:operation: agent_applications_revisions_bundle_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 06cc78373057..6bae7538d7e0 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -28005,6 +28005,41 @@ export namespace Schemas {id_jag_allowed_clients?: string[];}+ /**+ * One skill entry in a bulk-import payload.+ *+ * Skills are store-backed: each entry publishes to (or creates) a skill in+ * the skill store and pins a `skill_refs` entry on the draft. The optional+ * `description` is honoured when supplied; when omitted on an existing+ * skill, the current store description is preserved. Skill `id` must match+ * the canonical resource-id regex used by the janitor.+ */+ export interface ImportBundleSkill {+ /** Skill id. Lowercase letters, digits, hyphens, or underscores; must start and end with `[a-z0-9]`. */+ id: string;+ /** One-line summary shown in the skill index. Required when creating a new skill; optional when updating one. */+ description?: string;+ /** The skill's markdown body, published as a new version of the store skill. */+ body: string;+ }++ /**+ * Body shape for POST /revisions/<id>/bundle/import/.+ *+ * Bulk-paste hatch for migrating an existing multi-file agent. Either+ * `agent_md` or `skills` (or both) may be present. Skills merge by `id`+ * into the skill store: an id already referenced by the draft publishes a+ * new version of its store skill; a new id attaches (or creates) the store+ * skill of that name and appends a pinned `skill_refs` entry. Skills NOT+ * mentioned are left alone — the import is safe to retry.+ */+ export interface ImportBundleRequest {+ /** New `agent.md` contents. When omitted, the existing agent.md is left alone. */+ agent_md?: string;+ /** Per-skill payloads merged into the skill store by id and pinned onto the draft's skill references. When omitted, no skills are touched. */+ skills?: ImportBundleSkill[];+ }+export interface InsightBulkDeleteRequest {/*** Insight IDs to soft-delete (or restore). At most 1000 ids per request. Soft-deleted insights can be brought back via the bulk_restore endpoint.@@ -48769,6 +48804,27 @@ export namespace Schemas {stale: number;}+ /**+ * 409 body returned when a bundle edit targets a non-draft revision.+ *+ * Distinct from a 400 on purpose: the frozen bundle sha is the source of+ * truth once a revision leaves `draft`, so the fix is to clone a new draft,+ * not to correct the payload. Callers switch on `error`.+ */+ export interface RevisionNotDraftError {+ /** Machine-readable error code — always `revision_not_draft`. */+ error: string;+ /** The revision's current state (never `draft` — a draft would have accepted the edit).+ *+ * * `draft` - draft+ * * `ready` - ready+ * * `live` - live+ * * `archived` - archived */+ state: AgentRevisionStateEnum;+ /** Human-readable explanation of the conflict. */+ detail: string;+ }+export interface RevokeOtherSessionsResponse {/** Number of other login sessions that were revoked. */revoked_count: number;@@ -54433,6 +54489,23 @@ export namespace Schemas {target_language?: string;}+ /**+ * Body shape for PUT /revisions/<id>/bundle/file/.+ *+ * Edits one `.md` file on a draft revision. `agent.md` writes go to the+ * draft bundle. `skills/<id>/SKILL.md` writes are store-backed: the edit+ * publishes a new version of the referenced skill-store skill and re-pins+ * the draft's `skill_refs` entry to it — skills are materialized from the+ * store at freeze, so the store is the single source of truth. Tool+ * source / schema editing is out of scope here; use the per-tool endpoint.+ */+ export interface UpdateBundleFileRequest {+ /** Canonical bundle path. Must be `agent.md` or `skills/<id>/SKILL.md` where `<id>` is a skill-reference alias on this revision. */+ path: string;+ /** The new file contents. For `agent.md`, written verbatim to the draft bundle. For a skill, published as a new version of the referenced store skill — shared with every agent that references it. SKILL.md frontmatter (description, license, allowed-tools, metadata) is honoured when present; body-only content carries those fields forward. */+ content: string;+ }+export interface UpdateDashboardWidgetsBatchResponse {/** Updated dashboard widget tiles in request order. */tiles: DashboardTile[];