Skip to content

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

feat(llma): publish skills to community server (4/7) (#65013)

Andrew Maguire7d61b1455e72
diff --git a/docs/internal/skills/community-skills-api.md b/docs/internal/skills/community-skills-api.md
index 5ea30d9dc1ff..cdfc1c02ef04 100644
--- a/docs/internal/skills/community-skills-api.md
+++ b/docs/internal/skills/community-skills-api.md
@@ -65,3 +65,74 @@ trusting the sync:
Errors surface as `400` (invalid payload / duplicate name) or `404` (unknown or removed slug).
A duplicate-name conflict only blames the `new_name` field when the caller actually supplied it.
+
+## Publishing to the community
+
+Publishing runs the other way: it renders a team's own `LLMSkill` into the repo's
+`skills/<slug>/SKILL.md` layout and opens a pull request for a maintainer to review.
+
+| Method | Path | Purpose |
+| ------ | ------------------------------------------------- | ---------------------------------------- |
+| `POST` | `llm_skills/name/{skill_name}/publish-community/` | Open a PR adding or updating this skill. |
+
+Lives on `LLMSkillViewSet` (`products/skills/backend/api/skills.py`), not the community viewset,
+because the subject is a team-owned skill.
+Rendering and the GitHub calls are in `community_publish_services.py`.
+
+- Gated by `CommunityPublishFeatureFlagPermission`, which applies the same
+ `llm-analytics-community-skills` check as the browse endpoints to this action alone. Skills is GA,
+ so the flag cannot sit on the viewset.
+- Throttled at 6/hour and 20/day, **keyed by team rather than by credential**. `_ensure_web_authenticated`
+ also accepts a personal API key, and the inherited throttle key prefers the key hash, so one member
+ with several keys would otherwise get a fresh budget with each of them. The API-shaped
+ `BurstRateThrottle` would not fire here at all: it only counts personal-API-key traffic.
+- The slug is held to the same rule ingest applies (`SKILL_NAME_PATTERN`, no reserved name), and body,
+ file count, and per-file size to the same caps, so a publish that ingest would silently drop is
+ refused before the pull request exists. The manifest is also checked for paths that differ only by
+ case and for a name used as both a file and a folder, neither of which a git tree can hold.
+- Bundled paths are canonicalized and allowed-tool names are held to ingest's no-whitespace rule,
+ both through the shared validators in `skill_services.py`. `create_skill` (the path the Max tool
+ takes) stores either field without the REST serializer's checks, so a skill can hold
+ `references\guide.md` or a tool named `Bash Write`. Publishing one unchanged merges a pull
+ request whose entry ingest then drops.
+- `display_name` is capped at 64 characters to match `CommunitySkill.name`. A longer name would pass
+ review and then be dropped by ingest, so the skill would never appear in the catalog.
+- `author_handle` is validated against GitHub's username shape, and is self-reported. Nothing checks it
+ against the publisher's PostHog account, so the PR body presents it as a handle the publisher gave.
+- Bundled files are text only. `CommunitySkillFile.content` is a `TextField` and the renderer takes
+ `str`, so a skill referencing an image or other binary asset cannot round-trip through the catalog.
+
+### Settings
+
+| Setting | Effect |
+| ----------------------------------------- | ----------------------------------------------------------------------------------- |
+| `COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID` | Installation of the GitHub App that opens the PRs. Empty (the default) returns 503. |
+| `COMMUNITY_SKILLS_GITHUB_REPO` | Bare repo name to publish into. The owner comes from the installation's account. |
+
+`COMMUNITY_SKILLS_GITHUB_REPO` is publish-only. The hourly catalog sync reads `registry.json` from the
+repo pinned in `community_skill_sync.py`, so pointing this setting elsewhere sends pull requests to a
+repo the sync never reads back.
+
+### Repo writes
+
+The target repo is public, so a failed publish must not leave anything behind:
+
+- The branch is `community-skill/<slug>-<publisher key>`, so re-publishing rewrites that branch and
+ returns the PR already open for it instead of opening a second one. The publisher key is a short
+ hash of the team's uuid: a slug is only unique within a team, so a branch keyed on the slug alone
+ would let one team force-update another team's open pull request.
+- Every rendered file lands in a single tree and commit, built before the branch reference exists.
+ A failure part way through leaves no branch, and reviewers see one commit rather than one per file.
+- If opening the PR fails, the branch is deleted again.
+- Content becomes public at the branch write, before the pull request that moderates it. Confirming
+ that with the user is a UI concern, and it gates enabling the flag rather than shipping this code.
+
+Errors surface as `400` (invalid payload), `404` (unknown skill), `502` (GitHub refused a step), or
+`503` when the instance has no `COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID` configured. The 503 is the
+fail-safe that keeps publishing off until the GitHub App is installed.
+
+The three are kept apart on purpose, because each sends the publisher somewhere different. The skill
+is rendered before GitHub is touched, so a skill that has to be edited answers `400` even while the
+App is down. `503` is reserved for an installation GitHub says is absent or refuses the App's
+credentials for; any other failed status while minting the publish token is an outage and answers
+`502`, so a transient failure doesn't read as "this instance can't publish".
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index adb3559fbf6d..bffb616c39f9 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4352,6 +4352,14 @@ export interface PatchedUserApi {
readonly requires_credential_review?: boolean
}
+export interface UserGithubLoginApi {
+ /**
+ * The user's resolved GitHub login, or null when no GitHub identity is linked.
+ * @nullable
+ */
+ github_login: string | null
+}
+
export interface UserGitHubAccountApi {
/**
* GitHub account type for the installation (e.g. User or Organization).
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 7079251d8f0c..da9a83371790 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -76,6 +76,7 @@ import type {
UserGitHubLinkStartRequestApi,
UserGitHubLinkStartResponseApi,
UserGitHubPrepareCallbackRequestApi,
+ UserGithubLoginApi,
UserPushTokenItemApi,
UserPushTokenRegisterRequestApi,
UserPushTokenUnregisterRequestApi,
@@ -2422,8 +2423,8 @@ export const getUsersGithubLoginRetrieveUrl = (uuid: string) => {
return `/api/users/${uuid}/github_login/`
}
-export const usersGithubLoginRetrieve = async (uuid: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getUsersGithubLoginRetrieveUrl(uuid), {
+export const usersGithubLoginRetrieve = async (uuid: string, options?: RequestInit): Promise<UserGithubLoginApi> => {
+ return apiMutator<UserGithubLoginApi>(getUsersGithubLoginRetrieveUrl(uuid), {
...options,
method: 'GET',
})
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 633bc4da3f23..eec0162150c3 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -959,6 +959,13 @@ class RevokeOtherSessionsResponseSerializer(serializers.Serializer):
revoked_count = serializers.IntegerField(help_text="Number of other login sessions that were revoked.")
+class UserGithubLoginSerializer(serializers.Serializer):
+ github_login = serializers.CharField(
+ allow_null=True,
+ help_text="The user's resolved GitHub login, or null when no GitHub identity is linked.",
+ )
+
+
@extend_schema(extensions={"x-product": "core"})
@extend_schema_view(
retrieve=extend_schema(
@@ -1065,6 +1072,7 @@ class UserViewSet(
report_user_deleted_account(user)
super().perform_destroy(user)
+ @extend_schema(responses=UserGithubLoginSerializer)
@action(methods=["GET"], detail=True, url_path="github_login")
def github_login(self, request, **kwargs):
user = self.get_object()
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index b35fd780eecd..8f63eb86ad3f 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -1239,12 +1239,12 @@ class GitHubIntegrationBase:
return []
return [pr["html_url"] for pr in pulls if isinstance(pr, dict) and isinstance(pr.get("html_url"), str)]
- def get_open_pr_base_for_head(self, repository: str, branch: str) -> str | None:
- """Return the base branch of an OPEN pull request whose head is ``branch``, if one exists.
+ def get_open_pull_request_for_head(self, repository: str, branch: str) -> dict[str, Any] | None:
+ """Return the OPEN pull request whose head is ``branch`` — its number, HTML url, and base ref.
- ``repository`` is ``owner/repo`` (or a bare repo, resolved against the org). Distinguishes
- a branch that *heads* an open PR (work continues on it) from a branch used as a PR *base*.
- Best-effort: returns None on a bad repo, non-200, no open PR, or any error.
+ ``repository`` is ``owner/repo`` (or a bare repo, resolved against the org). Lets a caller
+ that owns a deterministic branch name find the PR it already opened, instead of opening a
+ second one. Best-effort: returns None on a bad repo, non-200, no open PR, or any error.
"""
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
owner = repo_path.split("/", 1)[0]
@@ -1258,12 +1258,29 @@ class GitHubIntegrationBase:
try:
pulls = response.json()
except Exception:
- logger.warning("GitHubIntegration: get_open_pr_base_for_head non-JSON response", repository=repo_path)
+ logger.warning("GitHubIntegration: get_open_pull_request_for_head non-JSON response", repository=repo_path)
return None
if not isinstance(pulls, list) or not pulls or not isinstance(pulls[0], dict):
return None
- base = (pulls[0].get("base") or {}).get("ref")
- return base if isinstance(base, str) and base else None
+ pull = pulls[0]
+ number = pull.get("number")
+ if not isinstance(number, int):
+ return None
+ base = (pull.get("base") or {}).get("ref")
+ return {
+ "number": number,
+ "url": pull.get("html_url") if isinstance(pull.get("html_url"), str) else None,
+ "base": base if isinstance(base, str) and base else None,
+ }
+
+ def get_open_pr_base_for_head(self, repository: str, branch: str) -> str | None:
+ """Return the base branch of an OPEN pull request whose head is ``branch``, if one exists.
+
+ Distinguishes a branch that *heads* an open PR (work continues on it) from a branch used as
+ a PR *base*. Best-effort: returns None on a bad repo, non-200, no open PR, or any error.
+ """
+ pull = self.get_open_pull_request_for_head(repository, branch)
+ return pull.get("base") if pull else None
_PR_SNAPSHOT_QUERY = """
query($owner: String!, $repo: String!, $number: Int!) {
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 0b4a549e4cdf..eb312115b648 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -3956,6 +3956,213 @@ class GitHubIntegration(GitHubIntegrationBase):
"status_code": response.status_code,
}
+ def commit_files_to_branch(
+ self,
+ repository: str,
+ branch_name: str,
+ base_branch: str,
+ files: Mapping[str, str],
+ commit_message: str,
+ replace_directory: str | None = None,
+ ) -> dict[str, Any]:
+ """Point ``branch_name`` at a single commit on top of ``base_branch`` writing every file in
+ ``files`` (repo-relative path → text content).
+
+ Prefer this over ``create_branch`` plus one ``update_file`` per file when the files only make
+ sense together: the commit object is built before the branch reference exists, so a failure
+ part way through leaves nothing in the repository, and reviewers get one commit rather than
+ one per file. An existing branch is force-updated to the new commit, discarding whatever was
+ on it — callers republishing generated content want exactly that, callers collaborating on a
+ branch do not.
+
+ ``replace_directory`` makes the commit *replace* that directory with exactly the files given
+ under it, instead of merging them into whatever ``base_branch`` already holds there. Without
+ it a path that existed on the base and is absent from ``files`` survives, because the tree is
+ built on the base tree: a caller republishing a generated directory would keep shipping files
+ it has since deleted or renamed. Files outside the directory are still merged as usual.
+ """
+ if not files:
+ return {"success": False, "error": "No files to commit"}
+
+ org = self.organization()
+
+ base_ref_response = self.api_request(
+ "GET",
+ f"/repos/{org}/{repository}/git/ref/heads/{base_branch}",
+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",
+ )
+ if base_ref_response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to get base branch {base_branch}: {base_ref_response.text}",
+ "status_code": base_ref_response.status_code,
+ }
+ base_sha = base_ref_response.json()["object"]["sha"]
+
+ base_commit_response = self.api_request(
+ "GET",
+ f"/repos/{org}/{repository}/git/commits/{base_sha}",
+ endpoint="/repos/{owner}/{repo}/git/commits/{commit_sha}",
+ )
+ if base_commit_response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to read base commit {base_sha}: {base_commit_response.text}",
+ "status_code": base_commit_response.status_code,
+ }
+ base_tree_sha = base_commit_response.json()["tree"]["sha"]
+
+ # Inline `content` lets GitHub create the blobs as part of the tree, so no separate blob
+ # round trip per file. 100644 is a non-executable file.
+ def blob_entries(paths: Mapping[str, str]) -> list[dict[str, str]]:
+ return [
+ {"path": path, "mode": "100644", "type": "blob", "content": content} for path, content in paths.items()
+ ]
+
+ entries: list[dict[str, str]] = []
+ if replace_directory:
+ prefix = replace_directory.rstrip("/") + "/"
+ inside = {path[len(prefix) :]: content for path, content in files.items() if path.startswith(prefix)}
+ # Built with no base_tree, so this tree holds the given files and nothing else. Pointing
+ # the directory entry at it swaps the whole subtree in one step, which is what makes a
+ # path the caller dropped disappear rather than survive from the base tree.
+ subtree_response = self.api_request(
+ "POST",
+ f"/repos/{org}/{repository}/git/trees",
+ endpoint="/repos/{owner}/{repo}/git/trees",
+ json_body={"tree": blob_entries(inside)},
+ )
+ if subtree_response.status_code != 201:
+ return {
+ "success": False,
+ "error": f"Failed to create tree for {replace_directory}: {subtree_response.text}",
+ "status_code": subtree_response.status_code,
+ }
+ entries.append(
+ {
+ "path": replace_directory.rstrip("/"),
+ "mode": "040000",
+ "type": "tree",
+ "sha": subtree_response.json()["sha"],
+ }
+ )
+ entries.extend(blob_entries({p: c for p, c in files.items() if not p.startswith(prefix)}))
+ else:
+ entries = blob_entries(files)
+
+ tree_response = self.api_request(
+ "POST",
+ f"/repos/{org}/{repository}/git/trees",
+ endpoint="/repos/{owner}/{repo}/git/trees",
+ json_body={"base_tree": base_tree_sha, "tree": entries},
+ )
+ if tree_response.status_code != 201:
+ return {
+ "success": False,
+ "error": f"Failed to create tree: {tree_response.text}",
+ "status_code": tree_response.status_code,
+ }
+
+ commit_response = self.api_request(
+ "POST",
+ f"/repos/{org}/{repository}/git/commits",
+ endpoint="/repos/{owner}/{repo}/git/commits",
+ json_body={
+ "message": commit_message,
+ "tree": tree_response.json()["sha"],
+ "parents": [base_sha],
+ },
+ )
+ if commit_response.status_code != 201:
+ return {
+ "success": False,
+ "error": f"Failed to create commit: {commit_response.text}",
+ "status_code": commit_response.status_code,
+ }
+ commit_sha = commit_response.json()["sha"]
+
+ create_ref_response = self.api_request(
+ "POST",
+ f"/repos/{org}/{repository}/git/refs",
+ endpoint="/repos/{owner}/{repo}/git/refs",
+ json_body={"ref": f"refs/heads/{branch_name}", "sha": commit_sha},
+ )
+ if create_ref_response.status_code == 201:
+ return {"success": True, "branch_name": branch_name, "commit_sha": commit_sha, "created_branch": True}
+
+ # 422 is what GitHub returns for a reference that already exists; move it instead.
+ if create_ref_response.status_code != 422:
+ return {
+ "success": False,
+ "error": f"Failed to create branch {branch_name}: {create_ref_response.text}",
+ "status_code": create_ref_response.status_code,
+ }
+
+ update_ref_response = self.api_request(
+ "PATCH",
+ f"/repos/{org}/{repository}/git/refs/heads/{branch_name}",
+ endpoint="/repos/{owner}/{repo}/git/refs/heads/{branch}",
+ json_body={"sha": commit_sha, "force": True},
+ )
+ if update_ref_response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to update branch {branch_name}: {update_ref_response.text}",
+ "status_code": update_ref_response.status_code,
+ }
+ return {"success": True, "branch_name": branch_name, "commit_sha": commit_sha, "created_branch": False}
+
+ def delete_branch(self, repository: str, branch_name: str, expected_sha: str | None = None) -> dict[str, Any]:
+ """Delete a branch reference. A branch that is already gone counts as success.
+
+ ``expected_sha`` makes the delete conditional: the ref is read first and left alone when it
+ has moved on, which is what a caller cleaning up its own failed write wants on a branch name
+ that is shared by construction. GitHub has no conditional delete, so this narrows the race
+ rather than closing it.
+ """
+ org = self.organization()
+
+ if expected_sha is not None:
+ head_response = self.api_request(
+ "GET",
+ f"/repos/{org}/{repository}/git/ref/heads/{branch_name}",
+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",
+ )
+ if head_response.status_code == 404:
+ return {"success": True, "branch_name": branch_name}
+ if head_response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to read branch {branch_name}: {head_response.text}",
+ "status_code": head_response.status_code,
+ }
+ if head_response.json()["object"]["sha"] != expected_sha:
+ return {"success": True, "branch_name": branch_name, "skipped": True}
+
+ response = self.api_request(
+ "DELETE",
+ f"/repos/{org}/{repository}/git/refs/heads/{branch_name}",
+ endpoint="/repos/{owner}/{repo}/git/refs/heads/{branch}",
+ )
+ if response.status_code in (204, 404):
+ return {"success": True, "branch_name": branch_name}
+ # GitHub answers a delete with 422 both for a reference that is already gone and for one it
+ # refused to remove, so the status alone can't tell "done" from "still there". Read the ref
+ # back: absent is the success the caller wanted, present is a branch it has to hear about.
+ if response.status_code == 422:
+ recheck_response = self.api_request(
+ "GET",
+ f"/repos/{org}/{repository}/git/ref/heads/{branch_name}",
+ endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",
+ )
+ if recheck_response.status_code == 404:
+ return {"success": True, "branch_name": branch_name}
+ return {
+ "success": False,
+ "error": f"Failed to delete branch {branch_name}: {response.text}",
+ "status_code": response.status_code,
+ }
+
def get_diff(
self,
repository: str,
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index daa278886b2d..bce0ad9e7ee0 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -1985,11 +1985,162 @@ class TestGitHubIntegrationModel(BaseTest):
assert result["success"] is False
assert result["status_code"] == 502
+ def _github_for_org(self) -> GitHubIntegration:
+ integration = self.create_integration(
+ config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}
+ )
+ return GitHubIntegration(integration)
+
+ @staticmethod
+ def _git_data_api_request(*, ref_status: int = 201):
+ calls: list[tuple[str, str, Optional[dict]]] = []
+
+ def _request(method, path, **kwargs):
+ calls.append((method, path, kwargs.get("json_body")))
+ if "/git/ref/heads/" in path and method == "GET":
+ return MagicMock(status_code=200, **{"json.return_value": {"object": {"sha": "base-sha"}}})
+ if "/git/commits/" in path:
+ return MagicMock(status_code=200, **{"json.return_value": {"tree": {"sha": "base-tree"}}})
+ if path.endswith("/git/trees"):
+ return MagicMock(status_code=201, **{"json.return_value": {"sha": "new-tree"}})
+ if path.endswith("/git/commits"):
+ return MagicMock(status_code=201, **{"json.return_value": {"sha": "new-commit"}})
+ if path.endswith("/git/refs"):
+ return MagicMock(status_code=ref_status, text="Reference already exists")
+ if "/git/refs/heads/" in path and method == "PATCH":
+ return MagicMock(status_code=200)
+ raise AssertionError(f"unexpected request {method} {path}")
+
+ return _request, calls
+
+ def test_commit_files_to_branch_writes_every_file_in_one_commit(self):
+ github = self._github_for_org()
+ request, calls = self._git_data_api_request()
+
+ with patch.object(github, "api_request", side_effect=request):
+ result = github.commit_files_to_branch(
+ "community-skills", "community-skill/x", "main", {"a.md": "A", "b/c.md": "C"}, "msg"
+ )
+
+ assert result["success"] is True
+ assert result["commit_sha"] == "new-commit"
+ tree_body = next(body for _, path, body in calls if path.endswith("/git/trees"))
+ assert {entry["path"] for entry in tree_body["tree"]} == {"a.md", "b/c.md"}
+ assert tree_body["base_tree"] == "base-tree"
+ # The branch reference is written last, so a failure earlier leaves no branch in the repo.
+ assert calls[-1][1].endswith("/git/refs")
+
+ def test_commit_files_to_branch_replaces_a_directory_rather_than_merging_into_it(self):
+ github = self._github_for_org()
+ request, calls = self._git_data_api_request()
+
+ with patch.object(github, "api_request", side_effect=request):
+ result = github.commit_files_to_branch(
+ "community-skills",
+ "community-skill/x",
+ "main",
+ {"skills/x/SKILL.md": "S", "skills/x/refs/g.md": "G", "README.md": "R"},
+ "msg",
+ replace_directory="skills/x",
+ )
+
+ assert result["success"] is True
+ subtree_body, tree_body = (body for _, path, body in calls if path.endswith("/git/trees"))
+ # No base_tree on the subtree, so it holds these files and nothing else. That is what makes a
+ # path the caller dropped disappear instead of surviving from the base.
+ assert "base_tree" not in subtree_body
+ assert {entry["path"] for entry in subtree_body["tree"]} == {"SKILL.md", "refs/g.md"}
+ assert tree_body["base_tree"] == "base-tree"
+ assert {(entry["path"], entry["type"]) for entry in tree_body["tree"]} == {
+ ("skills/x", "tree"),
+ ("README.md", "blob"),
+ }
+
+ def test_commit_files_to_branch_force_updates_an_existing_branch(self):
+ github = self._github_for_org()
+ request, calls = self._git_data_api_request(ref_status=422)
+
+ with patch.object(github, "api_request", side_effect=request):
+ result = github.commit_files_to_branch(
+ "community-skills", "community-skill/x", "main", {"a.md": "A"}, "msg"
+ )
+
+ assert result["success"] is True
+ assert result["created_branch"] is False
+ method, path, body = calls[-1]
+ assert (method, path) == ("PATCH", "/repos/PostHog/community-skills/git/refs/heads/community-skill/x")
+ assert body == {"sha": "new-commit", "force": True}
+
+ @parameterized.expand([("deleted", 204), ("already gone", 404)])
+ def test_delete_branch_treats_a_missing_branch_as_deleted(self, _name: str, status_code: int):
+ github = self._github_for_org()
+ with patch.object(github, "api_request", return_value=MagicMock(status_code=status_code)):
+ assert github.delete_branch("community-skills", "community-skill/x")["success"] is True
+
+ @parameterized.expand([("the ref is gone", 404, True), ("the ref is still there", 200, False)])
+ def test_delete_branch_reads_the_ref_back_after_an_ambiguous_422(self, _name: str, recheck: int, deleted: bool):
+ github = self._github_for_org()
+
+ def _request(method, path, **kwargs):
+ if method == "DELETE":
+ return MagicMock(status_code=422, text="Validation failed")
+ return MagicMock(status_code=recheck, **{"json.return_value": {"object": {"sha": "abc"}}})
+
+ with patch.object(github, "api_request", side_effect=_request):
+ result = github.delete_branch("community-skills", "community-skill/x")
+
+ # A 422 the caller reads as success is a branch left on a public repo with nobody warned.
+ assert result["success"] is deleted
+
+ @parameterized.expand([("the expected commit", "mine", True), ("someone else's commit", "theirs", False)])
+ def test_delete_branch_with_an_expected_sha_only_deletes_its_own_commit(
+ self, _name: str, head_sha: str, deleted: bool
+ ):
+ github = self._github_for_org()
+ methods: list[str] = []
+
+ def _request(method, path, **kwargs):
+ methods.append(method)
+ if method == "GET":
+ return MagicMock(status_code=200, **{"json.return_value": {"object": {"sha": head_sha}}})
+ return MagicMock(status_code=204)
+
+ with patch.object(github, "api_request", side_effect=_request):
+ result = github.delete_branch("community-skills", "community-skill/x", expected_sha="mine")
+
+ assert result["success"] is True
+ assert ("DELETE" in methods) is deleted
+
+ def test_get_open_pull_request_for_head_returns_number_and_url(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=200)
+ mock_response.json.return_value = [
+ {
+ "number": 7,
+ "html_url": "https://github.com/PostHog/posthog/pull/7",
+ "base": {"ref": "master"},
+ }
+ ]
+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response):
+ assert github.get_open_pull_request_for_head("PostHog/posthog", "posthog-code/fix") == {
+ "number": 7,
+ "url": "https://github.com/PostHog/posthog/pull/7",
+ "base": "master",
+ }
+
def test_get_open_pr_base_for_head_returns_base_ref_of_open_pr(self):
integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
github = GitHubIntegration(integration)
mock_response = MagicMock(status_code=200)
- mock_response.json.return_value = [{"base": {"ref": "master"}, "head": {"ref": "posthog-code/fix"}}]
+ mock_response.json.return_value = [
+ {
+ "number": 7,
+ "html_url": "https://github.com/PostHog/posthog/pull/7",
+ "base": {"ref": "master"},
+ "head": {"ref": "posthog-code/fix"},
+ }
+ ]
with patch.object(github, "_installation_authenticated_get", return_value=mock_response) as mock_get:
result = github.get_open_pr_base_for_head("PostHog/posthog", "posthog-code/fix")
assert result == "master"
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index e1a0d29c7e9e..70e0d16c3283 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -79,6 +79,15 @@ STAMPHOG_GITHUB_APP_SLUG = get_from_env("STAMPHOG_GITHUB_APP_SLUG", "")
# PyPI, the LLM gateway host, the PostHog capture host). Comma-separated; an ops escape hatch for
# when a legitimate dependency host is missing — never a way to open the sandbox wide.
STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS = get_list(get_from_env("STAMPHOG_SANDBOX_EXTRA_EGRESS_DOMAINS", ""))
+# Installation id of the GitHub App on the PostHog/community-skills repo, used by the in-product
+# "Publish to community" flow to open skill PRs. Empty (the default) disables publishing → the
+# endpoint returns 503 and the UI falls back to the manual-PR path.
+COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID = get_from_env("COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID", "")
+# Bare repo name (no owner prefix) — the owner is the App installation's account. Defaults to the
+# PostHog/community-skills repo. Publish-only: the hourly catalog sync reads its registry from the
+# repo pinned in community_skill_sync.py, so pointing this elsewhere sends pull requests to a repo the
+# sync does not read back.
+COMMUNITY_SKILLS_GITHUB_REPO = get_from_env("COMMUNITY_SKILLS_GITHUB_REPO", "community-skills")
META_ADS_APP_CLIENT_ID = get_from_env("META_ADS_APP_CLIENT_ID", "")
META_ADS_APP_CLIENT_SECRET = get_from_env("META_ADS_APP_CLIENT_SECRET", "")
diff --git a/products/skills/backend/api/community_publish_services.py b/products/skills/backend/api/community_publish_services.py
new file mode 100644
index 000000000000..a93b9bfcb125
--- /dev/null
+++ b/products/skills/backend/api/community_publish_services.py
@@ -0,0 +1,689 @@
+"""Publish a team's LLMSkill to the PostHog/community-skills repo as a pull request.
+
+The heavy lifting (branch + commit + PR) reuses the existing `GitHubIntegration` that already
+powers the Tasks product. This module owns the pure rendering of an `LLMSkill` into the repo's
+`skills/<slug>/SKILL.md` layout; the GitHub side lives in `publish_skill_to_community`.
+"""
+
+from __future__ import annotations
+
+import re
+import json
+import hashlib
+from typing import Any
+
+from django.conf import settings
+
+import yaml
+import requests
+import structlog
+
+from posthog.dataclasses import frozen
+from posthog.egress.github.transport import GitHubRateLimitError
+from posthog.models.github_integration_base import GitHubIntegrationError
+from posthog.models.integration import GitHubIntegration, Integration
+
+from ..marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH
+from .skill_services import (
+ MAX_SKILL_BODY_BYTES,
+ MAX_SKILL_FILE_BYTES,
+ MAX_SKILL_FILE_COUNT,
+ RESERVED_SKILL_NAMES,
+ SKILL_NAME_PATTERN,
+ check_allowed_tool_name,
+ normalize_skill_file_path,
+)
+
+logger = structlog.get_logger(__name__)
+
+MAX_SLUG_LENGTH = 64
+# GitHub caps one create-tree request at 7 MB, and commit_files_to_branch inlines every file's
+# content in that single request, so a skill above the cap can only ever fail with a 502. Measured
+# against the escaped form the request actually carries, and held under the cap for the frontmatter,
+# paths and envelope that ride along with it.
+MAX_PUBLISH_TREE_BYTES = 5_000_000
+# GitHub usernames are alphanumeric with single inner hyphens, up to 39 characters. The handle is
+# self-reported and lands in a public PR body and in the listing, so hold it to the shape of a real
+# username rather than letting free text through. The pattern alone can't bound the total, since each
+# repetition may contribute a hyphen and a character, so the length is checked beside it.
+MAX_GITHUB_HANDLE_LENGTH = 39
+GITHUB_HANDLE_PATTERN = re.compile(r"^[a-zA-Z0-9](?:-?[a-zA-Z0-9]){0,38}$")
+# The API field is optional, so the shape it publishes to clients has to accept an empty string too —
+# otherwise generated validators reject the blank the endpoint itself allows.
+OPTIONAL_GITHUB_HANDLE_PATTERN = re.compile(f"^$|{GITHUB_HANDLE_PATTERN.pattern}")
+# Matches CommunitySkill.name — a longer name publishes and merges, then ingest rejects the entry and
+# the skill silently never appears in the catalog.
+MAX_DISPLAY_NAME_LENGTH = 64
+# The display name is interpolated into the App-authored commit message, the pull request title and
+# its Markdown body. A newline in it can forge a commit trailer, so `Co-authored-by:` would make
+# GitHub attribute our App's commit to an unrelated account. Hold the name to one printable line.
+DISPLAY_NAME_PATTERN = re.compile(r"^[^\x00-\x1f\x7f]*$")
+MAX_TAG_LENGTH = 64
+SKILLS_DIR = "skills"
+# The subtree one publish owns. Rewritten whole on every publish, so a file dropped from the skill
+# stops being published rather than surviving on the branch the previous publish left it on.
+SKILL_TREE_MODE = "040000"
+COMMUNITY_SKILLS_PR_BASE_BRANCH = "main"
+COMMUNITY_SKILLS_BRANCH_PREFIX = "community-skill/"
+
+
+class CommunitySkillPublishError(Exception):
+ """Raised when a skill can't be rendered or published to the community repo."""
+
+
+class CommunitySkillPublishNotConfiguredError(CommunitySkillPublishError):
+ """Raised when the community-skills GitHub App installation isn't configured on this instance."""
+
+
+class CommunitySkillPublishValidationError(CommunitySkillPublishError):
+ """Raised when the skill itself can't be published, before anything is written to GitHub.
+
+ Split from the GitHub failures the base class also carries because the two need opposite advice:
+ this one is fixed by editing the skill, and republishing it unchanged fails the same way, so the
+ endpoint answers it 400 rather than the 502 it answers an unreachable GitHub with.
+ """
+
+
+class _CommunitySkillsPublisher(GitHubIntegration):
+ """Publisher client whose Integration row is transient and belongs to no team.
+
+ A fresh installation token is minted for every publish, so a 401 is a real failure rather than an
+ expiry to heal — and the inherited refresh would try to save a teamless row, which the model's
+ team foreign key forbids.
+ """
+
+ def refresh_access_token(self) -> None:
+ raise GitHubIntegrationError("The community-skills publisher mints a token per publish and cannot refresh.")
+
+
+@frozen
+class RenderedFile:
+ """A single file to commit, at its path within the community-skills repo."""
+
+ path: str
+ content: str
+
+
+def publishable_tags(tags: object) -> list[str]:
+ """Keep only the entries of a skill's stored tags that the catalog can actually accept.
+
+ `LLMSkill.metadata` is an arbitrary dict, so its `tags` can hold any JSON, while ingest requires
+ every tag to be a string within the catalog's cap and drops the whole entry otherwise. Publishing
+ the unusable ones would open a pull request that merges and then never appears in the catalog.
+ """
+ if not isinstance(tags, list):
+ return []
+ # Stripped, like the serializer's own CharField already gives us for request-supplied tags. Sync
+ # only lowercases a tag, and catalog filtering matches it exactly, so a stored `" github "` would
+ # publish as a tag no filter can ever select.
+ stripped = (tag.strip() for tag in tags if isinstance(tag, str))
+ return [tag for tag in stripped if tag and len(tag) <= MAX_TAG_LENGTH]
+
+
+def publisher_branch_key(publisher_id: str) -> str:
+ """Short, stable, opaque branch suffix for one publisher.
+
+ Skill slugs are only unique within a team, but a branch name is global to the community repo, so a
+ slug alone would let one team's publish force-update another team's open pull request. Hashing
+ keeps the publisher's identifier out of a public branch name.
+ """
+ return hashlib.sha256(publisher_id.encode()).hexdigest()[:8]
+
+
+def _validate_slug(slug: str) -> str:
+ # The same rule community_skill_sync._validate_entry_shape applies to a registry entry, so a slug
+ # that would be dropped on ingest is refused here instead of merging into a catalog that skips
+ # it. fullmatch, not match: `$` also matches before a trailing newline.
+ if not SKILL_NAME_PATTERN.fullmatch(slug) or "--" in slug or len(slug) > MAX_SLUG_LENGTH:
+ raise CommunitySkillPublishValidationError(
+ f"'{slug}' is not a valid community skill slug (lowercase letters, numbers, single hyphens)."
+ )
+ if slug.lower() in RESERVED_SKILL_NAMES:
+ raise CommunitySkillPublishValidationError(
+ f"'{slug}' is a reserved name and can't be published to the community."
+ )
+ return slug
+
+
+def _validate_allowed_tool(tool: object) -> None:
+ """Hold one allowed-tool name to the rule ingest applies to a registry entry.
+
+ `create_skill` writes what a tool call passed straight to the model, without the REST
+ serializer's `validate_allowed_tool`, and `allowed_tools` is a JSONField, so a stored
+ `"Bash Write"` (or a non-string) renders into frontmatter that
+ community_skill_sync._validate_entry_shape rejects: the pull request merges and the skill never
+ appears in the catalog.
+ """
+ if not isinstance(tool, str):
+ raise CommunitySkillPublishValidationError("Allowed tools must be a list of tool names.")
+ try:
+ check_allowed_tool_name(tool)
+ except ValueError as err:
+ raise CommunitySkillPublishValidationError(f"'{tool}' can't be published as a tool name. {err}") from err
+
+
+def render_skill_md(
+ *,
+ name: str,
+ description: str,
+ body: str,
+ tags: list[str] | None = None,
+ allowed_tools: list[str] | None = None,
+ license: str = "",
+ compatibility: str = "",
+ author_handle: str = "",
+) -> str:
+ """Render an LLMSkill's fields into community-skills `SKILL.md` content (frontmatter + body).
+
+ Output parses cleanly under the repo's `build_registry.py` frontmatter regex and field rules:
+ `name` and `description` are required; `trust_tier` defaults to `community` (maintainers set
+ `official`/`verified` on review); optional fields are omitted when empty.
+ """
+ if not name.strip():
+ raise CommunitySkillPublishValidationError("Skill name is required to publish.")
+ if len(name.strip()) > MAX_DISPLAY_NAME_LENGTH:
+ raise CommunitySkillPublishValidationError(f"Skill name must be {MAX_DISPLAY_NAME_LENGTH} characters or fewer.")
+ if not DISPLAY_NAME_PATTERN.match(name.strip()):
+ raise CommunitySkillPublishValidationError("Skill name must be one line, with no line breaks.")
+ if not description.strip():
+ raise CommunitySkillPublishValidationError("Skill description is required to publish.")
+ # LLMSkill.description holds 4096, and the Agent Skills spec stops at 1024. A longer one
+ # publishes, syncs and installs, and then validate_for_export refuses the installed skill, so the
+ # publisher hands someone a skill they can never export.
+ if len(description.strip()) > SPEC_DESCRIPTION_MAX_LENGTH:
+ raise CommunitySkillPublishValidationError(
+ f"Skill description must be {SPEC_DESCRIPTION_MAX_LENGTH} characters or fewer to publish."
+ )
+ # The same rule install_community_skill applies on the way back in, where a blank body is refused
+ # as having no instructions. Without it the publish succeeds, the entry merges into the catalog,
+ # and the listing is one nobody can install.
+ if not body.strip():
+ raise CommunitySkillPublishValidationError("Skill instructions are required to publish.")
+ if author_handle.strip() and (
+ len(author_handle.strip()) > MAX_GITHUB_HANDLE_LENGTH or not GITHUB_HANDLE_PATTERN.match(author_handle.strip())
+ ):
+ raise CommunitySkillPublishValidationError(f"'{author_handle}' is not a valid GitHub username.")
+ for tool in allowed_tools or []:
+ _validate_allowed_tool(tool)
+
+ frontmatter: dict[str, Any] = {
+ "name": name.strip(),
+ "description": description.strip(),
+ "trust_tier": "community",
+ }
+ if tags:
+ frontmatter["tags"] = list(tags)
+ if author_handle.strip():
+ frontmatter["author_handle"] = author_handle.strip()
+ if license.strip():
+ frontmatter["license"] = license.strip()
+ if compatibility.strip():
+ frontmatter["compatibility"] = compatibility.strip()
+ if allowed_tools:
+ frontmatter["allowed_tools"] = list(allowed_tools)
+
+ # sort_keys=False keeps the human-friendly field order above; default_flow_style=False emits
+ # block-style YAML (lists as `- item`) that the repo's yaml.safe_load round-trips.
+ rendered_frontmatter = yaml.safe_dump(frontmatter, sort_keys=False, default_flow_style=False, allow_unicode=True)
+ # rstrip, not strip: leading whitespace is content. A body that opens with an indented code block
+ # becomes an ordinary paragraph once it's trimmed, so the published skill would instruct
+ # differently from the skill it was published from.
+ return f"---\n{rendered_frontmatter}---\n\n{body.rstrip()}\n"
+
+
+def render_community_skill_files(
+ *,
+ slug: str,
+ name: str,
+ description: str,
+ body: str,
+ files: list[dict[str, str]] | None = None,
+ tags: list[str] | None = None,
+ allowed_tools: list[str] | None = None,
+ license: str = "",
+ compatibility: str = "",
+ author_handle: str = "",
+) -> list[RenderedFile]:
+ """Render the full set of files to commit for a skill: SKILL.md plus any bundled files.
+
+ Bundled files keep their skill-relative path under `skills/<slug>/` (e.g. a skill file at
+ `references/playbook.md` becomes `skills/<slug>/references/playbook.md`).
+ """
+ _validate_slug(slug)
+ _validate_entry_caps(body=body, files=files or [])
+ skill_root = f"{SKILLS_DIR}/{slug}"
+
+ rendered: list[RenderedFile] = [
+ RenderedFile(
+ path=f"{skill_root}/SKILL.md",
+ content=render_skill_md(
+ name=name,
+ description=description,
+ body=body,
+ tags=tags,
+ allowed_tools=allowed_tools,
+ license=license,
+ compatibility=compatibility,
+ author_handle=author_handle,
+ ),
+ )
+ ]
+
+ seen_paths = {rendered[0].path.lower()}
+ for file in files or []:
+ # Canonical and confined to the skill directory, by the same rule ingest applies. A bundled
+ # file must never escape skills/<slug>/, and `create_skill` stores a tool-supplied path
+ # verbatim, so `references\guide.md` and `references/guide.md` arrive here as two distinct
+ # paths that community_skill_sync._validate_entry_within_caps then folds into one and
+ # rejects as a duplicate: the pull request merges and the skill never appears in the catalog.
+ rel_path = _publishable_file_path(file["path"])
+ path = f"{skill_root}/{rel_path}"
+ # Case-insensitive, matching community_skill_sync._validate_entry_within_caps: two paths
+ # differing only by case pass every check on this side, and then ingest rejects the whole
+ # entry, so the pull request merges and the skill never appears in the catalog. Seeding the
+ # set with SKILL.md is also what stops a bundled file from overwriting the rendered one.
+ if path.lower() in seen_paths:
+ raise CommunitySkillPublishValidationError(f"Duplicate bundled file path '{file['path']}'.")
+ seen_paths.add(path.lower())
+ rendered.append(RenderedFile(path=path, content=file["content"]))
+
+ _reject_blob_directory_collisions(seen_paths)
+ _validate_publishable_tree_size(rendered)
+ return rendered
+
+
+def _publishable_file_path(raw_path: str) -> str:
+ try:
+ return normalize_skill_file_path(raw_path)
+ except ValueError as err:
+ raise CommunitySkillPublishValidationError(f"'{raw_path}' can't be published as a file path. {err}") from err
+
+
+def _encoded_payload_bytes(content: str) -> int:
+ """Size this content adds to the one create-tree request GitHub caps at 7 MB.
+
+ What counts against that cap is the escaped form, because commit_files_to_branch inlines every
+ file's content in a single JSON body: a newline costs two bytes there and one here, and a control
+ character costs six. Counting raw bytes instead lets a body of newlines clear a 5 MB check and
+ still blow the limit, which fails the publish with a 502 nobody can act on. `json.dumps` defaults
+ match what `requests` serializes the body with, escaping included.
+ """
+ return len(json.dumps(content).encode("utf-8"))
+
+
+def _validate_entry_caps(*, body: str, files: list[dict[str, str]]) -> None:
+ """Hold a publish to ingest's own per-entry caps, which it measures on the stored bytes.
+
+ These are `community_skill_sync._validate_entry_within_caps`, where breaching one drops the whole
+ entry: the pull request merges and the skill never appears in the catalog. The file count is
+ checked here rather than after rendering so an absurd manifest never gets rendered at all.
+ """
+ if len(body.encode("utf-8")) > MAX_SKILL_BODY_BYTES:
+ raise CommunitySkillPublishValidationError(
+ f"The skill body must be under {MAX_SKILL_BODY_BYTES // 1_000_000} MB."
+ )
+ if len(files) > MAX_SKILL_FILE_COUNT:
+ raise CommunitySkillPublishValidationError(f"A skill can publish at most {MAX_SKILL_FILE_COUNT} files.")
+ for file in files:
+ if len(file["content"].encode("utf-8")) > MAX_SKILL_FILE_BYTES:
+ raise CommunitySkillPublishValidationError(
+ f"'{file['path']}' must be under {MAX_SKILL_FILE_BYTES // 1_000_000} MB."
+ )
+
+
+def _validate_publishable_tree_size(rendered: list[RenderedFile]) -> None:
+ """Hold the whole manifest to GitHub's cap on the create-tree request that writes it.
+
+ Measured on what is actually sent, which is why it runs on the rendered files rather than the
+ fields they came from: SKILL.md carries frontmatter as well as the body, and neither the tag list
+ nor `allowed_tools` has a count cap, so the difference is not a rounding error. Breaching the cap
+ fails the write with a 502 nobody can act on.
+ """
+ total = sum(_encoded_payload_bytes(file.content) + len(file.path.encode("utf-8")) for file in rendered)
+ if total > MAX_PUBLISH_TREE_BYTES:
+ raise CommunitySkillPublishValidationError(
+ f"This skill is too large to publish. Trim it to under "
+ f"{MAX_PUBLISH_TREE_BYTES // 1_000_000} MB of body and files, then publish again."
+ )
+
+
+def _reject_blob_directory_collisions(paths: set[str]) -> None:
+ """Refuse a manifest where one path is a file and also a directory in another path.
+
+ A git tree can't hold `references` as both a blob and a tree, so GitHub rejects the whole tree
+ and the skill can't be published at all. Saying which path collides beats the API's error.
+ """
+ directories = {parent for path in paths for parent in _parent_directories(path)}
+ collisions = sorted(directories & paths)
+ if collisions:
+ raise CommunitySkillPublishValidationError(
+ f"'{collisions[0].split('/', 2)[-1]}' is used as both a file and a folder. Rename one of them."
+ )
+
+
+def _parent_directories(path: str) -> list[str]:
+ parts = path.split("/")
+ return ["/".join(parts[:index]) for index in range(1, len(parts))]
+
+
+# The publish only writes files and opens a pull request, in one repository. An unscoped mint would
+# hand this transient token every repository and every optional permission the installation holds, so
+# it is requested down to what a publish uses. A permission the installation lacks fails the mint,
+# which is the same 502 an unusable installation would produce on the first write anyway.
+PUBLISHER_TOKEN_PERMISSIONS = {"contents": "write", "pull_requests": "write", "metadata": "read"}
+# Statuses that mean the App isn't installed here or its credentials are rejected: unauthenticated,
+# not permitted, or no such installation. Rate limits never reach this set — the transport raises
+# them, including the 403 spellings.
+PUBLISHER_NOT_CONFIGURED_STATUSES = frozenset({401, 403, 404})
+
+
+def _publisher_token_request_body() -> dict[str, Any]:
+ # The `repositories` field takes bare names; the setting is normally one already, but accept an
+ # `owner/repo` spelling rather than scoping the token to a repository that doesn't exist.
+ repo = (settings.COMMUNITY_SKILLS_GITHUB_REPO or "").split("/")[-1]
+ body: dict[str, Any] = {"permissions": dict(PUBLISHER_TOKEN_PERMISSIONS)}
+ if repo:
+ body["repositories"] = [repo]
+ return body
+
+
+def get_community_skills_publisher() -> GitHubIntegration | None:
+ """Build a GitHubIntegration bound to the central community-skills installation, or None.
+
+ Mints a fresh installation token via the GitHub App JWT (the same flow the per-team integration
+ uses), downscoped to the publish repository and the permissions a publish needs, and wraps it in a
+ transient, unsaved Integration — we never persist a teamless central row. Returns None when the
+ App or the community-skills installation isn't configured, so callers can surface a clean "not
+ configured" error instead of failing.
+
+ Raises CommunitySkillPublishError when GitHub can't be reached to mint the token: an outage here
+ is the same failure as an outage on the write that follows, and must not read as "not configured".
+ """
+ installation_id = settings.COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID
+ if not installation_id or not settings.GITHUB_APP_CLIENT_ID or not settings.GITHUB_APP_PRIVATE_KEY:
+ return None
+
+ try:
+ info_response = GitHubIntegration.client_request(f"installations/{installation_id}")
+ token_response = GitHubIntegration.client_request(
+ f"installations/{installation_id}/access_tokens",
+ method="POST",
+ json_body=_publisher_token_request_body(),
+ )
+ except (requests.RequestException, GitHubIntegrationError, GitHubRateLimitError) as err:
+ # client_request talks to the transport directly, so unlike api_request it hands a timeout
+ # back raw. Without this the publish path answers a GitHub outage with an unhandled 500.
+ logger.warning("community_skills_publisher_unreachable", exc_info=True)
+ raise CommunitySkillPublishError(
+ "Could not reach GitHub to publish this skill. Try again in a few minutes."
+ ) from err
+
+ failed_statuses = [
+ response.status_code
+ for response, expected in ((info_response, 200), (token_response, 201))
+ if response.status_code != expected
+ ]
+ if failed_statuses:
+ logger.warning(
+ "community_skills_publisher_unavailable",
+ info_status=info_response.status_code,
+ token_status=token_response.status_code,
+ )
+ # A missing installation or App credentials GitHub refuses are settings nobody can retry
+ # their way out of, which is the 503 this returns None for. Any other status is GitHub
+ # failing a call we were entitled to make, and has to read as a gateway error instead —
+ # answering a transient 500 with "not configured" sends the publisher to the manual path
+ # for an outage that clears on its own.
+ if all(status in PUBLISHER_NOT_CONFIGURED_STATUSES for status in failed_statuses):
+ return None
+ raise CommunitySkillPublishError("Could not reach GitHub to publish this skill. Try again in a few minutes.")
+
+ account = info_response.json().get("account") or {}
+ token = token_response.json().get("token")
+ if not token or not account.get("login"):
+ return None
+
+ # Transient (never saved) Integration, left unattached to any team: the write helpers only read
+ # the access token + account name and don't trigger a refresh/save, so this avoids polluting the
+ # team-scoped Integration table.
+ integration = Integration(
+ kind="github",
+ integration_id=str(installation_id),
+ config={"account": {"name": account["login"], "type": account.get("type")}},
+ sensitive_config={"access_token": token},
+ )
+ return _CommunitySkillsPublisher(integration)
+
+
+def _community_pr_body(*, name: str, slug: str, author_handle: str) -> str:
+ # No PostHog user PII here — this PR is public. Attribution is only the GitHub handle the
+ # publisher explicitly provided for public sharing.
+ # The handle is self-reported, so say so: a maintainer must not read it as a verified identity.
+ credit = (
+ f"Published from the PostHog skills marketplace. The publisher gave @{author_handle} as the author handle"
+ if author_handle
+ else "Published from the PostHog skills marketplace"
+ )
+ return (
+ f"Adds the **{name}** community skill (`skills/{slug}/`).\n\n"
+ f"{credit} via the in-product *Publish to community* flow.\n\n"
+ "A maintainer should review the instructions for safety before merging; "
+ "set `trust_tier` on review. On merge, CI regenerates `registry.json` and PostHog syncs it."
+ )
+
+
+def publish_skill_to_community(
+ *,
+ slug: str,
+ publisher_id: str,
+ name: str,
+ description: str,
+ body: str,
+ files: list[dict[str, str]] | None = None,
+ tags: list[str] | None = None,
+ allowed_tools: list[str] | None = None,
+ license: str = "",
+ compatibility: str = "",
+ author_handle: str = "",
+) -> dict[str, Any]:
+ """Open a PR in PostHog/community-skills adding (or updating) this skill. Returns the PR url/number.
+
+ One open PR per skill per publisher: the branch is derived from the slug and ``publisher_id``, so
+ re-publishing rewrites that branch and returns the pull request already open for it instead of
+ opening a second one. Every file lands in a single commit, and a failure after the branch write
+ deletes the branch again, since this repo is public and a half-written skill or an unreviewed
+ branch must not survive a failed publish. A failure that may still have opened a pull request is
+ reconciled against GitHub first, so cleanup can never remove a branch under live review.
+
+ ``publisher_id`` identifies the publishing team and is required. Leaving the branch keyed on the
+ slug alone would let one team's publish force-update another team's open pull request, because a
+ skill slug is only unique within a team.
+
+ Raises CommunitySkillPublishError when any GitHub step fails, or
+ CommunitySkillPublishNotConfiguredError when publishing is disabled.
+ """
+ # Rendering is pure and deterministic, so it runs before the publisher is acquired: a skill the
+ # publisher has to edit gets the 400 that says so, rather than a 502 or 503 about GitHub that
+ # sends them away to retry a publish that would never have succeeded.
+ rendered = render_community_skill_files(
+ slug=slug,
+ name=name,
+ description=description,
+ body=body,
+ files=files,
+ tags=tags,
+ allowed_tools=allowed_tools,
+ license=license,
+ compatibility=compatibility,
+ author_handle=author_handle,
+ )
+
+ publisher = get_community_skills_publisher()
+ if publisher is None:
+ raise CommunitySkillPublishNotConfiguredError("Community skill publishing is not configured.")
+
+ branch = f"{COMMUNITY_SKILLS_BRANCH_PREFIX}{slug}-{publisher_branch_key(publisher_id)}"
+ try:
+ return _write_branch_and_pull_request(
+ publisher, rendered=rendered, slug=slug, name=name, author_handle=author_handle, branch=branch
+ )
+ except (GitHubIntegrationError, GitHubRateLimitError) as err:
+ # The client only ever sees this class of failure as "GitHub is unreachable", so the detail
+ # has to reach the logs here or it is lost.
+ logger.warning("community_skill_publish_github_unavailable", slug=slug, branch=branch, exc_info=True)
+ raise CommunitySkillPublishError(
+ "Could not reach GitHub to publish this skill. Try again in a few minutes."
+ ) from err
+
+
+def _write_branch_and_pull_request(
+ publisher: GitHubIntegration,
+ *,
+ rendered: list[RenderedFile],
+ slug: str,
+ name: str,
+ author_handle: str,
+ branch: str,
+) -> dict[str, Any]:
+ repo = settings.COMMUNITY_SKILLS_GITHUB_REPO
+ base = COMMUNITY_SKILLS_PR_BASE_BRANCH
+
+ # Read the open PR before writing, so a failed write doesn't get blamed on a PR that predates it.
+ existing_pr = publisher.get_open_pull_request_for_head(repo, branch)
+ if existing_pr is not None:
+ _require_publishable_base(existing_pr, base=base)
+
+ commit_result = publisher.commit_files_to_branch(
+ repo,
+ branch,
+ base,
+ {rendered_file.path: rendered_file.content for rendered_file in rendered},
+ f"{'Update' if existing_pr else 'Add'} community skill: {name}",
+ # The skill's directory is rewritten whole rather than merged onto whatever main already
+ # holds there. Merged, a bundled file the skill has since dropped keeps being published, and
+ # a rename that only changes case leaves both spellings, which ingest folds together and
+ # rejects: the pull request merges and the skill disappears from the catalog.
+ replace_directory=f"{SKILLS_DIR}/{slug}",
+ )
+ if not commit_result.get("success"):
+ raise CommunitySkillPublishError(f"Failed to commit skill files: {commit_result.get('error')}")
+ commit_sha = commit_result.get("commit_sha")
+
+ if existing_pr is not None:
+ # Re-read rather than trusting the lookup from before the write. A maintainer merging or
+ # closing that review in between would otherwise leave our commit on a public branch with no
+ # open review, reported as a success pointing at a pull request that no longer takes it.
+ still_open = _reconcile_open_pr(publisher, repo=repo, slug=slug, branch=branch, base=base)
+ if still_open is not None:
+ logger.info("community_skill_publish_updated_open_pr", slug=slug, pr_number=still_open["pr_number"])
+ return still_open
+ logger.info("community_skill_publish_reopening_after_review_ended", slug=slug, pr_number=existing_pr["number"])
+
+ try:
+ pr_result = publisher.create_pull_request(
+ repo,
+ f"Add community skill: {name}",
+ _community_pr_body(name=name, slug=slug, author_handle=author_handle),
+ branch,
+ base,
+ )
+ except (GitHubIntegrationError, GitHubRateLimitError):
+ # A transport failure on this POST is ambiguous: GitHub may still have opened the pull
+ # request, and api_request doesn't retry a POST. Reconcile before cleaning up, so a timeout
+ # can't delete a branch that now heads a live review.
+ logger.warning("community_skill_publish_pr_create_ambiguous", slug=slug, branch=branch, exc_info=True)
+ reconciled = _reconcile_open_pr(publisher, repo=repo, slug=slug, branch=branch, base=base)
+ if reconciled is not None:
+ return reconciled
+ _delete_publish_branch(publisher, repo=repo, slug=slug, branch=branch, commit_sha=commit_sha)
+ raise
+
+ if pr_result.get("success"):
+ logger.info("community_skill_published", slug=slug, pr_number=pr_result.get("pr_number"))
+ return {"pr_url": pr_result["pr_url"], "pr_number": pr_result["pr_number"], "branch": branch}
+
+ error = str(pr_result.get("error") or "")
+ # A branch that already heads a pull request means a concurrent publish won the race. Our commit
+ # is on that branch and so inside that review, so return it rather than reporting a failure for
+ # content that is already public. Cleanup would belong to that review's branch, not to us.
+ if "already exists" in error.lower():
+ reconciled = _reconcile_open_pr(publisher, repo=repo, slug=slug, branch=branch, base=base)
+ if reconciled is not None:
+ return reconciled
+ raise CommunitySkillPublishError("A pull request for this skill is already open for review.")
+
+ _delete_publish_branch(publisher, repo=repo, slug=slug, branch=branch, commit_sha=commit_sha)
+ # GitHub refuses a pull request with an empty diff, which is what an unchanged skill produces.
+ if "no commits between" in error.lower():
+ raise CommunitySkillPublishError(
+ "This skill already matches what's published, so there's nothing to send. "
+ "Edit the skill, then publish again."
+ )
+ raise CommunitySkillPublishError(f"Failed to open pull request: {error}")
+
+
+def _require_publishable_base(pull: dict[str, Any], *, base: str) -> None:
+ """Refuse a pull request on our branch that no longer targets the branch the catalog is built from.
+
+ Merging a retargeted pull request writes to that other branch, so the skill would never reach the
+ catalog even though publishing reported success. Its branch is also under live review, which is
+ why this runs before the commit: we neither force-update that branch nor delete it.
+ """
+ if pull.get("base") == base:
+ return
+ raise CommunitySkillPublishError(
+ f"Pull request #{pull['number']} for this skill is open against "
+ f"'{pull.get('base') or 'another branch'}' instead of '{base}'. "
+ "Ask a maintainer to retarget or close it, then publish again."
+ )
+
+
+def _reconcile_open_pr(
+ publisher: GitHubIntegration, *, repo: str, slug: str, branch: str, base: str
+) -> dict[str, Any] | None:
+ """Re-read the pull request open for ``branch`` after an ambiguous create, or None if there is none.
+
+ A None here means "found nothing", not "the branch has no pull request": the lookup is
+ best-effort and answers None for most failures. It still raises when GitHub rate-limits the read,
+ which is caught here so a caller cleaning up after a failure isn't handed a second one.
+
+ A pull request retargeted away from ``base`` raises instead of returning: it is not ours to
+ report as this publish's destination, and the raise also keeps the caller from deleting a branch
+ that is under review.
+ """
+ try:
+ pull = publisher.get_open_pull_request_for_head(repo, branch)
+ except (GitHubIntegrationError, GitHubRateLimitError):
+ logger.warning("community_skill_publish_pr_lookup_failed", slug=slug, branch=branch, exc_info=True)
+ return None
+ if pull is None or not pull.get("url"):
+ return None
+ _require_publishable_base(pull, base=base)
+ logger.info("community_skill_publish_reconciled_open_pr", slug=slug, pr_number=pull["number"])
+ return {"pr_url": pull["url"], "pr_number": pull["number"], "branch": branch}
+
+
+def _delete_publish_branch(
+ publisher: GitHubIntegration, *, repo: str, slug: str, branch: str, commit_sha: str | None
+) -> None:
+ """Remove a branch this publish created. Cleanup failure is logged, never raised over the cause.
+
+ This also runs while handling a GitHub failure, where a raise here would replace the error that
+ actually explains the publish with one about the tidy-up after it.
+
+ The delete is conditional on ``commit_sha``: the branch name is shared by every publish of this
+ skill from this team, so an unconditional delete could take out a concurrent publisher's commit,
+ which they cannot recover the way the publisher who wrote it can.
+ """
+ try:
+ cleanup_result = publisher.delete_branch(repo, branch, expected_sha=commit_sha)
+ except (GitHubIntegrationError, GitHubRateLimitError):
+ logger.warning("community_skill_publish_branch_cleanup_failed", slug=slug, branch=branch, exc_info=True)
+ return
+ if not cleanup_result.get("success"):
+ logger.warning(
+ "community_skill_publish_branch_cleanup_failed",
+ slug=slug,
+ branch=branch,
+ error=cleanup_result.get("error"),
+ )
diff --git a/products/skills/backend/api/community_skill_sync.py b/products/skills/backend/api/community_skill_sync.py
index f6c868b46cd5..9f2adb63a7dd 100644
--- a/products/skills/backend/api/community_skill_sync.py
+++ b/products/skills/backend/api/community_skill_sync.py
@@ -11,8 +11,14 @@ from rest_framework.serializers import ValidationError as DRFValidationError
from posthog.egress.github.transport import github_request
from ..models.community_skills import CommunitySkill, CommunitySkillFile, CommunitySkillTrustTier
-from .skill_serializers import RESERVED_SKILL_NAMES, SKILL_NAME_PATTERN, validate_skill_file_path
-from .skill_services import MAX_SKILL_BODY_BYTES, MAX_SKILL_FILE_BYTES, MAX_SKILL_FILE_COUNT
+from .skill_serializers import validate_skill_file_path
+from .skill_services import (
+ MAX_SKILL_BODY_BYTES,
+ MAX_SKILL_FILE_BYTES,
+ MAX_SKILL_FILE_COUNT,
+ RESERVED_SKILL_NAMES,
+ SKILL_NAME_PATTERN,
+)
logger = structlog.get_logger(__name__)
diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.py
index ce37cda845d7..d7d15972e4c3 100644
--- a/products/skills/backend/api/skill_serializers.py
+++ b/products/skills/backend/api/skill_serializers.py
@@ -1,4 +1,3 @@
-import re
from typing import Any
from django.db import transaction
@@ -11,21 +10,25 @@ from posthog.api.shared import UserBasicSerializer
from products.ai_observability.backend.markdown_outline import get_markdown_outline
from ..models.skills import LLMSkill, LLMSkillFile, category_for_skill_name
+from .community_publish_services import (
+ DISPLAY_NAME_PATTERN,
+ MAX_DISPLAY_NAME_LENGTH,
+ MAX_GITHUB_HANDLE_LENGTH,
+ MAX_TAG_LENGTH,
+ OPTIONAL_GITHUB_HANDLE_PATTERN,
+)
from .skill_services import (
+ RESERVED_SKILL_NAMES,
+ SKILL_NAME_PATTERN,
LLMSkillOwnerNotFoundError,
+ check_allowed_tool_name,
+ normalize_skill_file_path,
resolve_owner_users,
resolve_skill_owners,
seed_skill_owner,
set_skill_owners,
)
-# Skill names that collide with reserved /skills routes and so can't be used: "new" is the create
-# form, and the rest mirror the tab slugs registered under /skills/<slug> in
-# products/skills/manifest.tsx — a skill with such a name would be shadowed by its tab route.
-RESERVED_SKILL_NAMES = {"new", "scouts", "review-hog", "community"}
-# Bundled-file paths that would collide with generated artifacts in the exported skill
-# tree / plugin marketplace (the rendered SKILL.md). Compared case-insensitively.
-RESERVED_SKILL_FILE_PATHS = {"skill.md"}
DEFAULT_VERSION_PAGE_SIZE = 50
# Body-paging metadata is meaningless without the body, so the list serializer drops it alongside body/files.
_LIST_EXCLUDED_FIELDS = ("body", "body_total_length", "body_next_offset", "files")
@@ -43,7 +46,6 @@ MAX_SKILL_OWNERS = 25
# null, never a guess. Sized to sit under observed transport truncation with room for the
# response envelope (outline, file manifest, metadata).
DEFAULT_BODY_PAGE_LENGTH = 8000
-SKILL_NAME_PATTERN = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")
# Tools that opt a scout skill into the report channel. Local copy of
# products/signals/backend/scout_harness/skill_loader.REPORT_CHANNEL_TOOLS — skills must not
# import signals internals, and drift fails closed: a report tool unknown here keeps owners
@@ -77,26 +79,10 @@ def validate_skill_name_value(value: str) -> str:
def validate_skill_file_path(value: str) -> str:
- # Paths become git tree entries (and zip/marketplace paths), so anything that would
- # produce an empty or ambiguous entry name must be rejected — otherwise a single bad
- # path synthesizes a corrupt git tree and breaks the whole team's marketplace clone.
- normalized = value.replace("\\", "/")
- if not normalized or normalized != normalized.strip():
- raise serializers.ValidationError("File path must be a non-empty, trimmed relative path.")
- if normalized.startswith("/"):
- raise serializers.ValidationError("File paths must be relative, not absolute.")
- if normalized.endswith("/"):
- raise serializers.ValidationError("File paths must not end with a slash.")
- if any(part in ("", ".", "..") for part in normalized.split("/")):
- raise serializers.ValidationError("File paths must not contain empty, '.', or '..' segments.")
- if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in normalized):
- raise serializers.ValidationError("File paths must not contain control characters.")
- if normalized.lower() in RESERVED_SKILL_FILE_PATHS:
- raise serializers.ValidationError(f"'{value}' is a reserved file path and cannot be used.")
- # Persist the normalized (forward-slash) form, not the original: backslashes mean "separator"
- # here, so storing them verbatim would make `references\guide.md` a single flat tree entry
- # rather than a file under `references/`, and would let the two spellings dodge dedup.
- return normalized
+ try:
+ return normalize_skill_file_path(value)
+ except ValueError as err:
+ raise serializers.ValidationError(str(err)) from err
def _validate_files(files: list[dict[str, Any]]) -> list[dict[str, Any]]:
@@ -122,11 +108,11 @@ def validate_skill_body_size(body: str) -> str:
def validate_allowed_tool(value: str) -> None:
- # The Agent Skills spec serializes allowed-tools as a single space-separated string, so a tool
- # name containing whitespace would silently fracture into multiple tools on export/round-trip.
# Returns None (raise-only) so it fits a DRF `validators=[...]` list.
- if any(ch.isspace() for ch in value):
- raise serializers.ValidationError("Tool names cannot contain whitespace.")
+ try:
+ check_allowed_tool_name(value)
+ except ValueError as err:
+ raise serializers.ValidationError(str(err)) from err
class LLMSkillFetchQuerySerializer(serializers.Serializer):
@@ -846,3 +832,41 @@ class LLMSkillMarketplaceCommandSerializer(serializers.Serializer):
)
created_at = serializers.DateTimeField(allow_null=True, help_text="When the credential was created.")
last_rolled_at = serializers.DateTimeField(allow_null=True, help_text="When the credential was last rotated.")
+
+
+class LLMSkillPublishToCommunitySerializer(serializers.Serializer):
+ display_name = serializers.RegexField(
+ DISPLAY_NAME_PATTERN,
+ required=False,
+ allow_blank=True,
+ max_length=MAX_DISPLAY_NAME_LENGTH,
+ help_text=(
+ "Human-friendly display name for the community listing. Defaults to a title-cased skill slug. "
+ "Must be a single line: it is used as the pull request title and commit message."
+ ),
+ )
+ tags = serializers.ListField(
+ child=serializers.CharField(max_length=MAX_TAG_LENGTH),
+ required=False,
+ help_text="Tags used for filtering and discovery in the marketplace, e.g. ['web-analytics', 'triage'].",
+ )
+ author_handle = serializers.RegexField(
+ OPTIONAL_GITHUB_HANDLE_PATTERN,
+ required=False,
+ allow_blank=True,
+ # The pattern can't bound the total on its own: each of its repetitions may contribute a
+ # hyphen and a character, so it alone accepts 77 characters — not a username GitHub can hold.
+ max_length=MAX_GITHUB_HANDLE_LENGTH,
+ help_text=(
+ "The publisher's GitHub username, used for public attribution on the listing and PR. Optional, "
+ "and self-reported: it is not verified against the publisher's PostHog account."
+ ),
+ )
+
+
+class CommunitySkillPublishResultSerializer(serializers.Serializer):
+ pr_url = serializers.URLField(
+ help_text="URL of the pull request opened in the community-skills repo for maintainer review."
+ )
+ pr_number = serializers.IntegerField(help_text="Number of the opened pull request.")
+ branch = serializers.CharField(help_text="Name of the branch created in the community-skills repo.")
diff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.py
index c59410631148..fdcb488d52bb 100644
--- a/products/skills/backend/api/skill_services.py
+++ b/products/skills/backend/api/skill_services.py
@@ -1,3 +1,4 @@
+import re
from dataclasses import dataclass
from typing import Any
@@ -19,6 +20,53 @@ MAX_SKILL_VERSION = 2000
MAX_SKILL_BODY_BYTES = 1_000_000
MAX_SKILL_FILE_BYTES = 1_000_000
MAX_SKILL_FILE_COUNT = 200
+# Skill names that collide with reserved /skills routes and so can't be used: "new" is the create
+# form, and the rest mirror the category-tab slugs registered under /skills/<slug> in
+# products/skills/manifest.tsx — a skill with such a name would be shadowed by its tab route.
+# Here rather than in skill_serializers so the publish path can hold a slug to the same rule without
+# importing the serializers that import it.
+RESERVED_SKILL_NAMES = {"new", "scouts", "review-hog", "community"}
+SKILL_NAME_PATTERN = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?$")
+# Bundled-file paths that would collide with generated artifacts in the exported skill
+# tree / plugin marketplace (the rendered SKILL.md). Compared case-insensitively.
+RESERVED_SKILL_FILE_PATHS = {"skill.md"}
+
+
+def normalize_skill_file_path(value: str) -> str:
+ """Return the canonical relative path for a bundled file, raising ValueError if it has none.
+
+ Here rather than in skill_serializers so the publish path can canonicalize a path the same way
+ without importing the serializers that import it. skill_serializers wraps it as the DRF
+ validator, so the request layer keeps reporting these as field errors.
+ """
+ # Paths become git tree entries (and zip/marketplace paths), so anything that would
+ # produce an empty or ambiguous entry name must be rejected — otherwise a single bad
+ # path synthesizes a corrupt git tree and breaks the whole team's marketplace clone.
+ normalized = value.replace("\\", "/")
+ if not normalized or normalized != normalized.strip():
+ raise ValueError("File path must be a non-empty, trimmed relative path.")
+ if normalized.startswith("/"):
+ raise ValueError("File paths must be relative, not absolute.")
+ if normalized.endswith("/"):
+ raise ValueError("File paths must not end with a slash.")
+ if any(part in ("", ".", "..") for part in normalized.split("/")):
+ raise ValueError("File paths must not contain empty, '.', or '..' segments.")
+ if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in normalized):
+ raise ValueError("File paths must not contain control characters.")
+ if normalized.lower() in RESERVED_SKILL_FILE_PATHS:
+ raise ValueError(f"'{value}' is a reserved file path and cannot be used.")
+ # Persist the normalized (forward-slash) form, not the original: backslashes mean "separator"
+ # here, so storing them verbatim would make `references\guide.md` a single flat tree entry
+ # rather than a file under `references/`, and would let the two spellings dodge dedup.
+ return normalized
+
+
+def check_allowed_tool_name(value: str) -> None:
+ """Raise ValueError when a tool name can't survive the Agent Skills allowed-tools encoding."""
+ # The Agent Skills spec serializes allowed-tools as a single space-separated string, so a tool
+ # name containing whitespace would silently fracture into multiple tools on export/round-trip.
+ if any(ch.isspace() for ch in value):
+ raise ValueError("Tool names cannot contain whitespace.")
class LLMSkillNotFoundError(Exception):
diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.py
index 64ff60aff68c..90bca8205579 100644
--- a/products/skills/backend/api/skills.py
+++ b/products/skills/backend/api/skills.py
@@ -27,7 +27,7 @@ from posthog.auth import (
from posthog.event_usage import report_user_action
from posthog.models import User
from posthog.permissions import AccessControlPermission, get_authenticator_scopes
-from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottle
+from posthog.rate_limit import BurstRateThrottle, PersonalApiKeyOrUserRateThrottle, SustainedRateThrottle
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
from products.ai_observability.backend.api.metrics import llma_track_latency
@@ -43,10 +43,19 @@ from ..marketplace.credentials import (
)
from ..marketplace.packaging import SkillImportError, build_skill_zip, parse_skill_zip, validate_for_export
from ..models.skills import LLMSkill, LLMSkillFile
+from .community_publish_services import (
+ CommunitySkillPublishError,
+ CommunitySkillPublishNotConfiguredError,
+ CommunitySkillPublishValidationError,
+ publish_skill_to_community,
+ publishable_tags,
+)
+from .community_skills import CommunitySkillFeatureFlagPermission
from .skill_serializers import (
DEFAULT_BODY_PAGE_LENGTH,
MAX_SKILL_FILE_BYTES,
PUBLISH_CONTENT_FIELDS,
+ CommunitySkillPublishResultSerializer,
LLMSkillBodyFetchQuerySerializer,
LLMSkillCreateSerializer,
LLMSkillDuplicateSerializer,
@@ -61,6 +70,7 @@ from .skill_serializers import (
LLMSkillMarketplaceCommandSerializer,
LLMSkillMarketplaceIssueSerializer,
LLMSkillPublishSerializer,
+ LLMSkillPublishToCommunitySerializer,
LLMSkillResolveQuerySerializer,
LLMSkillResolveResponseSerializer,
LLMSkillSerializer,
@@ -159,6 +169,44 @@ ALLOWED_LIST_ORDERINGS = frozenset(
)
+class CommunityPublishFeatureFlagPermission(CommunitySkillFeatureFlagPermission):
+ """Gates publishing to the community marketplace, and nothing else on this viewset.
+
+ The Skills product is GA and the marketplace is not, so the flag can only bind to the one action —
+ otherwise the whole product goes dark, and without it publish goes live everywhere the moment the
+ GitHub App is installed and the 503 fail-safe stops firing.
+ """
+
+ def has_permission(self, request, view) -> bool:
+ if getattr(view, "action", None) != "publish_to_community":
+ return True
+ return super().has_permission(request, view)
+
+
+class _CommunityPublishThrottle(PersonalApiKeyOrUserRateThrottle):
+ # Publishing opens a pull request in a public repo, so the ceiling is "a handful, by hand", not
+ # the API-shaped hundreds-per-minute of BurstRateThrottle. That one also extends
+ # PersonalApiKeyRateThrottle, which ignores session traffic.
+ def get_cache_key(self, request, view):
+ # Per team, not per credential. The inherited key prefers the personal API key hash, so one
+ # member holding several keys would get a fresh budget with each of them — and the skill
+ # being published belongs to the team either way.
+ team_id = self.safely_get_team_id_from_view(view)
+ if team_id is None:
+ return super().get_cache_key(request, view)
+ return self.cache_format % {"scope": self.scope, "ident": f"team-{team_id}"}
+
+
+class CommunityPublishBurstThrottle(_CommunityPublishThrottle):
+ scope = "community_skill_publish_burst"
+ rate = "6/hour"
+
+
+class CommunityPublishSustainedThrottle(_CommunityPublishThrottle):
+ scope = "community_skill_publish_sustained"
+ rate = "20/day"
+
+
class LLMSkillViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
@@ -169,12 +217,14 @@ class LLMSkillViewSet(
scope_object = "llm_skill"
queryset = LLMSkill.objects.all()
serializer_class = LLMSkillSerializer
- permission_classes = [AccessControlPermission]
+ permission_classes = [AccessControlPermission, CommunityPublishFeatureFlagPermission]
def safely_get_queryset(self, queryset: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]:
return get_active_skill_queryset(self.team)
def get_throttles(self):
+ if self.action == "publish_to_community":
+ return [CommunityPublishBurstThrottle(), CommunityPublishSustainedThrottle()]
if self.action in ["update_by_name", "get_by_name", "resolve_by_name"]:
return [BurstRateThrottle(), SustainedRateThrottle()]
return super().get_throttles()
@@ -908,6 +958,90 @@ class LLMSkillViewSet(
)
return Response(self._serialize_skill(new_skill), status=status.HTTP_201_CREATED)
+ @extend_schema(request=LLMSkillPublishToCommunitySerializer, responses={201: CommunitySkillPublishResultSerializer})
+ @action(
+ methods=["POST"],
+ detail=False,
+ url_path=r"name/(?P<skill_name>[^/]+)/publish-community",
+ required_scopes=["llm_skill:write"],
+ )
+ @llma_track_latency("llma_skills_publish_community")
+ @monitor(feature=None, endpoint="llma_skills_publish_community", method="POST")
+ def publish_to_community(self, request: Request, skill_name: str = "", **kwargs) -> Response:
+ auth_error = self._ensure_web_authenticated(request)
+ if auth_error is not None:
+ return auth_error
+
+ skill = get_skill_by_name_from_db(self.team, skill_name)
+ if skill is None:
+ return self._skill_not_found_response(skill_name)
+
+ payload = LLMSkillPublishToCommunitySerializer(data=request.data)
+ payload.is_valid(raise_exception=True)
+
+ files = [{"path": f.path, "content": f.content, "content_type": f.content_type} for f in skill.files.all()]
+ supplied_tags = payload.validated_data.get("tags")
+ # An explicit empty list means "publish with no tags", so fall back to the skill's own tags
+ # only when the caller omitted the field. Those are unvalidated metadata, unlike the ones the
+ # serializer checked, so they go through publishable_tags first.
+ if supplied_tags is None:
+ supplied_tags = publishable_tags((skill.metadata or {}).get("tags"))
+ # The LLMSkill name is the kebab slug; default the community display name to a title-cased form.
+ display_name = payload.validated_data.get("display_name") or skill.name.replace("-", " ").title()
+
+ try:
+ result = publish_skill_to_community(
+ slug=skill.name,
+ # Scopes the publish branch to this team, so one team cannot rewrite another team's
+ # open pull request for the same slug.
+ publisher_id=str(self.team.uuid),
+ name=display_name,
+ description=skill.description,
+ body=skill.body,
+ files=files or None,
+ tags=supplied_tags,
+ allowed_tools=skill.allowed_tools or [],
+ license=skill.license or "",
+ compatibility=skill.compatibility or "",
+ author_handle=payload.validated_data.get("author_handle", ""),
+ )
+ except CommunitySkillPublishNotConfiguredError:
+ return Response(
+ {"detail": "Publishing to the community is not available on this instance."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ except CommunitySkillPublishValidationError as err:
+ # Nothing reached GitHub, and republishing the same skill fails the same way — the
+ # publisher has to edit it. That is a 400, not the 502 an unreachable GitHub gets.
+ return Response({"detail": str(err)}, status=status.HTTP_400_BAD_REQUEST)
+ except CommunitySkillPublishError as err:
+ # The client sees the reason once; without this the server keeps no record of a publish
+ # that failed against GitHub.
+ logger.warning(
+ "llma_skill_publish_to_community_failed",
+ team_id=self.team.id,
+ user_id=cast(User, request.user).id,
+ skill_name=skill.name,
+ error=str(err),
+ )
+ return Response({"detail": str(err)}, status=status.HTTP_502_BAD_GATEWAY)
+
+ props = {**_skill_analytics_props(skill), "community_pr_number": result["pr_number"]}
+ logger.info(
+ "llma_skill_published_to_community",
+ team_id=self.team.id,
+ user_id=cast(User, request.user).id,
+ **props,
+ )
+ report_user_action(
+ cast(User, request.user),
+ "llma skill published to community",
+ props,
+ team=self.team,
+ request=request,
+ )
+ return Response(result, status=status.HTTP_201_CREATED)
+
@extend_schema(
parameters=[LLMSkillFetchQuerySerializer],
responses={200: LLMSkillFileSerializer},
diff --git a/products/skills/backend/api/test/test_community_publish_services.py b/products/skills/backend/api/test/test_community_publish_services.py
new file mode 100644
index 000000000000..1dc66cc1c9e3
--- /dev/null
+++ b/products/skills/backend/api/test/test_community_publish_services.py
@@ -0,0 +1,509 @@
+import re
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+import yaml
+import requests
+from parameterized import parameterized
+
+from posthog.models.github_integration_base import GitHubIntegrationError
+
+from products.skills.backend.api.community_publish_services import (
+ MAX_TAG_LENGTH,
+ CommunitySkillPublishError,
+ CommunitySkillPublishValidationError,
+ get_community_skills_publisher,
+ publish_skill_to_community,
+ publisher_branch_key,
+ render_community_skill_files,
+ render_skill_md,
+)
+from products.skills.backend.api.skill_services import MAX_SKILL_BODY_BYTES, MAX_SKILL_FILE_BYTES, MAX_SKILL_FILE_COUNT
+from products.skills.backend.marketplace.packaging import SPEC_DESCRIPTION_MAX_LENGTH
+
+# Mirror of the community-skills repo's frontmatter parser (scripts/build_registry.py) so these
+# tests fail if we ever render a SKILL.md the repo's own CI would reject.
+FRONTMATTER_RE = re.compile(r"^---\n(.*?)\n---\n?(.*)$", re.DOTALL)
+
+
+def _parse(content: str) -> tuple[dict, str]:
+ match = FRONTMATTER_RE.match(content)
+ assert match is not None, "rendered SKILL.md must start with a YAML frontmatter block"
+ return yaml.safe_load(match.group(1)) or {}, match.group(2).strip()
+
+
+class TestRenderSkillMd:
+ def test_renders_required_fields_and_body(self) -> None:
+ content = render_skill_md(
+ name="Make PR", description="Open a PR for the current branch.", body="# Make PR\n\nDo it."
+ )
+ frontmatter, body = _parse(content)
+ assert frontmatter["name"] == "Make PR"
+ assert frontmatter["description"] == "Open a PR for the current branch."
+ assert frontmatter["trust_tier"] == "community"
+ assert body == "# Make PR\n\nDo it."
+
+ def test_optional_fields_omitted_when_empty(self) -> None:
+ frontmatter, _ = _parse(render_skill_md(name="X", description="Y", body="Z"))
+ for omitted in ("tags", "author_handle", "license", "compatibility", "allowed_tools"):
+ assert omitted not in frontmatter
+
+ def test_optional_fields_included_when_set(self) -> None:
+ content = render_skill_md(
+ name="Make PR",
+ description="Open a PR.",
+ body="body",
+ tags=["github", "workflow"],
+ allowed_tools=["query", "docs-search"],
+ license="MIT",
+ compatibility="Requires gh",
+ author_handle="andymaguire",
+ )
+ frontmatter, _ = _parse(content)
+ assert frontmatter["tags"] == ["github", "workflow"]
+ assert frontmatter["allowed_tools"] == ["query", "docs-search"]
+ assert frontmatter["license"] == "MIT"
+ assert frontmatter["compatibility"] == "Requires gh"
+ assert frontmatter["author_handle"] == "andymaguire"
+
+ def test_preserves_leading_whitespace_in_the_body(self) -> None:
+ # strip() would turn an opening indented code block into an ordinary paragraph, so the
+ # published skill would instruct differently from the skill it was published from.
+ content = render_skill_md(name="X", description="Y", body=" indented code\n\ntext\n\n\n")
+
+ assert content.endswith("---\n\n indented code\n\ntext\n")
+
+ @parameterized.expand(
+ [
+ ("blank name", " ", "d", "b"),
+ ("blank description", "n", "", "b"),
+ # install_community_skill refuses a blank body as having no instructions, so publishing
+ # one merges a listing that nobody can ever install.
+ ("blank body", "n", "d", " \n "),
+ # Longer than the Agent Skills spec allows, so validate_for_export refuses the skill once
+ # someone installs it from the catalog.
+ ("description over the spec cap", "n", "x" * (SPEC_DESCRIPTION_MAX_LENGTH + 1), "b"),
+ # Longer than CommunitySkill.name: the PR would merge and ingest would then drop the entry.
+ ("name over 64 chars", "x" * 65, "d", "b"),
+ # The name becomes the commit message, where a trailer would reattribute the App's commit.
+ ("name spanning two lines", "Make PR\nCo-authored-by: someone <[email protected]>", "d", "b"),
+ ]
+ )
+ def test_requires_the_fields_a_listing_cannot_do_without(
+ self, _label: str, name: str, description: str, body: str
+ ) -> None:
+ with pytest.raises(CommunitySkillPublishError):
+ render_skill_md(name=name, description=description, body=body)
+
+ @parameterized.expand(
+ [
+ ("with a space in it", "not a handle"),
+ ("with a double hyphen", "andy--maguire"),
+ # 77 characters: the pattern's repetition can contribute a hyphen and a character each, so
+ # nothing bounds the total unless the length is held beside it, and the listing would
+ # attribute the skill to a handle GitHub cannot hold.
+ ("longer than a GitHub username", "-".join("a" for _ in range(39))),
+ ]
+ )
+ def test_rejects_an_author_handle_that_is_not_a_github_username(self, _label: str, handle: str) -> None:
+ with pytest.raises(CommunitySkillPublishError):
+ render_skill_md(name="n", description="d", body="b", author_handle=handle)
+
+ @parameterized.expand(
+ [
+ ("a tool name with a space", ["Bash Write"]),
+ ("a tool name with a newline", ["Bash\nWrite"]),
+ ("a tool name that is not a string", [123]),
+ ]
+ )
+ def test_rejects_allowed_tools_ingest_would_drop(self, _label: str, allowed_tools: list[Any]) -> None:
+ # create_skill stores what a tool call passed without the REST serializer's checks, and
+ # ingest rejects a whitespace-bearing or non-string tool name, so publishing one opens a
+ # pull request that merges and whose skill never appears in the catalog.
+ with pytest.raises(CommunitySkillPublishError):
+ render_skill_md(name="n", description="d", body="b", allowed_tools=allowed_tools)
+
+
+class TestRenderCommunitySkillFiles:
+ def test_skill_md_path_and_bundled_files(self) -> None:
+ rendered = render_community_skill_files(
+ slug="make-pr",
+ name="Make PR",
+ description="Open a PR.",
+ body="body",
+ files=[
+ {"path": "references/playbook.md", "content": "hints", "content_type": "text/markdown"},
+ # A skill created through the Max tool can store the backslash spelling, and ingest
+ # canonicalizes it, so the publish has to write the forward-slash path ingest will
+ # then look for rather than one flat `scripts\\run.sh` tree entry.
+ {"path": "scripts\\run.sh", "content": "echo hi", "content_type": "text/plain"},
+ ],
+ )
+ paths = {f.path for f in rendered}
+ assert paths == {
+ "skills/make-pr/SKILL.md",
+ "skills/make-pr/references/playbook.md",
+ "skills/make-pr/scripts/run.sh",
+ }
+
+ def test_rejects_bad_slug(self) -> None:
+ # "new" and the category-tab slugs are rejected by ingest, so publishing one merges a pull
+ # request whose skill never appears in the catalog. A trailing newline needs `fullmatch`.
+ for bad in ["Make-PR", "make_pr", "-bad", "double--hyphen", "x" * 65, "new", "review-hog", "make-pr\n"]:
+ try:
+ render_community_skill_files(slug=bad, name="n", description="d", body="b")
+ except CommunitySkillPublishError:
+ continue
+ raise AssertionError(f"expected rejection for slug {bad!r}")
+
+ @parameterized.expand(
+ [
+ ("path traversal", ["../escape.md"]),
+ ("overwriting the rendered SKILL.md", ["SKILL.md"]),
+ # Ingest case-folds paths and drops the whole entry on a collision, so publishing both
+ # opens a pull request that merges and then never appears in the catalog.
+ ("paths differing only by case", ["references/Guide.md", "references/guide.md"]),
+ # Same reason: ingest canonicalizes the backslash spelling, so the two paths that look
+ # distinct here are one duplicate path by the time the merged entry is read.
+ ("the same path spelled with a backslash", ["references\\guide.md", "references/guide.md"]),
+ ("an absolute path", ["/references/guide.md"]),
+ # A git tree can't hold `references` as both a blob and a directory, so GitHub rejects
+ # the whole tree and the skill can't be published at all.
+ ("a name used as both file and folder", ["references", "references/guide.md"]),
+ ]
+ )
+ def test_rejects_unpublishable_bundled_file_paths(self, _label: str, paths: list[str]) -> None:
+ with pytest.raises(CommunitySkillPublishError):
+ render_community_skill_files(
+ slug="make-pr",
+ name="n",
+ description="d",
+ body="b",
+ files=[{"path": path, "content": "x", "content_type": "text/plain"} for path in paths],
+ )
+
+
+class TestPublishableSize:
+ @parameterized.expand(
+ [
+ # Ingest's own per-entry caps: breaching one drops the whole entry, so the pull request
+ # merges and the skill never appears in the catalog.
+ ("body over the catalog cap", "x" * (MAX_SKILL_BODY_BYTES + 1), 1, 10),
+ ("more files than the catalog takes", "b", MAX_SKILL_FILE_COUNT + 1, 10),
+ ("one file over the catalog cap", "b", 1, MAX_SKILL_FILE_BYTES + 1),
+ # GitHub's cap on a single create-tree request, which inlines every file's content.
+ ("files summing over the tree cap", "b", 6, MAX_SKILL_FILE_BYTES),
+ ]
+ )
+ def test_rejects_a_skill_no_publish_could_survive(
+ self, _label: str, body: str, file_count: int, file_size: int
+ ) -> None:
+ with pytest.raises(CommunitySkillPublishError):
+ render_community_skill_files(
+ slug="make-pr",
+ name="n",
+ description="d",
+ body=body,
+ files=[
+ {"path": f"references/{index}.md", "content": "x" * file_size, "content_type": "text/markdown"}
+ for index in range(file_count)
+ ],
+ )
+
+ def test_counts_the_rendered_frontmatter_against_the_tree_cap(self) -> None:
+ # Nothing caps how many tags a skill stores, and every one is rendered into SKILL.md, so
+ # measuring the fields the files came from instead of the files themselves leaves the
+ # difference between them unbounded.
+ files = [
+ {"path": f"references/{index}.md", "content": "x" * MAX_SKILL_FILE_BYTES, "content_type": "text/markdown"}
+ for index in range(4)
+ ]
+ fields: dict[str, Any] = {"slug": "make-pr", "name": "n", "description": "d", "body": "x" * 990_000}
+
+ render_community_skill_files(**fields, files=files)
+
+ with pytest.raises(CommunitySkillPublishError):
+ render_community_skill_files(**fields, files=files, tags=["t" * MAX_TAG_LENGTH] * 4000)
+
+ def test_rejects_a_skill_whose_encoded_payload_blows_the_tree_cap(self) -> None:
+ # 3 MB of newlines clears every raw-byte check, and doubles once escaped into the single JSON
+ # body the tree write inlines it in. Counted raw, this publishes and then fails against
+ # GitHub with a 502 the publisher can do nothing with.
+ with pytest.raises(CommunitySkillPublishError):
+ render_community_skill_files(
+ slug="make-pr",
+ name="n",
+ description="d",
+ body="b",
+ files=[
+ {
+ "path": f"references/{index}.md",
+ "content": "\n" * MAX_SKILL_FILE_BYTES,
+ "content_type": "text/markdown",
+ }
+ for index in range(3)
+ ],
+ )
+
+
+class TestCommunitySkillsPublisher:
+ def _response(self, status_code: int, payload: dict) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = payload
+ return response
+
+ @override_settings(
+ COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID="4242",
+ COMMUNITY_SKILLS_GITHUB_REPO="community-skills",
+ GITHUB_APP_CLIENT_ID="client",
+ GITHUB_APP_PRIVATE_KEY="key",
+ )
+ @patch("products.skills.backend.api.community_publish_services.GitHubIntegration.client_request")
+ def test_mints_a_token_scoped_to_the_publish_repository(self, mock_request: MagicMock) -> None:
+ mock_request.side_effect = [
+ self._response(200, {"account": {"login": "PostHog", "type": "Organization"}}),
+ self._response(201, {"token": "ghs_x"}),
+ ]
+
+ assert get_community_skills_publisher() is not None
+
+ mint_body = mock_request.call_args.kwargs["json_body"]
+ assert mint_body["repositories"] == ["community-skills"]
+ # A publish writes files and opens a pull request. Anything else the installation holds is
+ # blast radius this transient token has no use for.
+ assert mint_body["permissions"] == {"contents": "write", "pull_requests": "write", "metadata": "read"}
+
+ @parameterized.expand(
+ [
+ ("the app is not installed here", 404, False),
+ ("github refuses the app credentials", 401, False),
+ ("github fails the mint", 500, True),
+ ]
+ )
+ def test_only_a_refused_installation_reads_as_not_configured(
+ self, _label: str, token_status: int, is_gateway_failure: bool
+ ) -> None:
+ # None here becomes the endpoint's 503, which tells the publisher this instance can't publish
+ # at all. A transient failure must not say that: it sends them to the manual path over an
+ # outage that clears by itself.
+ settings_override = override_settings(
+ COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID="4242",
+ COMMUNITY_SKILLS_GITHUB_REPO="community-skills",
+ GITHUB_APP_CLIENT_ID="client",
+ GITHUB_APP_PRIVATE_KEY="key",
+ )
+ with (
+ settings_override,
+ patch(
+ "products.skills.backend.api.community_publish_services.GitHubIntegration.client_request"
+ ) as mock_request,
+ ):
+ mock_request.side_effect = [
+ self._response(200, {"account": {"login": "PostHog", "type": "Organization"}}),
+ self._response(token_status, {}),
+ ]
+
+ if is_gateway_failure:
+ with pytest.raises(CommunitySkillPublishError):
+ get_community_skills_publisher()
+ else:
+ assert get_community_skills_publisher() is None
+
+ @override_settings(
+ COMMUNITY_SKILLS_GITHUB_INSTALLATION_ID="4242",
+ COMMUNITY_SKILLS_GITHUB_REPO="community-skills",
+ GITHUB_APP_CLIENT_ID="client",
+ GITHUB_APP_PRIVATE_KEY="key",
+ )
+ @patch("products.skills.backend.api.community_publish_services.GitHubIntegration.client_request")
+ def test_github_being_unreachable_while_minting_raises_a_publish_error(self, mock_request: MagicMock) -> None:
+ # client_request goes to the transport directly, so a timeout arrives raw rather than as the
+ # GitHubIntegrationError api_request would wrap it in. Unhandled, the endpoint answers 500.
+ mock_request.side_effect = requests.ConnectTimeout("boom")
+
+ with pytest.raises(CommunitySkillPublishError):
+ get_community_skills_publisher()
+
+
+TEAM_A = "11111111-1111-1111-1111-111111111111"
+TEAM_B = "22222222-2222-2222-2222-222222222222"
+# Branch for slug "make-pr" published by TEAM_A.
+TEAM_A_BRANCH = f"community-skill/make-pr-{publisher_branch_key(TEAM_A)}"
+
+
+class TestPublishSkillToCommunity:
+ def _publisher(self, *, open_pr: dict | None = None) -> MagicMock:
+ publisher = MagicMock()
+ publisher.get_open_pull_request_for_head.return_value = open_pr
+ publisher.commit_files_to_branch.return_value = {"success": True, "commit_sha": "abc123"}
+ publisher.create_pull_request.return_value = {
+ "success": True,
+ "pr_number": 12,
+ "pr_url": "https://github.com/PostHog/community-skills/pull/12",
+ }
+ publisher.delete_branch.return_value = {"success": True}
+ return publisher
+
+ def _publish(self, publisher: MagicMock, *, publisher_id: str = TEAM_A) -> dict:
+ with patch(
+ "products.skills.backend.api.community_publish_services.get_community_skills_publisher",
+ return_value=publisher,
+ ):
+ return publish_skill_to_community(
+ slug="make-pr",
+ publisher_id=publisher_id,
+ name="Make PR",
+ description="Open a PR.",
+ body="body",
+ files=[{"path": "references/playbook.md", "content": "hints", "content_type": "text/markdown"}],
+ )
+
+ def test_a_skill_that_cannot_be_published_is_rejected_before_the_publisher_is_acquired(self) -> None:
+ # Acquiring the publisher talks to GitHub, so a skill that fails rendering used to come back
+ # as 502 or 503 whenever the App was down or unconfigured — advice to retry, for a publish
+ # that can only succeed once the publisher edits the skill.
+ with patch(
+ "products.skills.backend.api.community_publish_services.get_community_skills_publisher",
+ side_effect=AssertionError("the publisher was acquired before the skill was validated"),
+ ):
+ with pytest.raises(CommunitySkillPublishValidationError):
+ publish_skill_to_community(
+ slug="make-pr", publisher_id=TEAM_A, name="Make PR", description="", body="body"
+ )
+
+ def test_commits_every_file_in_one_commit(self) -> None:
+ publisher = self._publisher()
+
+ result = self._publish(publisher)
+
+ assert result == {
+ "pr_url": "https://github.com/PostHog/community-skills/pull/12",
+ "pr_number": 12,
+ "branch": TEAM_A_BRANCH,
+ }
+ publisher.commit_files_to_branch.assert_called_once()
+ # The skill's directory is replaced, not merged onto main, so a bundled file dropped since
+ # the last publish stops being published instead of surviving on the branch.
+ assert publisher.commit_files_to_branch.call_args.kwargs["replace_directory"] == "skills/make-pr"
+ committed_files = publisher.commit_files_to_branch.call_args.args[3]
+ assert set(committed_files) == {"skills/make-pr/SKILL.md", "skills/make-pr/references/playbook.md"}
+
+ @parameterized.expand(
+ [
+ ("transient github failure", "GitHub said no", True),
+ # A branch that already heads a pull request belongs to that review, not to this call.
+ ("pull request already exists", "A pull request already exists for PostHog:community-skill/x.", False),
+ ]
+ )
+ def test_branch_cleanup_when_the_pull_request_fails(self, _label: str, error: str, deleted: bool) -> None:
+ publisher = self._publisher()
+ publisher.create_pull_request.return_value = {"success": False, "error": error}
+
+ with pytest.raises(CommunitySkillPublishError):
+ self._publish(publisher)
+
+ assert publisher.delete_branch.called is deleted
+ if deleted:
+ assert publisher.delete_branch.call_args.args[1] == TEAM_A_BRANCH
+
+ def test_reuses_the_open_pull_request_for_the_same_skill(self) -> None:
+ publisher = self._publisher(
+ open_pr={"number": 5, "url": "https://github.com/PostHog/community-skills/pull/5", "base": "main"}
+ )
+
+ result = self._publish(publisher)
+
+ assert result["pr_number"] == 5
+ publisher.create_pull_request.assert_not_called()
+ publisher.commit_files_to_branch.assert_called_once()
+
+ def test_a_reused_pull_request_that_ends_mid_publish_opens_a_new_one(self) -> None:
+ # Open when we look before the write, merged by the time the commit lands. Returning it would
+ # report success for a review that no longer carries the commit, and leave that commit on a
+ # public branch with nothing open over it.
+ open_pr = {"number": 5, "url": "https://github.com/PostHog/community-skills/pull/5", "base": "main"}
+ publisher = self._publisher(open_pr=open_pr)
+ publisher.get_open_pull_request_for_head.side_effect = [open_pr, None]
+
+ result = self._publish(publisher)
+
+ assert result["pr_number"] == 12
+ publisher.create_pull_request.assert_called_once()
+ publisher.delete_branch.assert_not_called()
+
+ def test_refuses_a_pull_request_retargeted_away_from_the_base_branch(self) -> None:
+ # Merging it writes to that other branch, so the skill never reaches the catalog. Reusing it
+ # would report a successful publish for content nothing will ever pick up.
+ publisher = self._publisher(
+ open_pr={"number": 5, "url": "https://github.com/PostHog/community-skills/pull/5", "base": "draft"}
+ )
+
+ with pytest.raises(CommunitySkillPublishError):
+ self._publish(publisher)
+
+ publisher.commit_files_to_branch.assert_not_called()
+ publisher.delete_branch.assert_not_called()
+
+ def test_another_team_publishing_the_same_slug_writes_its_own_branch(self) -> None:
+ # Slugs are unique per team, so a slug-only branch would let team B rewrite team A's open PR.
+ publisher = self._publisher()
+
+ self._publish(publisher, publisher_id=TEAM_B)
+
+ branch = publisher.commit_files_to_branch.call_args.args[1]
+ assert branch.startswith("community-skill/make-pr-")
+ assert branch != TEAM_A_BRANCH
+
+ def test_a_concurrent_publish_returns_the_pull_request_that_won_the_race(self) -> None:
+ # Both requests force-update the same branch, so the loser's commit is already inside the
+ # winner's review. Reporting a failure would deny content that is public by then.
+ publisher = self._publisher()
+ winner = {"number": 9, "url": "https://github.com/PostHog/community-skills/pull/9", "base": "main"}
+ publisher.get_open_pull_request_for_head.side_effect = [None, winner]
+ publisher.create_pull_request.return_value = {
+ "success": False,
+ "error": "A pull request already exists for PostHog:community-skill/x.",
+ }
+
+ result = self._publish(publisher)
+
+ assert result["pr_number"] == 9
+ publisher.delete_branch.assert_not_called()
+
+ def test_a_pull_request_create_that_times_out_after_landing_keeps_the_branch(self) -> None:
+ # api_request doesn't retry a POST, so a transport failure here can still have opened the
+ # pull request. Cleaning up blind would delete a branch under live review.
+ publisher = self._publisher()
+ landed = {"number": 9, "url": "https://github.com/PostHog/community-skills/pull/9", "base": "main"}
+ publisher.get_open_pull_request_for_head.side_effect = [None, landed]
+ publisher.create_pull_request.side_effect = GitHubIntegrationError("timeout")
+
+ result = self._publish(publisher)
+
+ assert result["pr_number"] == 9
+ publisher.delete_branch.assert_not_called()
+
+ def test_a_pull_request_create_that_times_out_with_nothing_landed_deletes_the_branch(self) -> None:
+ publisher = self._publisher()
+ publisher.get_open_pull_request_for_head.side_effect = [None, None]
+ publisher.create_pull_request.side_effect = GitHubIntegrationError("timeout")
+
+ with pytest.raises(CommunitySkillPublishError):
+ self._publish(publisher)
+
+ assert publisher.delete_branch.call_args.args[1] == TEAM_A_BRANCH
+ # Conditional on our own commit: the branch name is shared with every concurrent publish of
+ # this skill from this team, and deleting theirs destroys work only we could have recovered.
+ assert publisher.delete_branch.call_args.kwargs["expected_sha"] == "abc123"
+
+ def test_github_being_unreachable_raises_a_publish_error(self) -> None:
+ publisher = self._publisher()
+ publisher.get_open_pull_request_for_head.side_effect = GitHubIntegrationError("network error")
+
+ with pytest.raises(CommunitySkillPublishError):
+ self._publish(publisher)
diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.py
index 5e71fb322ec0..e20bef174ad3 100644
--- a/products/skills/backend/api/test/test_skills.py
+++ b/products/skills/backend/api/test/test_skills.py
@@ -1,6 +1,7 @@
import uuid
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from django.core.cache import cache
@@ -13,6 +14,11 @@ from posthog.models.organization import OrganizationMembership
from ee.models.rbac.access_control import AccessControl
+from ...api.community_publish_services import (
+ CommunitySkillPublishError,
+ CommunitySkillPublishNotConfiguredError,
+ CommunitySkillPublishValidationError,
+)
from ...api.skill_serializers import DEFAULT_BODY_PAGE_LENGTH
from ...api.skill_services import (
MAX_SKILL_FILE_COUNT,
@@ -24,6 +30,8 @@ from ...api.skill_services import (
)
from ...models.skills import LLMSkill, LLMSkillFile
+COMMUNITY_FLAG = "products.skills.backend.api.community_skills.posthoganalytics.feature_enabled"
+
class TestLLMSkillAPI(APIBaseTest):
def _url(self, path: str = "") -> str:
@@ -1245,6 +1253,143 @@ class TestLLMSkillAPI(APIBaseTest):
assert data["versions"][0]["version"] == 2
assert data["versions"][1]["version"] == 1
+ # --- Publish to community ---
+
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_succeeds(self, mock_publish, _mock_flag):
+ mock_publish.return_value = {
+ "pr_url": "https://github.com/PostHog/community-skills/pull/7",
+ "pr_number": 7,
+ "branch": "community-skill/make-pr",
+ }
+ skill = self.create_skill(
+ name="make-pr",
+ description="Open a PR.",
+ body="# Make PR",
+ allowed_tools=["query"],
+ metadata={"tags": ["github"]},
+ )
+ LLMSkillFile.objects.create(
+ skill=skill, path="references/playbook.md", content="hints", content_type="text/markdown"
+ )
+
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"author_handle": "andymaguire"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert response.json() == mock_publish.return_value
+ _, kwargs = mock_publish.call_args
+ assert kwargs["slug"] == "make-pr"
+ assert kwargs["name"] == "Make Pr" # default display name = title-cased slug
+ assert kwargs["description"] == "Open a PR."
+ assert kwargs["tags"] == ["github"] # falls back to metadata tags
+ assert kwargs["allowed_tools"] == ["query"]
+ assert kwargs["author_handle"] == "andymaguire"
+ assert kwargs["files"] == [
+ {"path": "references/playbook.md", "content": "hints", "content_type": "text/markdown"}
+ ]
+
+ @parameterized.expand(
+ [
+ # An explicit empty list means "no tags" and must not fall back to the skill's own tags.
+ ("explicit empty list", {"tags": []}, ["github"], []),
+ # metadata is an arbitrary dict, and ingest drops an entry whose tags are not all strings.
+ ("unusable metadata tags", {}, ["github", 123, {"name": "x"}, " ", "y" * 65], ["github"]),
+ # Sync only lowercases a tag and filtering matches it exactly, so an unstripped tag would
+ # publish as one no catalog filter can select.
+ ("padded metadata tags", {}, [" github "], ["github"]),
+ ]
+ )
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_tags(
+ self, _label: str, payload: dict, metadata_tags: list, expected: list, mock_publish, _mock_flag
+ ):
+ mock_publish.return_value = {"pr_url": "https://github.com/x/y/pull/1", "pr_number": 1, "branch": "b"}
+ self.create_skill(name="make-pr", metadata={"tags": metadata_tags})
+
+ response = self.client.post(self._url("name/make-pr/publish-community"), data=payload, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED
+ assert mock_publish.call_args.kwargs["tags"] == expected
+
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_unknown_skill_returns_404(self, mock_publish, _mock_flag):
+ response = self.client.post(self._url("name/does-not-exist/publish-community"), data={}, format="json")
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+ mock_publish.assert_not_called()
+
+ @parameterized.expand(
+ [
+ # Longer than CommunitySkill.name: the PR merges and ingest then drops the entry.
+ ("over the catalog limit", "x" * 65),
+ # The name becomes the commit message, where a trailer would reattribute the App's commit.
+ ("spanning two lines", "Make PR\nCo-authored-by: someone <[email protected]>"),
+ ]
+ )
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_rejects_display_name(self, _label: str, display_name: str, mock_publish, _mock_flag):
+ self.create_skill(name="make-pr")
+
+ response = self.client.post(
+ self._url("name/make-pr/publish-community"),
+ data={"display_name": display_name},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ mock_publish.assert_not_called()
+
+ @patch(COMMUNITY_FLAG, return_value=False)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_is_gated_on_the_community_flag(self, mock_publish, _mock_flag):
+ self.create_skill(name="make-pr")
+
+ response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_publish.assert_not_called()
+
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_not_configured_returns_503(self, mock_publish, _mock_flag):
+ mock_publish.side_effect = CommunitySkillPublishNotConfiguredError("nope")
+ self.create_skill(name="make-pr")
+
+ response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+
+ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
+
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_invalid_skill_returns_400(self, mock_publish, _mock_flag):
+ # Nothing reached GitHub and republishing the same skill fails the same way, so a 502 would
+ # tell the publisher to retry an upstream request that was never the problem.
+ mock_publish.side_effect = CommunitySkillPublishValidationError("that slug is reserved")
+ self.create_skill(name="make-pr")
+
+ response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["detail"] == "that slug is reserved"
+
+ @patch(COMMUNITY_FLAG, return_value=True)
+ @patch("products.skills.backend.api.skills.publish_skill_to_community")
+ def test_publish_to_community_github_error_returns_502(self, mock_publish, _mock_flag):
+ mock_publish.side_effect = CommunitySkillPublishError("github exploded")
+ self.create_skill(name="make-pr")
+
+ response = self.client.post(self._url("name/make-pr/publish-community"), data={}, format="json")
+
+ assert response.status_code == status.HTTP_502_BAD_GATEWAY
+
# llm_skill is its own access-control resource (see ACCESS_CONTROL_RESOURCES in
# posthog/rbac/user_access_control.py) - same as TestSkillMarketplaceRBAC in
diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.ts
index 34e4473e476b..eb19c3f6fc24 100644
--- a/products/skills/frontend/generated/api.schemas.ts
+++ b/products/skills/frontend/generated/api.schemas.ts
@@ -644,6 +644,35 @@ export interface LLMSkillFileApi {
content_type?: string
}
+export interface LLMSkillPublishToCommunityApi {
+ /**
+ * Human-friendly display name for the community listing. Defaults to a title-cased skill slug. Must be a single line: it is used as the pull request title and commit message.
+ * @maxLength 64
+ * @pattern ^[^\u0000-\u001f\u007f]*$
+ */
+ display_name?: string
+ /**
+ * Tags used for filtering and discovery in the marketplace, e.g. ['web-analytics', 'triage'].
+ * @items.maxLength 64
+ */
+ tags?: string[]
+ /**
+ * The publisher's GitHub username, used for public attribution on the listing and PR. Optional, and self-reported: it is not verified against the publisher's PostHog account.
+ * @maxLength 39
+ * @pattern ^$|^[a-zA-Z0-9](?:-?[a-zA-Z0-9]){0,38}$
+ */
+ author_handle?: string
+}
+
+export interface CommunitySkillPublishResultApi {
+ /** URL of the pull request opened in the community-skills repo for maintainer review. */
+ pr_url: string
+ /** Number of the opened pull request. */
+ pr_number: number
+ /** Name of the branch created in the community-skills repo. */
+ branch: string
+}
+
export interface LLMSkillVersionSummaryApi {
readonly id: string
readonly version: number
diff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.ts
index b204d39d6ed4..6354c8ab3f33 100644
--- a/products/skills/frontend/generated/api.ts
+++ b/products/skills/frontend/generated/api.ts
@@ -11,6 +11,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
CommunitySkillApi,
CommunitySkillInstallApi,
+ CommunitySkillPublishResultApi,
CommunitySkillVoteResponseApi,
CommunitySkillsListParams,
LLMSkillApi,
@@ -22,6 +23,7 @@ import type {
LLMSkillImportApi,
LLMSkillMarketplaceCommandApi,
LLMSkillMarketplaceIssueApi,
+ LLMSkillPublishToCommunityApi,
LLMSkillResolveResponseApi,
LlmSkillsListParams,
LlmSkillsNameExportRetrieveParams,
@@ -450,6 +452,24 @@ export const llmSkillsNameFilesDestroy = async (
})
}
+export const getLlmSkillsNamePublishCommunityCreateUrl = (projectId: string, skillName: string) => {
+ return `/api/projects/${projectId}/llm_skills/name/${skillName}/publish-community/`
+}
+
+export const llmSkillsNamePublishCommunityCreate = async (
+ projectId: string,
+ skillName: string,
+ lLMSkillPublishToCommunityApi?: LLMSkillPublishToCommunityApi,
+ options?: RequestInit
+): Promise<CommunitySkillPublishResultApi> => {
+ return apiMutator<CommunitySkillPublishResultApi>(getLlmSkillsNamePublishCommunityCreateUrl(projectId, skillName), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(lLMSkillPublishToCommunityApi),
+ })
+}
+
export const getLlmSkillsResolveNameRetrieveUrl = (
projectId: string,
skillName: string,
diff --git a/products/skills/frontend/generated/api.zod.ts b/products/skills/frontend/generated/api.zod.ts
index 92b5fe3596c2..4e43aff5b237 100644
--- a/products/skills/frontend/generated/api.zod.ts
+++ b/products/skills/frontend/generated/api.zod.ts
@@ -283,3 +283,37 @@ export const LlmSkillsNameFilesRenameCreateBody = /* @__PURE__ */ zod.object({
'Latest version you are editing from. If provided, the request fails with 409 when another write has landed in the meantime.'
),
})
+
+export const llmSkillsNamePublishCommunityCreateBodyDisplayNameMax = 64
+
+export const llmSkillsNamePublishCommunityCreateBodyDisplayNameRegExp = new RegExp('^[^\\u0000-\\u001f\\u007f]\*$')
+export const llmSkillsNamePublishCommunityCreateBodyTagsItemMax = 64
+
+export const llmSkillsNamePublishCommunityCreateBodyAuthorHandleMax = 39
+
+export const llmSkillsNamePublishCommunityCreateBodyAuthorHandleRegExp = new RegExp(
+ '^$|^[a-zA-Z0-9](?:-?[a-zA-Z0-9]){0,38}$'
+)
+
+export const LlmSkillsNamePublishCommunityCreateBody = /* @__PURE__ */ zod.object({
+ display_name: zod
+ .string()
+ .max(llmSkillsNamePublishCommunityCreateBodyDisplayNameMax)
+ .regex(llmSkillsNamePublishCommunityCreateBodyDisplayNameRegExp)
+ .optional()
+ .describe(
+ 'Human-friendly display name for the community listing. Defaults to a title-cased skill slug. Must be a single line: it is used as the pull request title and commit message.'
+ ),
+ tags: zod
+ .array(zod.string().max(llmSkillsNamePublishCommunityCreateBodyTagsItemMax))
+ .optional()
+ .describe("Tags used for filtering and discovery in the marketplace, e.g. ['web-analytics', 'triage']."),
+ author_handle: zod
+ .string()
+ .max(llmSkillsNamePublishCommunityCreateBodyAuthorHandleMax)
+ .regex(llmSkillsNamePublishCommunityCreateBodyAuthorHandleRegExp)
+ .optional()
+ .describe(
+ "The publisher's GitHub username, used for public attribution on the listing and PR. Optional, and self-reported: it is not verified against the publisher's PostHog account."
+ ),
+})
diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yaml
index dfc5bb4798d0..5adc6a02c72d 100644
--- a/products/skills/mcp/tools.yaml
+++ b/products/skills/mcp/tools.yaml
@@ -30,6 +30,9 @@ tools:
llm-skills-name-export-retrieve:
operation: llm_skills_name_export_retrieve
enabled: false
+ llm-skills-name-publish-community-create:
+ operation: llm_skills_name_publish_community_create
+ enabled: false
skill-archive:
operation: llm_skills_name_archive_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8ec6fc6373c1..a1012b9e6d80 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -17898,6 +17898,15 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface CommunitySkillPublishResult {
+ /** URL of the pull request opened in the community-skills repo for maintainer review. */
+ pr_url: string;
+ /** Number of the opened pull request. */
+ pr_number: number;
+ /** Name of the branch created in the community-skills repo. */
+ branch: string;
+ }
+
export interface CommunitySkillVoteResponse {
/** Total upvotes after applying the toggle. */
vote_count: number;
@@ -44614,6 +44623,26 @@ export namespace Schemas {
rotate?: boolean;
}
+ export interface LLMSkillPublishToCommunity {
+ /**
+ * Human-friendly display name for the community listing. Defaults to a title-cased skill slug. Must be a single line: it is used as the pull request title and commit message.
+ * @maxLength 64
+ * @pattern ^[^\u0000-\u001f\u007f]*$
+ */
+ display_name?: string;
+ /**
+ * Tags used for filtering and discovery in the marketplace, e.g. ['web-analytics', 'triage'].
+ * @items.maxLength 64
+ */
+ tags?: string[];
+ /**
+ * The publisher's GitHub username, used for public attribution on the listing and PR. Optional, and self-reported: it is not verified against the publisher's PostHog account.
+ * @maxLength 39
+ * @pattern ^$|^[a-zA-Z0-9](?:-?[a-zA-Z0-9]){0,38}$
+ */
+ author_handle?: string;
+ }
+
export interface LLMSkillVersionSummary {
readonly id: string;
readonly version: number;
@@ -80986,6 +81015,14 @@ export namespace Schemas {
installation_id: string;
}
+ export interface UserGithubLogin {
+ /**
+ * The user's resolved GitHub login, or null when no GitHub identity is linked.
+ * @nullable
+ */
+ github_login: string | null;
+ }
+
/**
* * `transcript` - transcript
* * `summary` - summary