:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(skills): add optional owners on skills for foolproof scout reviewer routing (#73007)
Andrew Maguire0482e4fab9e1
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 7bc48f03f0cd..353d128cf5de 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -198,6 +198,7 @@ rules:|LLMPromptLabel|LLMProviderKey|LLMSkill+ |LLMSkillOwner|LLMTraceSummary|ManagedWarehouseBackfillPartition|MarketingAnalyticsGoalMapping@@ -511,6 +512,7 @@ rules:|LLMPromptLabel|LLMProviderKey|LLMSkill+ |LLMSkillOwner|LLMTraceSummary|ManagedWarehouseBackfillPartition|MarketingAnalyticsGoalMappingdiff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.pyindex 7e57418baeb9..1a86ffa5e084 100644--- a/products/signals/backend/artefact_schemas.py+++ b/products/signals/backend/artefact_schemas.py@@ -190,6 +190,15 @@ class SuggestedReviewerEntry(BaseModel):default=None,description="Why this reviewer was chosen — the evidence behind the routing (e.g. recent author on the affected surface, human correction precedent).",)+ is_skill_owner: bool = Field(+ default=False,+ description=(+ "True when this entry was injected by the scout owner guardrail (an editor-controlled "+ "`LLMSkillOwner`), rather than derived from commit authorship. Such entries route the "+ "report but must never select the autostart task identity — otherwise a skill editor "+ "could name a privileged teammate as owner and have an implementation agent run as them."+ ),+ )@field_validator("github_login")@classmethoddiff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.pyindex f2e2ef564319..7b25efa7a4f2 100644--- a/products/signals/backend/auto_start.py+++ b/products/signals/backend/auto_start.py@@ -54,6 +54,9 @@ class ReviewerContent(TypedDict):github_name: str | Nonerelevant_commits: list[dict]reason: str | None+ # True for entries injected by the scout owner guardrail (editor-controlled `LLMSkillOwner`).+ # These route the report but are never eligible to select the autostart task identity.+ is_skill_owner: bool_PRIORITY_RANK: dict[Priority, int] = {@@ -294,19 +297,28 @@ def _resolve_autostart_assignee(reviewer at all — it runs as the triggering user (see `_resolve_triggering_user`), so a usercan't name a colleague and have the agent run under that colleague's identity.+ Owner-provenance entries (``is_skill_owner``) are excluded from identity selection: the scout+ owner guardrail injects them from an editor-controlled `LLMSkillOwner`, so treating them as a+ trusted commit-authorship signal would let a skill editor name a privileged teammate as owner+ and have the implementation agent mint an OAuth session under that teammate. They still route+ the report (they remain in the artefact); they just can't be the runner.+Walks *reviewers_content* in order (most relevant first). A reviewer's effective threshold istheir personal autonomy setting when present, otherwise the team default (itself "allpriorities"/P4 when the team has no config row). A lower rank means higher priority. Returnsthe first matching ``User``, or ``None`` if no reviewer maps to an org member."""+ # Owner-injected entries never select the task identity (see docstring). Filter before resolving+ # so their logins aren't even looked up as candidates.+ identity_candidates = [r for r in reviewers_content if not r.get("is_skill_owner")]login_to_user = resolve_org_github_login_to_users(- team_id, (str(r["github_login"]) for r in reviewers_content if r.get("github_login"))+ team_id, (str(r["github_login"]) for r in identity_candidates if r.get("github_login")))report_rank = _priority_rank(report_priority)# Map reviewer github logins to org members, preserving reviewer order (most relevant first).candidate_users: list[User] = []- for reviewer in reviewers_content:+ for reviewer in identity_candidates:login = reviewer.get("github_login")if not login:continue@@ -583,6 +595,7 @@ async def _latest_reviewers_content(report_id: str) -> tuple[list[ReviewerContengithub_name=entry.get("github_name"),relevant_commits=entry.get("relevant_commits") or [],reason=entry.get("reason"),+ is_skill_owner=bool(entry.get("is_skill_owner")),))return reviewers, editor_user_iddiff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 4f58750899cc..d380bc23efca 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -59,24 +59,31 @@ it is exercised via the `run_signals_scout` management command (see `../managemefeedback leaves the customer's project, so it must carry the pattern, never the project'sdata (no PII, values, URLs, numbers, or custom event/property names); tool/harness frictionstill routes via the shared operational-friction section. A _report-channel_ custom scout's run identity also- carries a **skill authors** line (`LoadedSkill.authors`, rendered by `_skill_authors_line`):- creator + recent editors resolved server-side from the skill's version rows, which the- escalation guidance points `suggested_reviewers` at (creator first, via `scout-members-list`) —- without it a scout only sees its pinned version's `created_by`, i.e. the last editor,- and would route ownership to whoever most recently touched the skill. The line is gated on- the report channel: a signal-channel scout has no `suggested_reviewers` field, so member- names/emails (PII) must not reach its prompt.+ carries a **skill owners** line (`LoadedSkill.authors`, rendered by `_skill_authors_line`):+ the skill's explicit owners when set (else the version-history creator + recent editors,+ resolved server-side), which the escalation guidance points `suggested_reviewers` at (owner+ first, via `scout-members-list`) — without it a scout only sees its pinned version's+ `created_by`, i.e. the last editor, and would route ownership to whoever most recently touched+ the skill. This prompt line is advisory; the deterministic backstop is the owner guardrail in+ `tools/report.py._build_suggested_reviewers`, which places the skill's owners ahead of the+ model's picks regardless of what it wrote. The line is gated on the report channel: a+ signal-channel scout has no `suggested_reviewers` field, so member names/emails (PII) must not+ reach its prompt.- `skill_loader.py`Resolves `signals-scout-*` skills from the team's `LLMSkill` rows. Defines`SIGNALS_SCOUT_SKILL_PREFIX` and `LoadedSkill` (body + version + allowed_tools + origin + authors), plus`REPORT_CHANNEL_TOOLS` / `skill_uses_report_channel` — the shared report-channel opt-inpredicate the runner (scope posture) and prompt builder (persona fork) both resolve from.- `resolve_skill_authors` aggregates distinct non-null `created_by` across a skill's version rows- (creator = earliest first-authored, then editors by last-edit recency, capped), restricted to- `team.all_users_with_access()` so a revoked author's profile stops flowing into a privileged- prompt. Resolution is opt-in via `load_skill_for_run(..., include_authors=True)` — only the- runner's prompt-building path pays for it; the report-authorization gate in `views.py` loads- the skill per report write just to check `allowed_tools` and skips it.+ `resolve_skill_authors` prefers the skill's **explicit owner set** (`LLMSkillOwner`, keyed on the+ logical `(team, name)` so it never drifts when the body is edited) — returned as `role="owner"`,+ seed-creator first. Only when a skill has no explicit owners does it fall back to reconstructing+ authorship from version rows (distinct non-null `created_by`: creator = earliest first-authored,+ then editors by last-edit recency, capped). Both paths are restricted to+ `team.all_users_with_access()` so a revoked user's profile stops flowing into a privileged prompt.+ `resolve_skill_owner_user_uuids` exposes the owner set (seed-creator first) to the report tools'+ reviewer guardrail. Author resolution is opt-in via `load_skill_for_run(..., include_authors=True)`+ — only the runner's prompt-building path pays for it; the report-authorization gate in `views.py`+ loads the skill per report write just to check `allowed_tools` and skips it.- `lazy_seed.py`Canonical skill sync. Reads `products/signals/skills/signals-scout-*/` from disk andreconciles them against the team's `LLMSkill` rows: creates missing rows, updatesdiff --git a/products/signals/backend/scout_harness/prompt.py b/products/signals/backend/scout_harness/prompt.pyindex bafd2e0e829c..b77789ce9516 100644--- a/products/signals/backend/scout_harness/prompt.py+++ b/products/signals/backend/scout_harness/prompt.py@@ -449,16 +449,26 @@ def _render_tail(sections: list[str], *, schema_json: str) -> str:def _skill_authors_line(authors: list[SkillAuthor]) -> str:- """Run-identity line naming the custom skill's creator and recent editors, or empty.-- Version rows only record who published each version, so without this line a scout that- reads its own (latest) version via `skill-get` sees the last editor's name and would route- ownership there — e.g. a bulk cleanup pass over every custom scout makes the cleaner look- like the owner of all of them. Resolving authorship server-side also spares the scout a- tool call per version; a long-lived skill can carry hundreds.+ """Run-identity line naming the humans who own the skill, or empty.++ Prefers the explicit owner set (role="owner"), which is stable across edits. Only when a skill+ has no explicit owners does this fall back to the version-history reconstruction (creator ++ recent editors) — there, version rows record only who published each version, so without this+ line a scout reading its own (latest) version via `skill-get` sees the last editor's name and+ would route ownership there (a bulk cleanup pass over every custom scout would make the cleaner+ look like the owner of all of them). Resolving server-side also spares the scout a tool call per+ version; a long-lived skill can carry hundreds."""if not authors:return ""+ owners = [a for a in authors if a.role == "owner"]+ if owners:+ owned = ", ".join(f"{a.name} ({a.email})" for a in owners)+ return (+ f"\n- **skill owners**: {owned} — the humans who own your skill body. "+ "When a report needs someone who owns this scout (a self-improvement report especially), "+ "route to them — unless your skill body defines its own reviewer routing, which takes precedence."+ )parts = []creator = next((a for a in authors if a.role == "creator"), None)if creator is not None:diff --git a/products/signals/backend/scout_harness/skill_loader.py b/products/signals/backend/scout_harness/skill_loader.pyindex dd36b57741bc..9c6cb1cf9860 100644--- a/products/signals/backend/scout_harness/skill_loader.py+++ b/products/signals/backend/scout_harness/skill_loader.py@@ -8,7 +8,7 @@ from django.db.models import Max, Minfrom posthog.models.team.team import Team-from products.skills.backend.models.skills import LLMSkill, LLMSkillFile+from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, LLMSkillOwner# Naming contract for skills that steer a Signals-agent run.SIGNALS_SCOUT_SKILL_PREFIX = "signals-scout-"@@ -43,11 +43,16 @@ MAX_SKILL_EDITORS_IN_PROMPT = 5@dataclass(frozen=True)class SkillAuthor:- """One human who published at least one version of the skill, for reviewer routing."""+ """One human tied to the skill for reviewer routing.++ `role="owner"` is the explicit, durable owner set (from `LLMSkillOwner`) and takes precedence.+ `creator`/`editor` are the legacy reconstruction from version-row authorship, used only when a+ skill has no explicit owners. For an owner, `last_authored_at` is the owner-since date.+ """name: stremail: str- role: Literal["creator", "editor"]+ role: Literal["owner", "creator", "editor"]last_authored_at: datetime@@ -90,19 +95,87 @@ def is_signals_scout_skill(skill: LLMSkill) -> bool:return skill.name.startswith(SIGNALS_SCOUT_SKILL_PREFIX)+def resolve_skill_owner_user_uuids(team: Team, skill_name: str) -> list[str]:+ """Owner user UUIDs for a logical skill, seed-creator first — for the reviewer guardrail.++ Restricted to `team.all_users_with_access()` (same privacy boundary as the author scan): an+ owner who lost access can't be routed a review and their identity shouldn't leak downstream.+ """+ return [+ str(uuid)+ # canonical=True → exact environment team, matching how LLMSkill is scoped (see LLMSkillOwner).+ for uuid in LLMSkillOwner.objects.for_team(team.id, canonical=True)+ .filter(skill_name=skill_name, user__in=team.all_users_with_access())+ .order_by("created_at", "id")+ .values_list("user__uuid", flat=True)+ ]+++def _skill_has_owner_rows(team: Team, skill_name: str) -> bool:+ """Whether the logical skill has any owner rows at all — including owners who lost access.++ Distinguishes "no explicit owners, use version history" from "owned, but currently unroutable",+ so the latter never silently drifts back to the version-history heuristic.+ """+ return LLMSkillOwner.objects.for_team(team.id, canonical=True).filter(skill_name=skill_name).exists()+++def _resolve_owner_authors(team: Team, skill_name: str) -> list[SkillAuthor]:+ """The explicit owner set as `SkillAuthor`s (role="owner"), seed-creator first.++ Same membership filter as the legacy scan. Empty when the skill has no explicit owners, which+ is the signal to fall back to version-history reconstruction.+ """+ rows = (+ # canonical=True → exact environment team, matching how LLMSkill is scoped (see LLMSkillOwner).+ LLMSkillOwner.objects.for_team(team.id, canonical=True)+ .filter(skill_name=skill_name, user__in=team.all_users_with_access())+ .values("user__first_name", "user__last_name", "user__email", "created_at")+ .order_by("created_at", "id")+ )+ authors: list[SkillAuthor] = []+ for row in rows:+ # Collapse whitespace so a multi-line display name can't break the prompt's one-line list item.+ name = " ".join(f"{row['user__first_name']} {row['user__last_name']}".split())+ authors.append(+ SkillAuthor(+ name=name or row["user__email"],+ email=row["user__email"],+ role="owner",+ last_authored_at=row["created_at"],+ )+ )+ return authors++def resolve_skill_authors(team: Team, skill_name: str) -> list[SkillAuthor]:- """Distinct humans across the skill's version rows: creator first, then editors by recency.+ """Humans to route reviews to. Prefers the explicit owner set; falls back to version history.++ When the skill carries explicit owners (`LLMSkillOwner`), they win — ownership is keyed on the+ logical skill and never drifts when the body is edited, so it's the authoritative answer to+ "who owns this scout?". Only when there are no owners does this reconstruct authorship from+ version rows (creator first, then editors by recency), the best-effort legacy heuristic that a+ bulk edit could misattribute.- One indexed aggregate over all version rows for `(team, name)` — versions are capped at- `MAX_SKILL_VERSION`, so this stays cheap regardless of edit churn. Rows with a null- `created_by` (system-seeded versions, deleted users) carry no routable identity and are- skipped; a skill with only such rows resolves to no authors.+ Version-history path: one indexed aggregate over all version rows for `(team, name)` — capped at+ `MAX_SKILL_VERSION`, so cheap regardless of churn. Rows with a null `created_by` (system-seeded+ versions, deleted users) carry no routable identity and are skipped.- Authors are restricted to `team.all_users_with_access()` — the same boundary the+ Both paths restrict to `team.all_users_with_access()` — the same boundary the`scout-members-list` reviewer roster uses. A former member's profile (notably theself-editable display name) must not keep flowing into a privileged prompt after their- access is revoked, and an unroutable author would only waste an editor slot anyway.+ access is revoked, and an unroutable author would only waste a slot anyway."""+ owners = _resolve_owner_authors(team, skill_name)+ if owners:+ return owners+ # A skill with owner rows is authoritatively owned — even if every owner has since lost access.+ # Falling back to version-history reconstruction here would re-introduce exactly the editor drift+ # this primitive exists to prevent, so an owned-but-currently-unroutable skill gets no reviewer+ # rather than a guessed one. Only a skill with *no* owner rows uses the legacy heuristic.+ if _skill_has_owner_rows(team, skill_name):+ return []+rows = (LLMSkill.objects.filter(team=team,diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex a378ed2b0a53..33b77148be6f 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -47,6 +47,7 @@ from products.signals.backend.models import ArtefactAttribution, SignalReport, Sfrom products.signals.backend.report_generation.resolve_reviewers import get_org_member_github_logins_by_user_uuidfrom products.signals.backend.report_generation.select_repo import RepoSelectionResultfrom products.signals.backend.scout_harness.prompt import SELF_IMPROVEMENT_REPORT_TITLE_PREFIX+from products.signals.backend.scout_harness.skill_loader import resolve_skill_owner_user_uuidsfrom products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_deliveryfrom products.signals.backend.scout_harness.tools.emit import (SCOUT_SIGNAL_WEIGHT,@@ -245,55 +246,138 @@ def _build_priority(priority: str | None, explanation: str | None) -> PriorityAsreturn PriorityAssessment(priority=priority_level, explanation=explanation)-def _build_suggested_reviewers(team_id: int, reviewers: list[ReviewerInput] | None) -> SuggestedReviewers | None:- """Resolve scout-supplied reviewer entries to a canonical, lowercased, deduped `suggested_reviewers`- artefact (GitHub logins), or None to omit it.-- Each entry identifies a reviewer by `github_login`, `user_uuid`, or both — mirroring the inbox- `SuggestedReviewerEntryWriteSerializer`. A `user_uuid` is resolved to the org member's linked GitHub- login (and wins over a supplied `github_login` when both are given), so a scout that only knows a- PostHog user can still route a report. Resolution is fail-loud: a `user_uuid` that isn't an org- member of this team with a linked GitHub identity raises `InvalidScoutReportError` rather than- silently dropping the reviewer (matching the inbox artefact-write endpoint), since a quietly-lost- reviewer is what leaves a report routed to no one. Entries are deduped by resolved login; an- all-empty list yields None. Does a DB read (UUID resolution), so callers on the async path must- bridge it off the event loop."""- if not reviewers:- return None-- # Cap the input list *before* resolving — otherwise a malformed call with hundreds of uuid entries- # would fire one unbounded `IN` query (parameter/timeout risk) just to be rejected afterwards. The- # DRF ListField enforces the same bound at the API boundary; this guards the direct callers too.- if len(reviewers) > MAX_SUGGESTED_REVIEWERS:- raise InvalidScoutReportError(f"at most {MAX_SUGGESTED_REVIEWERS} suggested reviewers, got {len(reviewers)}")-- for entry in reviewers:- has_login = bool(entry.github_login and entry.github_login.strip())- if not has_login and not entry.user_uuid:- raise InvalidScoutReportError("each suggested reviewer needs a github_login or a user_uuid")-- uuids_to_resolve = [str(entry.user_uuid) for entry in reviewers if entry.user_uuid]- uuid_to_login = get_org_member_github_logins_by_user_uuid(team_id, uuids_to_resolve) if uuids_to_resolve else {}+def _owner_reviewer_entries(team: Team, skill_name: str) -> list[SuggestedReviewerEntry]:+ """The running scout's owners as reviewer entries (GitHub logins), seed-creator first.+ This is the deterministic half of the guardrail: owners come from `LLMSkillOwner`, not the model's+ prose, so ownership is always represented regardless of what the LLM picked. Owners with no linked+ GitHub identity are skipped — a `suggested_reviewers` artefact is GitHub-login-keyed, so there's no+ one to route to (the prompt still names them by email)."""+ owner_uuids = resolve_skill_owner_user_uuids(team, skill_name)+ if not owner_uuids:+ return []+ uuid_to_login = get_org_member_github_logins_by_user_uuid(team.id, owner_uuids)entries: list[SuggestedReviewerEntry] = []seen: set[str] = set()- for entry in reviewers:- if entry.user_uuid:- resolved = uuid_to_login.get(str(entry.user_uuid))- if not resolved:- raise InvalidScoutReportError(- f"user_uuid '{entry.user_uuid}' is not an org member of this team with a linked GitHub identity"- )- login = resolved.lower()- else:- login = (entry.github_login or "").strip().lower()- if not login:- raise InvalidScoutReportError("github_login resolved to empty after normalization")- if login in seen:+ for owner_uuid in owner_uuids:+ login = uuid_to_login.get(owner_uuid) # already lowercased by the resolver+ if not login or login in seen:continueseen.add(login)- reason = entry.reason.strip() if entry.reason and entry.reason.strip() else None- entries.append(SuggestedReviewerEntry(github_login=login, reason=reason))+ # `is_skill_owner=True` is the provenance flag autostart uses to keep these editor-controlled+ # entries out of task-identity selection — they route the report but never mint a session.+ entries.append(SuggestedReviewerEntry(github_login=login, reason="skill owner", is_skill_owner=True))+ return entries+++def _skill_authored_report(team: Team, skill_name: str, report_id: str) -> bool:+ """Whether any run of this (team, skill) emitted the report. Reports carry no skill column — the+ run-side `emitted_report_ids` tally is the authorship record, so the check is a containment query+ across the skill's runs. `for_team` (not the ambient-context manager) so it works on the async+ harness path too, where no request scope is set and the fail-closed manager would raise."""+ return (+ SignalScoutRun.objects.for_team(team.id)+ .filter(skill_name=skill_name, emitted_report_ids__contains=report_id)+ .exists()+ )+++def _build_suggested_reviewers(+ team: Team,+ reviewers: list[ReviewerInput] | None,+ *,+ skill_name: str | None = None,+ enforce_owners: bool = False,+) -> SuggestedReviewers | None:+ """Resolve reviewer entries to a canonical, lowercased, deduped `suggested_reviewers` artefact+ (GitHub logins), or None to omit it.++ Each scout-supplied entry identifies a reviewer by `github_login`, `user_uuid`, or both — mirroring+ the inbox `SuggestedReviewerEntryWriteSerializer`. A `user_uuid` is resolved to the org member's+ linked GitHub login (and wins over a supplied `github_login` when both are given), so a scout that+ only knows a PostHog user can still route a report. Resolution is fail-loud: a `user_uuid` that+ isn't an org member of this team with a linked GitHub identity raises `InvalidScoutReportError`+ rather than silently dropping the reviewer, since a quietly-lost reviewer is what leaves a report+ routed to no one.++ **Owner guardrail:** with `enforce_owners` and a `skill_name`, the running scout's owners+ (`LLMSkillOwner`) are resolved deterministically and placed *first*, ahead of the model's picks —+ so a report about a scout always routes to whoever owns it, even if the model picked the wrong+ person or none at all. This is a code rule the LLM can't prose past; it replaces the old reliance+ on the model reading a prompt line correctly. Owners and the model's picks are then deduped by+ login and capped, owners never dropped; an owner the scout also names keeps owner provenance+ (`is_skill_owner=True`), since a steerable scout repeating an owner is not independent evidence.++ Does DB reads (UUID + owner resolution), so callers on the async path must bridge it off the event+ loop."""+ owner_entries = _owner_reviewer_entries(team, skill_name) if enforce_owners and skill_name else []++ if not reviewers and not owner_entries:+ return None++ scout_entries: list[SuggestedReviewerEntry] = []+ if reviewers:+ # Cap the input list *before* resolving — otherwise a malformed call with hundreds of uuid+ # entries would fire one unbounded `IN` query (parameter/timeout risk) just to be rejected+ # afterwards. The DRF ListField enforces the same bound at the API boundary; this guards the+ # direct callers too.+ if len(reviewers) > MAX_SUGGESTED_REVIEWERS:+ raise InvalidScoutReportError(+ f"at most {MAX_SUGGESTED_REVIEWERS} suggested reviewers, got {len(reviewers)}"+ )++ for entry in reviewers:+ has_login = bool(entry.github_login and entry.github_login.strip())+ if not has_login and not entry.user_uuid:+ raise InvalidScoutReportError("each suggested reviewer needs a github_login or a user_uuid")++ uuids_to_resolve = [str(entry.user_uuid) for entry in reviewers if entry.user_uuid]+ uuid_to_login = get_org_member_github_logins_by_user_uuid(team.id, uuids_to_resolve) if uuids_to_resolve else {}++ for entry in reviewers:+ if entry.user_uuid:+ resolved = uuid_to_login.get(str(entry.user_uuid))+ if not resolved:+ raise InvalidScoutReportError(+ f"user_uuid '{entry.user_uuid}' is not an org member of this team with a linked GitHub identity"+ )+ login = resolved.lower()+ else:+ login = (entry.github_login or "").strip().lower()+ if not login:+ raise InvalidScoutReportError("github_login resolved to empty after normalization")+ reason = entry.reason.strip() if entry.reason and entry.reason.strip() else None+ scout_entries.append(SuggestedReviewerEntry(github_login=login, reason=reason))++ # Owners first (guardrail), then the scout's picks; dedupe by login so an owner the scout also+ # named isn't listed twice, and cap — owners lead, so they're never the ones truncated. An owner+ # the scout *also* picked keeps `is_skill_owner=True` (only the scout's reason merges in): the+ # skill body is the run's steering layer, so a scout repeating an owner's login is not+ # independent commit-authorship evidence — clearing the flag would let a skill editor name a+ # privileged member as owner, steer the scout to repeat that login, and mint the autostart+ # session as them. The invariant is that an owner row never adds identity eligibility; an+ # owner-picked reviewer still routes the report, and autostart falls to the next non-owner+ # reviewer or the team fallback.+ entries_by_login: dict[str, SuggestedReviewerEntry] = {e.github_login: e for e in owner_entries}+ for scout_entry in scout_entries:+ existing = entries_by_login.get(scout_entry.github_login)+ if existing is None:+ entries_by_login[scout_entry.github_login] = scout_entry+ elif existing.is_skill_owner and scout_entry.reason:+ entries_by_login[scout_entry.github_login] = SuggestedReviewerEntry(+ github_login=scout_entry.github_login,+ reason=scout_entry.reason,+ is_skill_owner=True,+ )+ merged = list(entries_by_login.values())+ entries = merged[:MAX_SUGGESTED_REVIEWERS]+ # A skill can have more routable owners than the reviewer cap (MAX_SKILL_OWNERS exceeds it), and+ # owner entries never carry PR intent — so an owner-only capped list would silently discard the+ # scout's explicit picks and with them the `_wants_repo_selection` signal. Reserve the last slot+ # for the first non-owner pick so routing keeps owners first but intent survives the cap.+ non_owner_picks = [e for e in merged if not e.is_skill_owner]+ if non_owner_picks and all(e.is_skill_owner for e in entries):+ entries = [*merged[: MAX_SUGGESTED_REVIEWERS - 1], non_owner_picks[0]]if not entries:return None@@ -306,8 +390,15 @@ def _wants_repo_selection("""Whether to run repo selection at all. Resolve a repo only when the scout signalled PR intent —either an explicit `repository`, or the priority + reviewers an autostart needs. An informationalreport that supplies none of these skips selection entirely, so it never pays for the (free-form)- selection sandbox just to surface in the inbox."""- return repository is not None or (priority is not None and reviewers is not None)+ selection sandbox just to surface in the inbox.++ Owner-guardrail entries don't count as PR intent: they're injected on every emit for routing, so+ counting them would run free-form repo selection — and later autostart under the team fallback+ runner — for a prioritized report whose scout supplied neither a repo nor a reviewer."""+ if repository is not None:+ return True+ scout_picked_reviewer = reviewers is not None and any(not entry.is_skill_owner for entry in reviewers.root)+ return priority is not None and scout_picked_reviewerdef _repo_request_section(title: str, summary: str, evidence: list[ReportEvidence]) -> str:@@ -715,7 +806,7 @@ async def emit_report(# Resolves user_uuid → github_login (a DB read), so bridge it off the event loop. Runs before the# safety judge so an unresolvable reviewer fails fast rather than after paying for the LLM call.reviewers = await database_sync_to_async(_build_suggested_reviewers, thread_sensitive=False)(- team.id, suggested_reviewers+ team, suggested_reviewers, skill_name=run.skill_name, enforce_owners=True)preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)@@ -823,7 +914,7 @@ def emit_report_sync(explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed)priority_assessment = _build_priority(priority, priority_explanation)- reviewers = _build_suggested_reviewers(team.id, suggested_reviewers)+ reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name, enforce_owners=True)preflight = _preflight_emit_gates(team, run)if preflight is not None:@@ -923,7 +1014,16 @@ def _do_edit_report(# reject caller input — an unresolvable user_uuid raises, which the view turns into a 400. Doing it# first means a combined edit (title/summary + a bad reviewer) fails before the content write# commits, rather than leaving the report partially mutated behind a failed call.- reviewers = _build_suggested_reviewers(team.id, suggested_reviewers)+ #+ # Enforce owners only when this edit actually sets reviewers — otherwise a title-only edit would+ # inject owners over a routing a human may have already chosen — and only on a report this skill+ # authored: `edit_report` can target any inbox report, and the guardrail exists to make a scout's+ # own reports route to its owners, not to stamp the editing skill's owners onto unrelated reports.+ # When no reviewers are supplied, this resolves to None and existing reviewers are left untouched.+ enforce_owners = bool(suggested_reviewers) and _skill_authored_report(team, run.skill_name, report_id)+ reviewers = _build_suggested_reviewers(+ team, suggested_reviewers, skill_name=run.skill_name, enforce_owners=enforce_owners+ )updated_fields: list[str] = []if title is not None or summary is not None:diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.pyindex 916d2ecf6a11..935ea6d580aa 100644--- a/products/signals/backend/scout_report/persistence.py+++ b/products/signals/backend/scout_report/persistence.py@@ -381,6 +381,11 @@ def _merge_forward_reviewer_evidence(*, report_id: str, suggested_reviewers: Sug"github_name": entry.github_name if entry.github_name is not None else prior.get("github_name"),"relevant_commits": entry.relevant_commits or prior.get("relevant_commits") or [],"reason": entry.reason if entry.reason is not None else prior.get("reason"),+ # Owner provenance is recomputed from the live `LLMSkillOwner` set on every+ # reviewers-setting edit, so the fresh entry's flag wins — OR-ing in the prior value+ # would keep a former owner, re-added as a normal reviewer, excluded from autostart+ # identity selection on stale evidence.+ "is_skill_owner": entry.is_skill_owner,}try:merged.append(SuggestedReviewerEntry.model_validate(candidate))diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.pyindex fa454073b9f4..68cbc28b9843 100644--- a/products/signals/backend/temporal/agentic/report.py+++ b/products/signals/backend/temporal/agentic/report.py@@ -226,6 +226,8 @@ def _build_reviewers_content(github_name=reviewer.name,relevant_commits=[dict(commit.model_dump()) for commit in reviewer.commits],reason=None,+ # Pipeline reviewers are commit-authorship-derived, never owner-injected.+ is_skill_owner=False,))return reviewers_contentdiff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.pyindex f50515d40ea2..4998562f2ecd 100644--- a/products/signals/backend/test/test_auto_start.py+++ b/products/signals/backend/test/test_auto_start.py@@ -62,8 +62,10 @@ def _create_org_member_with_github(email: str, organization: Organization, loginreturn user-def _reviewer(login: str) -> ReviewerContent:- return ReviewerContent(github_login=login, github_name=None, relevant_commits=[], reason=None)+def _reviewer(login: str, *, is_skill_owner: bool = False) -> ReviewerContent:+ return ReviewerContent(+ github_login=login, github_name=None, relevant_commits=[], reason=None, is_skill_owner=is_skill_owner+ )@pytest.mark.django_db@@ -100,6 +102,39 @@ def test_resolve_autostart_assignee(assert assignee is None+def test_resolve_autostart_assignee_never_runs_as_a_skill_owner(organization, team):+ # The owner guardrail places editor-controlled `LLMSkillOwner`s first in suggested_reviewers, but+ # the autostart path mints a full-scope OAuth token as the chosen reviewer. Selecting an owner as+ # that identity would let a skill editor name a privileged teammate as owner and have the agent run+ # as them, so owner-provenance entries must be excluded from identity selection.+ # Both resolve to real org members with linked GitHub — so "ownercat" being skipped is the guard+ # working, not just an unresolvable login.+ _create_org_member_with_github("[email protected]", organization, "OwnerCat")+ author = _create_org_member_with_github("[email protected]", organization, "AuthorCat")++ # Owner is listed first; the commit-authorship reviewer (author) must still be the one chosen.+ assignee = _resolve_autostart_assignee(+ team_id=team.id,+ report_priority=Priority.P0,+ reviewers_content=[_reviewer("ownercat", is_skill_owner=True), _reviewer("authorcat")],+ team_default_priority=Priority.P4,+ )+ assert assignee is not None+ assert assignee.id == author.id++ # An owner-only list resolves to nobody — the caller then falls back to the signals-enabling member.+ assert (+ _resolve_autostart_assignee(+ team_id=team.id,+ report_priority=Priority.P0,+ reviewers_content=[_reviewer("ownercat", is_skill_owner=True)],+ team_default_priority=Priority.P4,+ )+ is None+ )++@pytest.mark.parametrize(("report_priority", "team_default_priority", "expected"),[diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 2b028e64eb5c..ab92e6df7d6b 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -36,7 +36,7 @@ from products.signals.backend.scout_harness.skill_loader import ()from products.signals.backend.scout_harness.tools.runs import _build_task_url, _to_detail, _to_summaryfrom products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, run_signals_scout_activity-from products.skills.backend.models.skills import LLMSkill, LLMSkillFile+from products.skills.backend.models.skills import LLMSkill, LLMSkillFile, LLMSkillOwnerif TYPE_CHECKING:from products.tasks.backend.models import TaskRun@@ -215,6 +215,44 @@ class TestSkillLoader(BaseTest):skill.save()assert load_skill_for_run(self.team, "signals-scout-general", include_authors=True).authors == []+ def test_authors_prefer_explicit_owners_over_version_history(self) -> None:+ # With an explicit owner set, ownership is authoritative and stable: a later editor never+ # displaces the owner. Here ben owns the skill but self.user is the latest editor — the+ # version-history reconstruction would surface self.user, the owner set must not.+ ben = User.objects.create_and_join(self.organization, "[email protected]", None, "Ben")+ v1 = self._create_skill("signals-scout-errors")+ v1.is_latest = False+ v1.save()+ LLMSkill.objects.create(+ team=self.team,+ name="signals-scout-errors",+ description="A test skill",+ body="edited body",+ version=2,+ is_latest=True,+ created_by=self.user,+ )+ LLMSkillOwner.objects.for_team(self.team.id).create(team=self.team, skill_name="signals-scout-errors", user=ben)+ loaded = load_skill_for_run(self.team, "signals-scout-errors", include_authors=True)+ assert [(a.role, a.email) for a in loaded.authors] == [("owner", "[email protected]")]++ def test_owned_skill_with_all_owners_revoked_returns_no_authors(self) -> None:+ # A skill with owner rows is authoritatively owned. If every owner loses access, the reviewer+ # path must return NO authors, not silently drift back to the version-history editor — the+ # exact misroute the owner primitive exists to prevent. self.user is a valid version author+ # here, so a regression that falls through would surface them.+ ben = User.objects.create_and_join(self.organization, "[email protected]", None, "Ben")+ skill = self._create_skill("signals-scout-errors")+ skill.created_by = self.user+ skill.save()+ LLMSkillOwner.objects.for_team(self.team.id, canonical=True).create(+ team=self.team, skill_name="signals-scout-errors", user=ben+ )+ OrganizationMembership.objects.filter(user=ben).delete()++ loaded = load_skill_for_run(self.team, "signals-scout-errors", include_authors=True)+ assert loaded.authors == []+def test_signals_scout_prefix_check(self) -> None:match = self._create_skill("signals-scout-errors")non_match = self._create_skill("custom-research-helper")diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.pyindex e840a1932417..f4ff81adb619 100644--- a/products/signals/backend/test/test_scout_report_api.py+++ b/products/signals/backend/test/test_scout_report_api.py@@ -15,7 +15,7 @@ from social_django.models import UserSocialAuthfrom posthog.models import Organization, Team, Userfrom posthog.models.organization import OrganizationMembership-from products.signals.backend.artefact_schemas import SuggestedReviewers, TaskRunArtefact+from products.signals.backend.artefact_schemas import Priority, PriorityAssessment, SuggestedReviewers, TaskRunArtefactfrom products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalSourceConfigfrom products.signals.backend.scout_harness.tools.report import (MAX_SUGGESTED_REVIEWERS,@@ -27,10 +27,12 @@ from products.signals.backend.scout_harness.tools.report import (_build_suggested_reviewers,_capture_report_edited,_report_classification_props,+ _skill_authored_report,+ _wants_repo_selection,)from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponsefrom products.signals.backend.test.test_scout_harness_api import _authenticate_as_scout, _make_run-from products.skills.backend.models.skills import LLMSkill+from products.skills.backend.models.skills import LLMSkill, LLMSkillOwnerJUDGE_PATH = "products.signals.backend.scout_report.judge.judge_report_safety"EMBED_PATH = "products.signals.backend.scout_report.persistence.emit_embedding_request"@@ -92,6 +94,18 @@ class TestScoutReportAPI(APIBaseTest):body.update(overrides)return body+ def _seed_skill_owner(self, login: str, skill_name: str = "signals-scout-general") -> User:+ user = User.objects.create(email=f"{login}@example.com")+ OrganizationMembership.objects.create(user=user, organization=self.organization)+ UserSocialAuth.objects.create(user=user, provider="github", uid=f"gh-{login}", extra_data={"login": login})+ LLMSkillOwner.objects.for_team(self.team.id).create(team=self.team, skill_name=skill_name, user=user)+ return user++ def _reviewer_logins(self, report_id: str) -> list[str]:+ artefact = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS)+ assert artefact is not None+ return [entry["github_login"] for entry in json.loads(artefact.content)]+def test_emit_report_authors_ready_report(self) -> None:run = _make_run(self.team)with _safe_judge(), patch(EMBED_PATH) as embed_mock:@@ -401,6 +415,90 @@ class TestScoutReportAPI(APIBaseTest):assert stored["alice"]["reason"] == "confirmed owner via human correction"assert stored["dave"]["relevant_commits"] == []+ def test_edit_report_injects_owners_only_into_reports_the_skill_authored(self) -> None:+ # The owner guardrail on edit is scoped to reports the skill authored: `edit_report` can+ # target any inbox report, and stamping the editing skill's owners onto an unrelated+ # (e.g. pipeline-authored) report would rewrite that report's routing on no evidence.+ self._seed_skill_owner("scoutowner")+ run = _make_run(self.team)+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):+ authored = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()+ foreign = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="pipeline report")++ with patch(AUTOSTART_PATH, new=AsyncMock()):+ for report_id in (authored["report_id"], str(foreign.id)):+ response = self.client.post(+ self._edit_url(str(run.id)),+ data={"report_id": report_id, "suggested_reviewers": [{"github_login": "picked"}]},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()++ assert self._reviewer_logins(authored["report_id"]) == ["scoutowner", "picked"]+ assert self._reviewer_logins(str(foreign.id)) == ["picked"]++ def test_skill_authored_report_resolves_without_ambient_team_scope(self) -> None:+ # `SignalScoutRun` is on a fail-closed manager; the async harness path (temporal runner) has+ # no ambient request scope, so the helper must query via `for_team` — the ambient-context+ # manager would raise TeamScopeError there. This direct call runs with no request scope,+ # exactly like the runner.+ run = _make_run(self.team)+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()+ foreign = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY, title="pipeline")+ assert _skill_authored_report(self.team, "signals-scout-general", created["report_id"]) is True+ assert _skill_authored_report(self.team, "signals-scout-general", str(foreign.id)) is False++ def test_edit_readding_former_owner_clears_owner_provenance(self) -> None:+ # A former owner re-added as a normal reviewer must lose `is_skill_owner`: provenance is+ # recomputed from the live owner set on every reviewers-setting edit, and carrying the stale+ # flag forward would keep excluding them from autostart identity selection.+ self._seed_skill_owner("formerowner")+ run = _make_run(self.team)+ with _safe_judge(), patch(EMBED_PATH), patch(AUTOSTART_PATH, new=AsyncMock()):+ created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()+ report_id = created["report_id"]+ artefact = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS)+ assert artefact is not None+ seeded_entry = json.loads(artefact.content)[0]+ assert (seeded_entry["github_login"], seeded_entry["is_skill_owner"]) == ("formerowner", True)++ LLMSkillOwner.objects.for_team(self.team.id).filter(skill_name="signals-scout-general").delete()+ with patch(AUTOSTART_PATH, new=AsyncMock()):+ response = self.client.post(+ self._edit_url(str(run.id)),+ data={"report_id": report_id, "suggested_reviewers": [{"github_login": "formerowner"}]},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ artefact = self._latest_artefact(report_id, SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS)+ assert artefact is not None+ stored = {entry["github_login"]: entry for entry in json.loads(artefact.content)}+ assert stored["formerowner"]["is_skill_owner"] is False++ def test_scout_token_skill_fetch_hides_owners_off_the_report_channel(self) -> None:+ # The run prompt gates its owners line on the report channel because owner identities are+ # member PII a signal-channel scout has no routing use for — but the sandbox token could+ # still read them straight off skill-get. The skills serializer applies the same gate to+ # scout callers; a report-channel skill keeps its owners since they route its reports.+ owner = self._seed_skill_owner("reportowner")+ LLMSkill.objects.create(+ team=self.team,+ name="signals-scout-quiet",+ description="signal-channel scout",+ body="# scout",+ allowed_tools=["emit_signal"],+ )+ self._seed_skill_owner("quietowner", skill_name="signals-scout-quiet")++ quiet = self.client.get(f"/api/projects/{self.team.id}/llm_skills/name/signals-scout-quiet/")+ assert quiet.status_code == status.HTTP_200_OK, quiet.json()+ assert quiet.json()["owners"] == []++ report_channel = self.client.get(f"/api/projects/{self.team.id}/llm_skills/name/signals-scout-general/")+ assert report_channel.status_code == status.HTTP_200_OK, report_channel.json()+ assert [entry["email"] for entry in report_channel.json()["owners"]] == [owner.email]+def test_edit_report_unresolvable_reviewer_does_not_partially_mutate(self) -> None:# A combined edit (title + a bad reviewer) must fail atomically: reviewers resolve before any# write, so an unresolvable user_uuid 400s without the title change leaking through.@@ -627,7 +725,7 @@ class TestBuildSuggestedReviewers(APIBaseTest):return userdef test_resolves_github_login_lowercased(self) -> None:- result = _build_suggested_reviewers(self.team.id, [ReviewerInput(github_login="OctoCat")])+ result = _build_suggested_reviewers(self.team, [ReviewerInput(github_login="OctoCat")])assert result is not Noneassert [e.github_login for e in result.root] == ["octocat"]@@ -635,7 +733,7 @@ class TestBuildSuggestedReviewers(APIBaseTest):# The resolver rebuilds entries from resolved logins — a refactor that drops `reason` there# silently reverts reviewer routing to unexplained picks. Whitespace-only normalizes to None.result = _build_suggested_reviewers(- self.team.id,+ self.team,[ReviewerInput(github_login="alice", reason="Top recent author on the affected surface"),ReviewerInput(github_login="bob", reason=" "),@@ -649,23 +747,21 @@ class TestBuildSuggestedReviewers(APIBaseTest):def test_resolves_user_uuid_to_linked_login(self) -> None:member = self._github_member("ghhandle")- result = _build_suggested_reviewers(self.team.id, [ReviewerInput(user_uuid=str(member.uuid))])+ result = _build_suggested_reviewers(self.team, [ReviewerInput(user_uuid=str(member.uuid))])assert result is not Noneassert [e.github_login for e in result.root] == ["ghhandle"]def test_user_uuid_wins_when_both_supplied(self) -> None:# The serializer documents that a supplied user_uuid wins over a github_login on the same entry.member = self._github_member("realhandle")- result = _build_suggested_reviewers(- self.team.id, [ReviewerInput(github_login="typo", user_uuid=str(member.uuid))]- )+ result = _build_suggested_reviewers(self.team, [ReviewerInput(github_login="typo", user_uuid=str(member.uuid))])assert result is not Noneassert [e.github_login for e in result.root] == ["realhandle"]def test_dedupes_login_and_uuid_resolving_to_same_person(self) -> None:member = self._github_member("dupe")result = _build_suggested_reviewers(- self.team.id, [ReviewerInput(github_login="dupe"), ReviewerInput(user_uuid=str(member.uuid))]+ self.team, [ReviewerInput(github_login="dupe"), ReviewerInput(user_uuid=str(member.uuid))])assert result is not Noneassert [e.github_login for e in result.root] == ["dupe"]@@ -679,17 +775,17 @@ class TestBuildSuggestedReviewers(APIBaseTest):else:target = str(uuid4())with pytest.raises(InvalidScoutReportError):- _build_suggested_reviewers(self.team.id, [ReviewerInput(user_uuid=target)])+ _build_suggested_reviewers(self.team, [ReviewerInput(user_uuid=target)])@parameterized.expand([("none", None), ("empty", [])])def test_no_entries_yields_none(self, _name: str, reviewers: list | None) -> None:- assert _build_suggested_reviewers(self.team.id, reviewers) is None+ assert _build_suggested_reviewers(self.team, reviewers) is Nonedef test_entry_with_neither_identifier_raises(self) -> None:# An entry that carries neither a usable login nor a uuid is malformed — fail loud rather than# drop it, since a silently-dropped reviewer is exactly what leaves a report routed to no one.with pytest.raises(InvalidScoutReportError):- _build_suggested_reviewers(self.team.id, [ReviewerInput(github_login=" ")])+ _build_suggested_reviewers(self.team, [ReviewerInput(github_login=" ")])def test_caps_entries_before_resolving_uuids(self) -> None:# An over-cap list must be rejected before the UUID resolver runs, so a malformed many-entry@@ -697,9 +793,132 @@ class TestBuildSuggestedReviewers(APIBaseTest):resolver = "products.signals.backend.scout_harness.tools.report.get_org_member_github_logins_by_user_uuid"entries = [ReviewerInput(user_uuid=str(uuid4())) for _ in range(MAX_SUGGESTED_REVIEWERS + 1)]with patch(resolver) as resolve_mock, pytest.raises(InvalidScoutReportError):- _build_suggested_reviewers(self.team.id, entries)+ _build_suggested_reviewers(self.team, entries)resolve_mock.assert_not_called()+ def _seed_owner(self, skill_name: str, user: User) -> None:+ LLMSkillOwner.objects.for_team(self.team.id).create(team=self.team, skill_name=skill_name, user=user)++ def test_owners_enforced_first_and_deduped(self) -> None:+ # The guardrail: the running scout's owners are routed first, ahead of the model's picks, so a+ # report about a scout always reaches whoever owns it — even if the model also names the owner+ # (deduped) or picks someone else too. A regression that drops the guardrail routes to the+ # model's pick alone.+ self._seed_owner("signals-scout-x", self._github_member("ownerlogin"))+ result = _build_suggested_reviewers(+ self.team,+ [ReviewerInput(github_login="ownerlogin"), ReviewerInput(github_login="other")],+ skill_name="signals-scout-x",+ enforce_owners=True,+ )+ assert result is not None+ assert [e.github_login for e in result.root] == ["ownerlogin", "other"]+ assert result.root[0].reason == "skill owner"++ def test_owner_injected_when_scout_supplies_no_reviewers(self) -> None:+ # Foolproof routing: a report authored with no reviewers still routes to the owner, rather+ # than to no one.+ self._seed_owner("signals-scout-y", self._github_member("soleowner"))+ result = _build_suggested_reviewers(self.team, None, skill_name="signals-scout-y", enforce_owners=True)+ assert result is not None+ assert [e.github_login for e in result.root] == ["soleowner"]++ def test_owners_not_injected_without_enforce_flag(self) -> None:+ # The edit path leaves enforcement off when the caller isn't setting reviewers, so an+ # unrelated edit never injects owners over a routing a human may have chosen.+ self._seed_owner("signals-scout-z", self._github_member("ignoredowner"))+ result = _build_suggested_reviewers(+ self.team,+ [ReviewerInput(github_login="picked")],+ skill_name="signals-scout-z",+ enforce_owners=False,+ )+ assert result is not None+ assert [e.github_login for e in result.root] == ["picked"]++ def test_scout_repeating_an_owner_keeps_owner_provenance(self) -> None:+ # The skill body steers the scout, so a scout repeating an owner's login is not independent+ # commit-authorship evidence: clearing `is_skill_owner` here would let a skill editor name a+ # privileged member as owner, steer the scout to repeat that login, and mint the autostart+ # session as them. The flag must survive the dedupe; only the scout's reason merges in.+ self._seed_owner("signals-scout-v", self._github_member("pickedowner"))+ result = _build_suggested_reviewers(+ self.team,+ [ReviewerInput(github_login="PickedOwner", reason="top author on the surface")],+ skill_name="signals-scout-v",+ enforce_owners=True,+ )+ assert result is not None+ assert [(e.github_login, e.is_skill_owner, e.reason) for e in result.root] == [+ ("pickedowner", True, "top author on the surface")+ ]++ def test_scout_pick_survives_owner_overflow_at_the_cap(self) -> None:+ # A skill can hold more GitHub-routable owners than MAX_SUGGESTED_REVIEWERS+ # (MAX_SKILL_OWNERS exceeds it). Plain head-truncation would return an owner-only list,+ # silently discarding the scout's explicit pick — and with it the only entry+ # `_wants_repo_selection` counts as PR intent. The last slot is reserved for the pick.+ for i in range(MAX_SUGGESTED_REVIEWERS + 2):+ self._seed_owner("signals-scout-full", self._github_member(f"owner{i}"))+ result = _build_suggested_reviewers(+ self.team,+ [ReviewerInput(github_login="scoutpick", reason="top author on the surface")],+ skill_name="signals-scout-full",+ enforce_owners=True,+ )+ assert result is not None+ assert len(result.root) == MAX_SUGGESTED_REVIEWERS+ assert result.root[-1].github_login == "scoutpick"+ assert result.root[-1].is_skill_owner is False+ assert all(e.is_skill_owner for e in result.root[:-1])++ def test_owner_without_github_identity_is_skipped(self) -> None:+ # A `suggested_reviewers` artefact is GitHub-login-keyed, so an owner with no linked identity+ # can't be routed — skip them without failing the whole resolution.+ orphan = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(user=orphan, organization=self.organization)+ self._seed_owner("signals-scout-w", orphan)+ result = _build_suggested_reviewers(+ self.team,+ [ReviewerInput(github_login="picked")],+ skill_name="signals-scout-w",+ enforce_owners=True,+ )+ assert result is not None+ assert [e.github_login for e in result.root] == ["picked"]+++_P1 = PriorityAssessment(priority=Priority.P1, explanation="big blast radius")+_OWNER_ONLY_REVIEWERS = SuggestedReviewers.model_validate([{"github_login": "owner", "is_skill_owner": True}])+_OWNER_PLUS_SCOUT_PICK = SuggestedReviewers.model_validate(+ [{"github_login": "owner", "is_skill_owner": True}, {"github_login": "picked"}]+)+++class TestWantsRepoSelection(SimpleTestCase):+ """The PR-intent gate for repo selection. The load-bearing case: owner-guardrail entries land on+ every emit, so counting them as reviewers would run free-form repo selection (and later autostart+ under the team fallback runner) for a prioritized report whose scout supplied neither a repo nor+ a reviewer."""++ @parameterized.expand(+ [+ ("owner_only_reviewers_are_not_pr_intent", None, _P1, _OWNER_ONLY_REVIEWERS, False),+ ("scout_pick_with_priority_is_pr_intent", None, _P1, _OWNER_PLUS_SCOUT_PICK, True),+ ("explicit_repository_always_selects", "posthog/posthog", None, _OWNER_ONLY_REVIEWERS, True),+ ("priority_without_reviewers_is_not_pr_intent", None, _P1, None, False),+ ]+ )+ def test_wants_repo_selection(+ self,+ _name: str,+ repository: str | None,+ priority: PriorityAssessment | None,+ reviewers: SuggestedReviewers | None,+ expected: bool,+ ) -> None:+ assert _wants_repo_selection(repository, priority, reviewers) is expected+class TestReportClassificationProps(SimpleTestCase):@parameterized.expand(diff --git a/products/skills/backend/api/skill_serializers.py b/products/skills/backend/api/skill_serializers.pyindex a236a4bb15c3..6ae704865d95 100644--- a/products/skills/backend/api/skill_serializers.py+++ b/products/skills/backend/api/skill_serializers.py@@ -13,6 +13,13 @@ from posthog.api.shared import UserBasicSerializerfrom products.ai_observability.backend.markdown_outline import get_markdown_outlinefrom ..models.skills import LLMSkill, LLMSkillFile, category_for_skill_name+from .skill_services import (+ LLMSkillOwnerNotFoundError,+ 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 category-tab slugs registered under /skills/<slug> in@@ -27,6 +34,9 @@ _LIST_EXCLUDED_FIELDS = ("body", "body_total_length", "body_next_offset", "filesMAX_SKILL_BODY_BYTES = 1_000_000MAX_SKILL_FILE_BYTES = 1_000_000MAX_SKILL_FILE_COUNT = 50+# Ownership is a short routing list, not an ACL — cap it so a create/update can't resolve membership,+# clear the owner set, and insert an owner row per entry for an oversized input before being rejected.+MAX_SKILL_OWNERS = 25# skill-get returns the whole body when the caller doesn't page, but a large body is# truncated by the MCP transport before it reaches an agent — and an un-paged response# reported body_next_offset as null, so the agent had no valid offset to continue from and@@ -36,6 +46,11 @@ MAX_SKILL_FILE_COUNT = 50# response envelope (outline, file manifest, metadata).DEFAULT_BODY_PAGE_LENGTH = 8000SKILL_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+# hidden from scout callers rather than exposing them.+SCOUT_REPORT_CHANNEL_TOOLS = frozenset({"emit_report", "edit_report"})def validate_skill_name_value(value: str) -> str:@@ -313,6 +328,22 @@ class LLMSkillFileEditSerializer(serializers.Serializer):return value+# The fields that publish a new skill version when present on a PATCH. A payload carrying none of+# these (owners only) replaces ownership without minting a version — the view branches on the same+# tuple, so keep the two in sync via this constant.+PUBLISH_CONTENT_FIELDS = (+ "body",+ "edits",+ "description",+ "license",+ "compatibility",+ "allowed_tools",+ "metadata",+ "files",+ "file_edits",+)++class LLMSkillPublishSerializer(serializers.Serializer):body = serializers.CharField(required=False,@@ -370,9 +401,21 @@ class LLMSkillPublishSerializer(serializers.Serializer):"Cannot add, remove, or rename files — use 'files' for that. Mutually exclusive with files."),)+ owners = serializers.ListField(+ child=serializers.UUIDField(),+ required=False,+ max_length=MAX_SKILL_OWNERS,+ help_text="Replace the skill's owners with these user UUIDs (each a member of this project). "+ "Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the "+ "logical skill, so setting them is independent of the version being published — a body edit "+ "alone never changes ownership.",+ )base_version = serializers.IntegerField(min_value=1,- help_text="Latest version you are editing from. Used for optimistic concurrency checks.",+ required=False,+ help_text="Latest version you are editing from. Used for optimistic concurrency checks. "+ "Required when publishing content changes; optional for an owner-only update (when omitted, "+ "owners are replaced without a concurrency check).",)def validate_body(self, value: str) -> str:@@ -399,6 +442,15 @@ class LLMSkillPublishSerializer(serializers.Serializer):raise serializers.ValidationError("Provide either 'body' or 'edits', not both.")if "files" in attrs and "file_edits" in attrs:raise serializers.ValidationError("Provide either 'files' or 'file_edits', not both.")+ # `base_version` is a plain optional field so the generated PATCH schema (which marks every+ # body field optional) stays truthful for owner-only updates — but any payload that publishes+ # a version still needs the optimistic-concurrency anchor, so require it here where the+ # field-level schema can't.+ is_owner_only = attrs.get("owners") is not None and all(attrs.get(f) is None for f in PUBLISH_CONTENT_FIELDS)+ if not is_owner_only and attrs.get("base_version") is None:+ raise serializers.ValidationError(+ {"base_version": "base_version is required unless the update only sets owners."}+ )return attrs@@ -425,6 +477,12 @@ class LLMSkillSerializer(serializers.ModelSerializer):"not writable via the API. Empty for an ordinary skill. Groups skills into their own surface ""(e.g. the Scouts tab) independently of the skill name.",)+ owners = serializers.SerializerMethodField(+ help_text="Users who own this skill, seed-creator first. Ownership is keyed on the logical skill "+ "(not a version), so it's stable across edits. Prefer this over created_by to learn who to route "+ "reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). "+ "Empty for scout sandbox fetches of skills that haven't opted into the report channel.",+ )files = serializers.SerializerMethodField(help_text="Bundled files manifest. Each entry carries path, content_type, and line/char counts — no content; fetch content via /llm_skills/name/{name}/files/{path}/.",)@@ -456,6 +514,7 @@ class LLMSkillSerializer(serializers.ModelSerializer):"allowed_tools","metadata","category",+ "owners","files","outline","version",@@ -470,6 +529,7 @@ class LLMSkillSerializer(serializers.ModelSerializer):]read_only_fields = ["id",+ "owners","files","outline","body_total_length",@@ -514,6 +574,24 @@ class LLMSkillSerializer(serializers.ModelSerializer):return valuereturn value.isoformat().replace("+00:00", "Z")+ @extend_schema_field(UserBasicSerializer(many=True))+ def get_owners(self, instance: LLMSkill) -> list[dict[str, Any]]:+ # Owner identities are member PII. A scout sandbox token only gets them on skills that+ # opted into the report channel — owners exist to route `suggested_reviewers`, which only+ # report-channel scouts have — mirroring how the run prompt gates its owners line.+ if self.context.get("scout_sandbox_caller") and not (+ SCOUT_REPORT_CHANNEL_TOOLS & set(instance.allowed_tools or [])+ ):+ return []+ # The list endpoint pre-resolves owners for the whole page (one query) and passes them via+ # context to avoid N+1; a single-skill fetch resolves on demand.+ owners_by_name = self.context.get("owners_by_skill_name")+ if owners_by_name is not None:+ users = owners_by_name.get(instance.name, [])+ else:+ users = resolve_skill_owners(self.context["get_team"](), instance.name)+ return list(UserBasicSerializer(users, many=True).data)+@extend_schema_field(LLMSkillFileManifestSerializer(many=True))def get_files(self, instance: LLMSkill) -> list[dict[str, Any]]:# Counts are computed in the database so the manifest never fetches file contents.@@ -581,7 +659,7 @@ class LLMSkillSerializer(serializers.ModelSerializer):class LLMSkillCreateSerializer(LLMSkillSerializer):- """Create serializer — accepts bundled files as write-only input on POST."""+ """Create serializer — accepts bundled files and owners as write-only input on POST."""files = LLMSkillFileInputSerializer( # type: ignore[assignment]many=True,@@ -589,9 +667,17 @@ class LLMSkillCreateSerializer(LLMSkillSerializer):write_only=True,help_text="Bundled files to include with the initial version (scripts, references, assets).",)+ owners = serializers.ListField( # type: ignore[assignment]+ child=serializers.UUIDField(),+ required=False,+ write_only=True,+ max_length=MAX_SKILL_OWNERS,+ help_text="User UUIDs to set as the skill's owners. Each must be a member of this project. "+ "Defaults to the creating user when omitted; pass an empty list to create with no owners.",+ )class Meta(LLMSkillSerializer.Meta):- read_only_fields = [f for f in LLMSkillSerializer.Meta.read_only_fields if f != "files"]+ read_only_fields = [f for f in LLMSkillSerializer.Meta.read_only_fields if f not in ("files", "owners")]def validate_files(self, value: list[dict[str, Any]]) -> list[dict[str, Any]]:return _validate_files(value)@@ -600,6 +686,7 @@ class LLMSkillCreateSerializer(LLMSkillSerializer):request = self.context["request"]team = self.context["get_team"]()files = validated_data.pop("files", None)+ owner_uuids = validated_data.pop("owners", None)with transaction.atomic():# `category` is read-only on the serializer, so it can never arrive in validated_data —@@ -623,6 +710,20 @@ class LLMSkillCreateSerializer(LLMSkillSerializer):for f in files])+ # `is not None`, not truthiness: an explicit empty list means "create with no owners"+ # and must not fall through to the creator-owns default (matching the update path).+ if owner_uuids is not None:+ try:+ owner_users = resolve_owner_users(team, [str(u) for u in owner_uuids])+ except LLMSkillOwnerNotFoundError as err:+ raise serializers.ValidationError(+ {"owners": f"User '{err.user_uuid}' is not a member of this project."},+ code="invalid_owner",+ )+ set_skill_owners(team, skill.name, owner_users)+ else:+ # Creator owns by default — durable, not reconstructed from version history.+ seed_skill_owner(team, skill.name, request.user)return skilldiff --git a/products/skills/backend/api/skill_services.py b/products/skills/backend/api/skill_services.pyindex e831b9691626..432e9ef0dbab 100644--- a/products/skills/backend/api/skill_services.py+++ b/products/skills/backend/api/skill_services.py@@ -7,7 +7,13 @@ from django.utils import timezonefrom posthog.models import Team, User-from ..models.skills import LLMSkill, LLMSkillFile, annotate_llm_skill_version_history_metadata, category_for_skill_name+from ..models.skills import (+ LLMSkill,+ LLMSkillFile,+ LLMSkillOwner,+ annotate_llm_skill_version_history_metadata,+ category_for_skill_name,+)MAX_SKILL_VERSION = 2000MAX_SKILL_BODY_BYTES = 1_000_000@@ -48,6 +54,13 @@ class LLMSkillDuplicateNameConflictError(Exception):pass+@dataclass+class LLMSkillOwnerNotFoundError(Exception):+ """A user_uuid passed as an owner is not a member of the team (has no access)."""++ user_uuid: str++@dataclassclass LLMSkillFilePathConflictError(Exception):path: str@@ -370,6 +383,9 @@ def create_skill(raise LLMSkillDuplicateNameConflictError() from errraise+ # The creator owns the skill by default — durable, not reconstructed from version history.+ seed_skill_owner(team, name, user)+if files:try:LLMSkillFile.objects.bulk_create(@@ -439,6 +455,10 @@ def duplicate_skill(raise LLMSkillDuplicateNameConflictError() from errraise+ # A duplicate is a brand-new, user-authored skill: the duplicating user owns it, not the+ # source's owners (who never chose to own this fork).+ seed_skill_owner(team, new_name, user)+_copy_files(source_latest, new_skill)refreshed = get_active_skill_queryset(team).filter(pk=new_skill.pk).first()@@ -598,4 +618,121 @@ def archive_skill(team: Team, skill_name: str) -> list[int]:is_latest=False,updated_at=timezone.now(),)+ # Owners are keyed on the logical `(team, skill_name)`, so they'd otherwise outlive the+ # archived skill and attach to a later skill that reuses the name. Retire them with it.+ clear_skill_owners(team, skill_name)return skill_versions+++# --- Skill owners ---------------------------------------------------------------------------------+# Owners are keyed on the *logical* skill `(team, skill_name)`, so nothing here touches a version row:+# editing a skill body never changes who owns it. Every read and write goes through `_owner_qs`, which+# scopes to the *exact* environment team (`canonical=True` skips the child→parent resolution) so owners+# line up with `LLMSkill`'s environment scoping — see the `LLMSkillOwner` model docstring.+++def _owner_qs(team: Team) -> "QuerySet[LLMSkillOwner]":+ """Owner rows scoped to the exact environment team (not the canonical parent).++ `canonical=True` tells `for_team` the id is the scope to filter on as-is; it does not mean the id+ *is* canonical here — it deliberately bypasses the parent resolution so environment-scoped skills+ and their owners share one key. Works inside a request and outside one (harness, commands).+ """+ return LLMSkillOwner.objects.for_team(team.id, canonical=True)+++def resolve_owner_users(team: Team, user_uuids: list[str]) -> list[User]:+ """Resolve owner UUIDs to team members, preserving order and deduping.++ Fail-loud: a UUID that isn't a member with access raises `LLMSkillOwnerNotFoundError` rather than+ silently dropping — an owner who can't be resolved could never be routed a review anyway, and a+ quietly-lost owner is exactly the misattribution this primitive exists to prevent.+ """+ members = {str(u.uuid): u for u in team.all_users_with_access()}+ resolved: list[User] = []+ seen: set[str] = set()+ for raw_uuid in user_uuids:+ uuid = str(raw_uuid)+ if uuid in seen:+ continue+ seen.add(uuid)+ user = members.get(uuid)+ if user is None:+ raise LLMSkillOwnerNotFoundError(user_uuid=uuid)+ resolved.append(user)+ return resolved+++def resolve_skill_owners(team: Team, skill_name: str) -> list[User]:+ """Owners of a logical skill, seed-creator first (earliest `created_at`).++ Restricted to `team.all_users_with_access()`: an owner row survives a member losing access+ (rows aren't cascade-cleaned on access revocation), and this read path serializes the user+ through `UserBasicSerializer` on `skill-get` / `skill-list` (both MCP-exposed), so a former+ member's profile must not keep flowing out — matching the write and scout-prompt paths.+ """+ rows = (+ _owner_qs(team)+ .filter(skill_name=skill_name, user__in=team.all_users_with_access())+ .select_related("user")+ .order_by("created_at", "id")+ )+ return [row.user for row in rows]+++def resolve_skill_owners_for_names(team: Team, skill_names: list[str]) -> dict[str, list[User]]:+ """Batch `resolve_skill_owners` for many skills in one query — for the list endpoint's N rows.++ Same current-access filter as `resolve_skill_owners` so the list endpoint never leaks a former+ member's profile or reports an unroutable owner.+ """+ if not skill_names:+ return {}+ rows = (+ _owner_qs(team)+ .filter(skill_name__in=skill_names, user__in=team.all_users_with_access())+ .select_related("user")+ .order_by("created_at", "id")+ )+ owners_by_name: dict[str, list[User]] = {}+ for row in rows:+ owners_by_name.setdefault(row.skill_name, []).append(row.user)+ return owners_by_name+++def clear_skill_owners(team: Team, skill_name: str) -> None:+ """Drop every owner row for a logical skill — called on archive so a later skill that reuses the+ name (recreate / import / duplicate) doesn't inherit the archived skill's owners."""+ _owner_qs(team).filter(skill_name=skill_name).delete()+++def seed_skill_owner(team: Team, skill_name: str, user: User) -> None:+ """Idempotently record `user` as an owner — the default seed on skill creation.++ Routed through `_owner_qs` (not the ambient-context manager) so it works both inside a request and+ outside one (harness, management commands).+ """+ _owner_qs(team).get_or_create(team=team, skill_name=skill_name, user=user)+++def set_skill_owners(team: Team, skill_name: str, users: list[User]) -> list[User]:+ """Replace the owner set for a logical skill with `users` (deduped, order preserved).++ An empty list clears all owners. This is the explicit owner-management op — it is only ever+ called when a caller passes `owners`, never as a side effect of a body edit.+ """+ seen: set[int] = set()+ ordered: list[User] = []+ for user in users:+ if user.pk in seen:+ continue+ seen.add(user.pk)+ ordered.append(user)++ with transaction.atomic():+ _owner_qs(team).filter(skill_name=skill_name).delete()+ for user in ordered:+ # One-by-one (not bulk_create) so `save()` runs per row; `_owner_qs` scoping keeps the+ # write context-independent (works outside a request too).+ _owner_qs(team).create(team=team, skill_name=skill_name, user=user)+ return resolve_skill_owners(team, skill_name)diff --git a/products/skills/backend/api/skills.py b/products/skills/backend/api/skills.pyindex cb5803f8a77a..ef5bd1ad2abd 100644--- a/products/skills/backend/api/skills.py+++ b/products/skills/backend/api/skills.py@@ -1,7 +1,8 @@+from collections.abc import Sequencefrom typing import Any, castfrom uuid import UUID-from django.db import IntegrityError, OperationalError+from django.db import IntegrityError, OperationalError, transactionfrom django.db.models import Case, Exists, IntegerField, OuterRef, Q, QuerySet, Value, Whenfrom django.http import HttpResponse@@ -27,7 +28,7 @@ from posthog.auth import (from posthog.event_usage import report_user_actionfrom posthog.models import Userfrom posthog.models.utils import execute_with_timeout-from posthog.permissions import AccessControlPermission+from posthog.permissions import AccessControlPermission, get_authenticator_scopesfrom posthog.rate_limit import BurstRateThrottle, SustainedRateThrottlefrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin@@ -47,6 +48,7 @@ from ..models.skills import LLMSkill, LLMSkillFilefrom .skill_serializers import (DEFAULT_BODY_PAGE_LENGTH,MAX_SKILL_FILE_BYTES,+ PUBLISH_CONTENT_FIELDS,LLMSkillBodyFetchQuerySerializer,LLMSkillCreateSerializer,LLMSkillDuplicateSerializer,@@ -80,6 +82,7 @@ from .skill_services import (LLMSkillFileNotFoundError,LLMSkillFilePathConflictError,LLMSkillNotFoundError,+ LLMSkillOwnerNotFoundError,LLMSkillVersionConflictError,LLMSkillVersionLimitError,archive_skill,@@ -92,7 +95,10 @@ from .skill_services import (get_skill_by_name_from_db,publish_skill_version,rename_skill_file,+ resolve_owner_users,+ resolve_skill_owners_for_names,resolve_versions_page,+ set_skill_owners,)logger = structlog.get_logger(__name__)@@ -282,6 +288,22 @@ class LLMSkillViewSet()return None+ def _is_scout_sandbox_caller(self) -> bool:+ """Whether the request is authenticated with a Signals scout sandbox token.++ The scout harness's sandbox token is the only issuer of `signal_scout_internal:*`+ scopes, so their presence identifies a scout run. Session auth and ordinary API+ keys never carry them.+ """+ scopes = get_authenticator_scopes(getattr(self.request, "successful_authenticator", None))+ return scopes is not None and any(scope.startswith("signal_scout_internal:") for scope in scopes)++ def get_serializer_context(self) -> dict[str, Any]:+ context = super().get_serializer_context()+ if self._is_scout_sandbox_caller():+ context["scout_sandbox_caller"] = True+ return context+def _serialize_skill(self, skill: LLMSkill, *, body_offset: int | None = None, body_length: int | None = None) -> dict[str, Any]:@@ -545,22 +567,75 @@ class LLMSkillViewSet(payload = LLMSkillPublishSerializer(data=request.data)payload.is_valid(raise_exception=True)+ # Resolve owners before publishing so a bad UUID 400s without minting a version. `owner_uuids`+ # is None when omitted (owners left untouched), [] when the caller clears them.+ owner_uuids = payload.validated_data.get("owners")+ owner_users = None+ if owner_uuids is not None:+ try:+ owner_users = resolve_owner_users(self.team, [str(u) for u in owner_uuids])+ except LLMSkillOwnerNotFoundError as err:+ raise serializers.ValidationError(+ {"owners": f"User '{err.user_uuid}' is not a member of this project."},+ code="invalid_owner",+ )++ # An owner-only PATCH must not publish a version: owners live on the logical skill, not a+ # version row, so minting an identical version would rewrite version-history authorship, bump+ # marketplace/update timestamps, and burn toward MAX_SKILL_VERSION for a no-op body. Same+ # optimistic-concurrency contract as a publish when `base_version` is supplied: a stale value+ # still 409s. It may be omitted (the generated PATCH schema marks it optional), which skips+ # the version check — ownership isn't version-keyed, so the replace is still exact.+ if owner_uuids is not None and all(payload.validated_data.get(p) is None for p in PUBLISH_CONTENT_FIELDS):+ base_version = payload.validated_data.get("base_version")+ # Lock the latest row for the check + replace (mirrors publish_skill_version): requests+ # run autocommit, so without the lock an owner update racing a publish from the same+ # base_version could pass a stale check and 200 where the contract advertises 409.+ with transaction.atomic():+ current_latest = (+ LLMSkill.objects.select_for_update()+ .filter(team=self.team, name=skill_name, deleted=False, is_latest=True)+ .order_by("-version", "-created_at", "-id")+ .first()+ )+ if current_latest is None:+ return self._skill_not_found_response(skill_name)+ if base_version is not None and base_version != current_latest.version:+ return Response(+ {+ "detail": "The skill changed since you opened it. Reload the latest version and try again.",+ "current_version": current_latest.version,+ },+ status=status.HTTP_409_CONFLICT,+ )+ set_skill_owners(self.team, skill_name, cast(list, owner_users))+ refreshed = get_skill_by_name_from_db(self.team, skill_name=skill_name)+ return Response(self._serialize_skill(cast(LLMSkill, refreshed)))+try:- published_skill = publish_skill_version(- self.team,- user=cast(User, request.user),- skill_name=skill_name,- body=payload.validated_data.get("body"),- edits=payload.validated_data.get("edits"),- description=payload.validated_data.get("description"),- license=payload.validated_data.get("license"),- compatibility=payload.validated_data.get("compatibility"),- allowed_tools=payload.validated_data.get("allowed_tools"),- metadata=payload.validated_data.get("metadata"),- files=payload.validated_data.get("files"),- file_edits=payload.validated_data.get("file_edits"),- base_version=payload.validated_data["base_version"],- )+ # One transaction for the version publish *and* the owner replacement: if setting owners+ # fails, the published version rolls back with it — otherwise the new body/files would be+ # live while ownership stayed stale, and a retry with the original base_version would 409.+ with transaction.atomic():+ published_skill = publish_skill_version(+ self.team,+ user=cast(User, request.user),+ skill_name=skill_name,+ body=payload.validated_data.get("body"),+ edits=payload.validated_data.get("edits"),+ description=payload.validated_data.get("description"),+ license=payload.validated_data.get("license"),+ compatibility=payload.validated_data.get("compatibility"),+ allowed_tools=payload.validated_data.get("allowed_tools"),+ metadata=payload.validated_data.get("metadata"),+ files=payload.validated_data.get("files"),+ file_edits=payload.validated_data.get("file_edits"),+ base_version=payload.validated_data["base_version"],+ )+ # Owners are keyed on the logical skill, so this runs only when the caller passed+ # `owners` — a plain body edit never touches ownership.+ if owner_uuids is not None:+ set_skill_owners(self.team, skill_name, cast(list, owner_users))except IntegrityError as err:if "unique_skill_file_path" in str(err):raise serializers.ValidationError({"files": "Duplicate file paths are not allowed."}, code="unique")@@ -611,6 +686,7 @@ class LLMSkillViewSet("compatibility_changed": payload.validated_data.get("compatibility") is not None,"allowed_tools_changed": payload.validated_data.get("allowed_tools") is not None,"metadata_changed": payload.validated_data.get("metadata") is not None,+ "owners_changed": owner_uuids is not None,}logger.info("llma_skill_version_published",@@ -1242,13 +1318,29 @@ class LLMSkillViewSet(queryset = self.filter_queryset(self._get_list_queryset(request))page = self.paginate_queryset(queryset)if page is not None:- serializer = self.get_serializer(page, many=True)+ context = self._list_context_with_owners(page)+ serializer = self.get_serializer(page, many=True, context=context)return self.get_paginated_response(serializer.data)- serializer = self.get_serializer(queryset, many=True)+ skills = list(queryset)+ context = self._list_context_with_owners(skills)+ serializer = self.get_serializer(skills, many=True, context=context)data = serializer.datareturn Response({"count": len(data), "results": data})+ # `Sequence`, not `list[...]`: the viewset defines a `list` method that shadows the builtin in the+ # class body where this annotation is evaluated.+ def _list_context_with_owners(self, skills: Sequence[LLMSkill]) -> dict[str, Any]:+ """Serializer context carrying a name→owners map, so the list serializes owners in one query."""+ owners_by_skill_name = resolve_skill_owners_for_names(self.team, [skill.name for skill in skills])+ return {**self.get_serializer_context(), "owners_by_skill_name": owners_by_skill_name}++ # Explicit response schema: the request serializer (`LLMSkillCreateSerializer`) exposes `owners`+ # write-only as a UUID list, but the view returns `_serialize_skill` (`LLMSkillSerializer`) with+ # `owners` as `UserBasic[]`. Without this, drf-spectacular would infer the response from the+ # create serializer and the generated `llmSkillsCreate` / MCP `skill-create` types would drop+ # (or mistype) the returned owners.+ @extend_schema(request=LLMSkillCreateSerializer, responses={201: LLMSkillSerializer})@llma_track_latency("llma_skills_create")@monitor(feature=None, endpoint="llma_skills_create", method="POST")def create(self, request, *args, **kwargs):diff --git a/products/skills/backend/api/test/test_skills.py b/products/skills/backend/api/test/test_skills.pyindex 613db29929d5..96fb0c5959e8 100644--- a/products/skills/backend/api/test/test_skills.py+++ b/products/skills/backend/api/test/test_skills.py@@ -10,13 +10,20 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models import User+from posthog.models import Team, Userfrom posthog.models.organization import OrganizationMembershipfrom ee.models.rbac.access_control import AccessControlfrom ...api.skill_serializers import DEFAULT_BODY_PAGE_LENGTH-from ...api.skill_services import MAX_SKILL_FILE_COUNT+from ...api.skill_services import (+ MAX_SKILL_FILE_COUNT,+ archive_skill,+ create_skill,+ publish_skill_version,+ resolve_skill_owners,+ set_skill_owners,+)from ...models.skills import LLMSkill, LLMSkillFile@@ -1442,3 +1449,197 @@ class TestSkillAccessControlRBAC(APIBaseTest):self._url(), data={"name": "new-skill", "description": "d", "body": "x"}, format="json")assert response.status_code == status.HTTP_201_CREATED+++class TestLLMSkillOwners(APIBaseTest):+ """The owners primitive: a durable, version-independent set of owner users on a skill.++ The point of the primitive is that ownership can't drift when the body is edited (the misroute+ that motivated it), so the load-bearing test is `test_owners_survive_version_publish_by_another_user`.+ """++ def _url(self, path: str = "") -> str:+ return f"/api/environments/{self.team.id}/llm_skills/{path}"++ def _member(self, email: str) -> User:+ return User.objects.create_and_join(self.organization, email, None)++ def test_create_seeds_creator_as_owner(self) -> None:+ response = self.client.post(+ self._url(),+ data={"name": "seeded", "description": "d", "body": "# b"},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert [o["email"] for o in response.json()["owners"]] == [self.user.email]++ def test_create_with_explicit_owners_does_not_add_creator(self) -> None:+ member = self._member("[email protected]")+ response = self.client.post(+ self._url(),+ data={"name": "explicit", "description": "d", "body": "# b", "owners": [str(member.uuid)]},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert [o["email"] for o in response.json()["owners"]] == [member.email]++ def test_create_with_non_member_owner_is_rejected(self) -> None:+ response = self.client.post(+ self._url(),+ data={"name": "bad-owner", "description": "d", "body": "# b", "owners": [str(uuid.uuid4())]},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not LLMSkill.objects.filter(name="bad-owner").exists()++ def test_update_replaces_then_clears_owners(self) -> None:+ member = self._member("[email protected]")+ # Seeded via ORM helper (no owner row) so this exercises setting from empty, then replacing.+ LLMSkill.objects.create(team=self.team, name="editable", description="d", body="# b", created_by=self.user)++ set_resp = self.client.patch(+ self._url("name/editable"),+ data={"owners": [str(member.uuid)], "base_version": 1},+ format="json",+ )+ assert set_resp.status_code == status.HTTP_200_OK, set_resp.json()+ assert [o["email"] for o in set_resp.json()["owners"]] == [member.email]++ # Owner-only PATCHes don't publish a version, so the skill is still at version 1.+ clear_resp = self.client.patch(+ self._url("name/editable"),+ data={"owners": [], "base_version": 1},+ format="json",+ )+ assert clear_resp.status_code == status.HTTP_200_OK, clear_resp.json()+ assert clear_resp.json()["owners"] == []++ def test_update_without_owners_leaves_them_untouched(self) -> None:+ create_skill(self.team, user=self.user, name="untouched", description="d", body="# v1")+ response = self.client.patch(+ self._url("name/untouched"),+ data={"body": "# v2", "base_version": 1},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [o["email"] for o in response.json()["owners"]] == [self.user.email]++ def test_owner_only_update_replaces_owners_without_publishing_a_version(self) -> None:+ # Owners live on the logical skill, so an owner-only PATCH must not mint an identical version+ # (rewriting version-history authorship and burning toward the version limit for a no-op body).+ member = self._member("[email protected]")+ create_skill(self.team, user=self.user, name="ownersonly", description="d", body="# b")++ response = self.client.patch(+ self._url("name/ownersonly"),+ data={"owners": [str(member.uuid)], "base_version": 1},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [o["email"] for o in response.json()["owners"]] == [member.email]+ assert response.json()["version"] == 1+ assert LLMSkill.objects.filter(team=self.team, name="ownersonly").count() == 1++ def test_owner_only_update_without_base_version_succeeds(self) -> None:+ # The generated PATCH contract marks every body field optional, so an MCP client can send+ # `{owners: [...]}` alone — that shape must replace owners (skipping the version check), not+ # 400 on a runtime-only base_version requirement the schema doesn't advertise.+ member = self._member("[email protected]")+ create_skill(self.team, user=self.user, name="noversion", description="d", body="# b")++ response = self.client.patch(+ self._url("name/noversion"),+ data={"owners": [str(member.uuid)]},+ format="json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [o["email"] for o in response.json()["owners"]] == [member.email]+ assert LLMSkill.objects.filter(team=self.team, name="noversion").count() == 1++ def test_publish_without_base_version_is_rejected(self) -> None:+ # base_version became an optional field for the owner-only shape; any payload that publishes+ # a version must still be forced to carry the optimistic-concurrency anchor.+ create_skill(self.team, user=self.user, name="anchored", description="d", body="# v1")+ response = self.client.patch(+ self._url("name/anchored"),+ data={"body": "# v2"},+ format="json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "base_version" in str(response.json())++ def test_owner_only_update_with_stale_base_version_conflicts(self) -> None:+ # The optimistic-concurrency contract holds even when no version is published: a stale+ # base_version 409s and leaves ownership untouched.+ member = self._member("[email protected]")+ create_skill(self.team, user=self.user, name="staleowners", description="d", body="# b")++ response = self.client.patch(+ self._url("name/staleowners"),+ data={"owners": [str(member.uuid)], "base_version": 2},+ format="json",+ )+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()+ assert [o.email for o in resolve_skill_owners(self.team, "staleowners")] == [self.user.email]++ def test_owners_survive_version_publish_by_another_user(self) -> None:+ # The whole reason the primitive exists: editing a shared skill must not transfer ownership to+ # the editor. Reconstructing from version-row `created_by` would return the editor here.+ editor = self._member("[email protected]")+ create_skill(self.team, user=self.user, name="durable", description="d", body="# v1")+ publish_skill_version(self.team, user=editor, skill_name="durable", body="# v2", base_version=1)++ owners = resolve_skill_owners(self.team, "durable")+ assert [o.email for o in owners] == [self.user.email]++ def test_create_with_empty_owners_creates_with_no_owners(self) -> None:+ # An explicit empty list must mean "no owners", not fall through to the creator-owns default+ # (a truthiness check on the list would silently seed the creator, unlike the update path).+ response = self.client.post(+ self._url(),+ data={"name": "ownerless", "description": "d", "body": "# b", "owners": []},+ format="json",+ )+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["owners"] == []++ def test_recreated_skill_does_not_inherit_archived_owners(self) -> None:+ # Owners are keyed on the logical `(team, name)`. Archiving must retire them, or a later skill+ # reusing the name inherits the archived skill's owners and routes reports to unrelated people.+ old_owner = self._member("[email protected]")+ create_skill(self.team, user=old_owner, name="reused", description="d", body="# v1")+ assert [o.email for o in resolve_skill_owners(self.team, "reused")] == [old_owner.email]++ archive_skill(self.team, "reused")+ create_skill(self.team, user=self.user, name="reused", description="d", body="# fresh")++ assert [o.email for o in resolve_skill_owners(self.team, "reused")] == [self.user.email]++ def test_skill_get_excludes_owner_who_lost_access(self) -> None:+ # An owner row survives the member losing access; the read path serializes UserBasic, so a+ # former member's profile must not keep leaking through skill-get.+ member = self._member("[email protected]")+ create_skill(self.team, user=self.user, name="leaky", description="d", body="# b")+ set_skill_owners(self.team, "leaky", [self.user, member])++ member.organization_memberships.filter(organization=self.organization).delete()++ response = self.client.get(self._url("name/leaky"))+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert [o["email"] for o in response.json()["owners"]] == [self.user.email]++ def test_owners_are_scoped_to_the_exact_environment(self) -> None:+ # Skills are environment-scoped (LLMSkill filters team=<env>); owners must match. If owners+ # canonicalized to the parent project, two sibling environments' same-named skills would share+ # one owner set — a routing/profile collision. Set distinct owners per env, assert isolation.+ parent = Team.objects.create(organization=self.organization, name="proj")+ env_a = Team.objects.create(organization=self.organization, parent_team=parent, name="env-a")+ env_b = Team.objects.create(organization=self.organization, parent_team=parent, name="env-b")+ alice = self._member("[email protected]")+ bob = self._member("[email protected]")++ set_skill_owners(env_a, "shared-name", [alice])+ set_skill_owners(env_b, "shared-name", [bob])++ assert [o.email for o in resolve_skill_owners(env_a, "shared-name")] == [alice.email]+ assert [o.email for o in resolve_skill_owners(env_b, "shared-name")] == [bob.email]diff --git a/products/skills/backend/migrations/0004_llmskillowner.py b/products/skills/backend/migrations/0004_llmskillowner.pynew file mode 100644index 000000000000..7a50563d8931--- /dev/null+++ b/products/skills/backend/migrations/0004_llmskillowner.py@@ -0,0 +1,62 @@+# Generated by Django 5.2.14 on 2026-07-22 20:28++import django.utils.timezone+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1262_organization_members_can_see_org_members"),+ ("skills", "0003_backfill_scout_category"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="LLMSkillOwner",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("skill_name", models.CharField(max_length=64)),+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ options={+ "db_table": "llm_analytics_llmskillowner",+ "constraints": [+ models.UniqueConstraint(+ fields=("team", "skill_name", "user"),+ name="unique_llm_skill_owner",+ )+ ],+ },+ ),+ ]diff --git a/products/skills/backend/migrations/max_migration.txt b/products/skills/backend/migrations/max_migration.txtindex 7c2e7893dc75..a6c09606e036 100644--- a/products/skills/backend/migrations/max_migration.txt+++ b/products/skills/backend/migrations/max_migration.txt@@ -1 +1 @@-0003_backfill_scout_category+0004_llmskillownerdiff --git a/products/skills/backend/models/__init__.py b/products/skills/backend/models/__init__.pyindex 9f04a59cfe0f..f6f49966477a 100644--- a/products/skills/backend/models/__init__.py+++ b/products/skills/backend/models/__init__.py@@ -1,3 +1,3 @@-from .skills import LLMSkill, LLMSkillFile+from .skills import LLMSkill, LLMSkillFile, LLMSkillOwner-__all__ = ["LLMSkill", "LLMSkillFile"]+__all__ = ["LLMSkill", "LLMSkillFile", "LLMSkillOwner"]diff --git a/products/skills/backend/models/skills.py b/products/skills/backend/models/skills.pyindex e1b4633e4f58..332847305233 100644--- a/products/skills/backend/models/skills.py+++ b/products/skills/backend/models/skills.py@@ -2,6 +2,7 @@ from django.db import modelsfrom django.db.models import Count, DateTimeField, IntegerField, OuterRef, Q, QuerySet, Subqueryfrom django.utils import timezone+from posthog.models.scoping.manager import TeamScopedManagerfrom posthog.models.utils import UUIDModel# Server-owned grouping stamped on every create path (REST serializer, MCP tool, import): the Skills@@ -88,6 +89,52 @@ class LLMSkillFile(UUIDModel):content_type = models.CharField(max_length=100, default="text/plain")+class LLMSkillOwner(UUIDModel):+ """A human who owns a skill, keyed on the *logical* skill `(team, name)` — not a version row.++ Ownership is version-independent by construction: each skill version is its own `LLMSkill`+ row keyed `(team, name, version)`, so anything hung off a version row drifts every time the+ body is edited. Keying owners on `(team, skill_name)` means editing a skill can never touch+ who owns it. Owners are a list, so removing one (its row is dropped) leaves the rest — unlike+ a per-version `created_by`, whose `SET_NULL` on user deletion silently hands ownership to the+ first surviving editor.++ This is the durable answer to "who should review reports about this scout?": the reviewer+ path prefers these owners over reconstructing authorship from mutable version history.++ Scoped to the *exact* environment team, matching `LLMSkill` (a plain `UUIDModel` queried by+ `team=<environment>`) — deliberately NOT `TeamScopedRootMixin`, whose `save()`/`for_team()`+ canonicalize the team to the parent project. If owners were project-canonical while skills are+ environment-scoped, two sibling environments with a same-named skill would share one owner set,+ letting an edit in one environment overwrite the routing (and expose owner profiles) of the+ other. `objects = TeamScopedManager()` keeps it fail-closed against ambient access; every read+ and write goes through `for_team(team.id, canonical=True)`, which filters on the exact team id+ without the child→parent resolution.+ """++ objects = TeamScopedManager()++ # db_constraint=False on the FKs to hot tables (posthog_team, posthog_user): a real FK+ # constraint would take a lock on the parent when this table's rows are created. Enforcement+ # is app-level; the unique constraint below is a plain index and unaffected.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ # Logical skill identity, not a version FK — see the class docstring.+ skill_name = models.CharField(max_length=64)+ user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, db_constraint=False, related_name="+")+ created_at = models.DateTimeField(default=timezone.now)++ class Meta:+ db_table = "llm_analytics_llmskillowner"+ constraints = [+ # Its leading (team, skill_name) columns also serve the reviewer path's lookup of all+ # owners for one logical skill, so no separate index is needed.+ models.UniqueConstraint(+ fields=["team", "skill_name", "user"],+ name="unique_llm_skill_owner",+ ),+ ]++def annotate_llm_skill_version_history_metadata(queryset: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]:active_versions = LLMSkill.objects.filter(team_id=OuterRef("team_id"), name=OuterRef("name"), deleted=False)diff --git a/products/skills/frontend/LLMSkillScene.stories.tsx b/products/skills/frontend/LLMSkillScene.stories.tsxindex e18d8cb7e61f..c31619e01143 100644--- a/products/skills/frontend/LLMSkillScene.stories.tsx+++ b/products/skills/frontend/LLMSkillScene.stories.tsx@@ -81,6 +81,7 @@ const SKILL: LLMSkillApi = {],version: 4,created_by: MOCK_AUTHOR,+ owners: [MOCK_AUTHOR],created_at: '2025-01-14T10:00:00Z',updated_at: '2025-01-14T10:00:00Z',deleted: false,@@ -108,6 +109,7 @@ const SKILL_LIST_ENTRY: LLMSkillListApi = {outline: SKILL.outline,version: SKILL.version,created_by: SKILL.created_by,+ owners: SKILL.owners,created_at: SKILL.created_at,updated_at: SKILL.updated_at,deleted: SKILL.deleted,diff --git a/products/skills/frontend/generated/api.schemas.ts b/products/skills/frontend/generated/api.schemas.tsindex 9ea76627bc8c..2283ac850998 100644--- a/products/skills/frontend/generated/api.schemas.ts+++ b/products/skills/frontend/generated/api.schemas.ts@@ -7,17 +7,6 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/-export interface LLMSkillOutlineEntryApi {- /**- * Markdown heading level (1-6).- * @minimum 1- * @maximum 6- */- level: number- /** Heading text. */- text: string-}-/*** * `engineering` - Engineering* * `data` - Data@@ -73,6 +62,17 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+export interface LLMSkillOutlineEntryApi {+ /**+ * Markdown heading level (1-6).+ * @minimum 1+ * @maximum 6+ */+ level: number+ /** Heading text. */+ text: string+}+/*** Arbitrary key-value metadata.*/@@ -109,6 +109,8 @@ export interface LLMSkillListApi {metadata?: LLMSkillListApiMetadata/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string+ /** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */+ readonly owners: readonly UserBasicApi[]/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */readonly outline: readonly LLMSkillOutlineEntryApi[]readonly version: number@@ -152,7 +154,7 @@ export interface LLMSkillFileInputApi {}/**- * Create serializer — accepts bundled files as write-only input on POST.+ * Create serializer — accepts bundled files and owners as write-only input on POST.*/export interface LLMSkillCreateApi {readonly id: string@@ -191,6 +193,11 @@ export interface LLMSkillCreateApi {metadata?: LLMSkillCreateApiMetadata/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string+ /**+ * User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners.+ * @maxItems 25+ */+ owners?: string[]/** Bundled files to include with the initial version (scripts, references, assets). */files?: LLMSkillFileInputApi[]/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */@@ -206,11 +213,6 @@ export interface LLMSkillCreateApi {readonly first_version_created_at: string}-export interface LLMSkillImportApi {- /** A spec-compliant skill .zip (a SKILL.md plus optional bundled files under scripts/, references/, assets/). */- file: string-}-/*** Arbitrary key-value metadata.*/@@ -264,6 +266,8 @@ export interface LLMSkillApi {metadata?: LLMSkillApiMetadata/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string+ /** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */+ readonly owners: readonly UserBasicApi[]/** Bundled files manifest. Each entry carries path, content_type, and line/char counts — no content; fetch content via /llm_skills/name/{name}/files/{path}/. */readonly files: readonly LLMSkillFileManifestApi[]/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */@@ -279,6 +283,11 @@ export interface LLMSkillApi {readonly first_version_created_at: string}+export interface LLMSkillImportApi {+ /** A spec-compliant skill .zip (a SKILL.md plus optional bundled files under scripts/, references/, assets/). */+ file: string+}+/*** * `absent` - absent* * `exists` - exists@@ -405,7 +414,12 @@ export interface PatchedLLMSkillPublishApi {/** Per-file find/replace updates. Each entry targets one existing file by path and applies sequential edits to its content. Non-targeted files carry forward unchanged. Cannot add, remove, or rename files — use 'files' for that. Mutually exclusive with files. */file_edits?: LLMSkillFileEditApi[]/**- * Latest version you are editing from. Used for optimistic concurrency checks.+ * Replace the skill's owners with these user UUIDs (each a member of this project). Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the logical skill, so setting them is independent of the version being published — a body edit alone never changes ownership.+ * @maxItems 25+ */+ owners?: string[]+ /**+ * Latest version you are editing from. Used for optimistic concurrency checks. Required when publishing content changes; optional for an owner-only update (when omitted, owners are replaced without a concurrency check).* @minimum 1*/base_version?: numberdiff --git a/products/skills/frontend/generated/api.ts b/products/skills/frontend/generated/api.tsindex 4ebba34bbe91..088da0221a3e 100644--- a/products/skills/frontend/generated/api.ts+++ b/products/skills/frontend/generated/api.ts@@ -83,8 +83,8 @@ export const llmSkillsCreate = async (projectId: string,lLMSkillCreateApi: NonReadonly<LLMSkillCreateApi>,options?: RequestInit-): Promise<LLMSkillCreateApi> => {- return apiMutator<LLMSkillCreateApi>(getLlmSkillsCreateUrl(projectId), {+): Promise<LLMSkillApi> => {+ return apiMutator<LLMSkillApi>(getLlmSkillsCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },diff --git a/products/skills/frontend/generated/api.zod.ts b/products/skills/frontend/generated/api.zod.tsindex 996370fb4a68..1ebcda73db6b 100644--- a/products/skills/frontend/generated/api.zod.ts+++ b/products/skills/frontend/generated/api.zod.ts@@ -17,6 +17,8 @@ export const llmSkillsCreateBodyLicenseMax = 255export const llmSkillsCreateBodyCompatibilityMax = 500+export const llmSkillsCreateBodyOwnersMax = 25+export const llmSkillsCreateBodyFilesItemPathMax = 500export const llmSkillsCreateBodyFilesItemContentTypeDefault = `text/plain`@@ -48,6 +50,13 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod.optional().describe('List of pre-approved tools the skill may use. Tool names cannot contain whitespace.'),metadata: zod.record(zod.string(), zod.unknown()).optional().describe('Arbitrary key-value metadata.'),+ owners: zod+ .array(zod.uuid())+ .max(llmSkillsCreateBodyOwnersMax)+ .optional()+ .describe(+ "User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners."+ ),files: zod.array(zod.object({@@ -68,7 +77,7 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod.optional().describe('Bundled files to include with the initial version (scripts, references, assets).'),})- .describe('Create serializer — accepts bundled files as write-only input on POST.')+ .describe('Create serializer — accepts bundled files and owners as write-only input on POST.')export const LlmSkillsImportCreateBody = /* @__PURE__ */ zod.object({file: zod@@ -107,6 +116,8 @@ export const llmSkillsNamePartialUpdateBodyFilesItemContentTypeMax = 100export const llmSkillsNamePartialUpdateBodyFileEditsItemPathMax = 500+export const llmSkillsNamePartialUpdateBodyOwnersMax = 25+export const LlmSkillsNamePartialUpdateBody = /* @__PURE__ */ zod.object({body: zod.string()@@ -187,11 +198,20 @@ export const LlmSkillsNamePartialUpdateBody = /* @__PURE__ */ zod.object({.describe("Per-file find\/replace updates. Each entry targets one existing file by path and applies sequential edits to its content. Non-targeted files carry forward unchanged. Cannot add, remove, or rename files — use 'files' for that. Mutually exclusive with files."),+ owners: zod+ .array(zod.uuid())+ .max(llmSkillsNamePartialUpdateBodyOwnersMax)+ .optional()+ .describe(+ "Replace the skill's owners with these user UUIDs (each a member of this project). Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the logical skill, so setting them is independent of the version being published — a body edit alone never changes ownership."+ ),base_version: zod.number().min(1).optional()- .describe('Latest version you are editing from. Used for optimistic concurrency checks.'),+ .describe(+ 'Latest version you are editing from. Used for optimistic concurrency checks. Required when publishing content changes; optional for an owner-only update (when omitted, owners are replaced without a concurrency check).'+ ),})export const llmSkillsNameDuplicateCreateBodyNewNameMax = 64diff --git a/products/skills/mcp/tools.yaml b/products/skills/mcp/tools.yamlindex d21d4be75fa0..a05317c07823 100644--- a/products/skills/mcp/tools.yaml+++ b/products/skills/mcp/tools.yaml@@ -50,7 +50,9 @@ tools:description: >Create a new agent skill. Requires a unique kebab-case name (lowercase letters, numbers, hyphens), adescription explaining when to use it, and the skill body (SKILL.md instruction content as markdown).- Optionally include license, compatibility, allowed_tools, metadata, and bundled files.+ Optionally include license, compatibility, allowed_tools, metadata, bundled files, and owners. Owners (a+ list of project-member user UUIDs) default to the creating user; set them to route reviews or questions+ about this skill to specific people.include_params:- name- description@@ -60,6 +62,7 @@ tools:- allowed_tools- metadata- files+ - ownersskill-duplicate:operation: llm_skills_name_duplicate_createenabled: true@@ -229,6 +232,11 @@ tools:Passing a 'files' list here replaces ALL files and risks data loss if any file isomitted — use it only when you intentionally want to replace the entire bundle.++ To change who owns the skill, pass 'owners' (a list of project-member user UUIDs) —+ this replaces the owner set. Omit it to leave owners unchanged; pass an empty list to+ clear them. Ownership is independent of the version, so a body edit alone never+ changes it.include_params:- body- edits@@ -239,4 +247,5 @@ tools:- metadata- files- file_edits+ - owners- base_versiondiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex f1aed7a07e70..30763ea9e50a 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8531,7 +8531,7 @@}},"skill-create": {- "description": "Create a new agent skill. Requires a unique kebab-case name (lowercase letters, numbers, hyphens), a description explaining when to use it, and the skill body (SKILL.md instruction content as markdown). Optionally include license, compatibility, allowed_tools, metadata, and bundled files.",+ "description": "Create a new agent skill. Requires a unique kebab-case name (lowercase letters, numbers, hyphens), a description explaining when to use it, and the skill body (SKILL.md instruction content as markdown). Optionally include license, compatibility, allowed_tools, metadata, bundled files, and owners. Owners (a list of project-member user UUIDs) default to the creating user; set them to route reviews or questions about this skill to specific people.","category": "Skills","feature": "skills","summary": "Create skill",@@ -8657,7 +8657,7 @@}},"skill-update": {- "description": "Publish a new version of an existing agent skill by name. Any field not provided\nis carried forward from the current latest version. Requires base_version for\noptimistic concurrency.\n\nFor the body, you can either provide the full content via 'body', or use 'edits'\nfor incremental find/replace updates. Each edit must have 'old' (text to find,\nmust match exactly once) and 'new' (replacement text). Edits are applied\nsequentially. Only one of 'body' or 'edits' may be provided.\n\nFor file changes, prefer the per-file tools rather than passing a 'files' list:\nskill-file-create / skill-file-delete / skill-file-rename handle\nadd/remove/rename one file at a time and return the updated skill (including the\nbumped version) so callers can chain further edits via base_version.\n\nFor per-file content updates, use 'file_edits' to apply find/replace updates to\nindividual files without resending the full file set — each entry targets one\nexisting file by path. Non-targeted files carry forward unchanged. 'file_edits'\ncannot add, remove, or rename files; use the per-file tools or 'files' (replace-all)\nfor that. 'files' and 'file_edits' are mutually exclusive.\n\nPassing a 'files' list here replaces ALL files and risks data loss if any file is\nomitted — use it only when you intentionally want to replace the entire bundle.",+ "description": "Publish a new version of an existing agent skill by name. Any field not provided\nis carried forward from the current latest version. Requires base_version for\noptimistic concurrency.\n\nFor the body, you can either provide the full content via 'body', or use 'edits'\nfor incremental find/replace updates. Each edit must have 'old' (text to find,\nmust match exactly once) and 'new' (replacement text). Edits are applied\nsequentially. Only one of 'body' or 'edits' may be provided.\n\nFor file changes, prefer the per-file tools rather than passing a 'files' list:\nskill-file-create / skill-file-delete / skill-file-rename handle\nadd/remove/rename one file at a time and return the updated skill (including the\nbumped version) so callers can chain further edits via base_version.\n\nFor per-file content updates, use 'file_edits' to apply find/replace updates to\nindividual files without resending the full file set — each entry targets one\nexisting file by path. Non-targeted files carry forward unchanged. 'file_edits'\ncannot add, remove, or rename files; use the per-file tools or 'files' (replace-all)\nfor that. 'files' and 'file_edits' are mutually exclusive.\n\nPassing a 'files' list here replaces ALL files and risks data loss if any file is\nomitted — use it only when you intentionally want to replace the entire bundle.\n\nTo change who owns the skill, pass 'owners' (a list of project-member user UUIDs) —\nthis replaces the owner set. Omit it to leave owners unchanged; pass an empty list to\nclear them. Ownership is independent of the version, so a body edit alone never\nchanges it.","category": "Skills","feature": "skills","summary": "Update skill",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex b34377925897..8e47ef334924 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -9096,7 +9096,7 @@}},"skill-create": {- "description": "Create a new agent skill. Requires a unique kebab-case name (lowercase letters, numbers, hyphens), a description explaining when to use it, and the skill body (SKILL.md instruction content as markdown). Optionally include license, compatibility, allowed_tools, metadata, and bundled files.",+ "description": "Create a new agent skill. Requires a unique kebab-case name (lowercase letters, numbers, hyphens), a description explaining when to use it, and the skill body (SKILL.md instruction content as markdown). Optionally include license, compatibility, allowed_tools, metadata, bundled files, and owners. Owners (a list of project-member user UUIDs) default to the creating user; set them to route reviews or questions about this skill to specific people.","category": "Skills","feature": "skills","summary": "Create skill",@@ -9222,7 +9222,7 @@}},"skill-update": {- "description": "Publish a new version of an existing agent skill by name. Any field not provided\nis carried forward from the current latest version. Requires base_version for\noptimistic concurrency.\n\nFor the body, you can either provide the full content via 'body', or use 'edits'\nfor incremental find/replace updates. Each edit must have 'old' (text to find,\nmust match exactly once) and 'new' (replacement text). Edits are applied\nsequentially. Only one of 'body' or 'edits' may be provided.\n\nFor file changes, prefer the per-file tools rather than passing a 'files' list:\nskill-file-create / skill-file-delete / skill-file-rename handle\nadd/remove/rename one file at a time and return the updated skill (including the\nbumped version) so callers can chain further edits via base_version.\n\nFor per-file content updates, use 'file_edits' to apply find/replace updates to\nindividual files without resending the full file set — each entry targets one\nexisting file by path. Non-targeted files carry forward unchanged. 'file_edits'\ncannot add, remove, or rename files; use the per-file tools or 'files' (replace-all)\nfor that. 'files' and 'file_edits' are mutually exclusive.\n\nPassing a 'files' list here replaces ALL files and risks data loss if any file is\nomitted — use it only when you intentionally want to replace the entire bundle.",+ "description": "Publish a new version of an existing agent skill by name. Any field not provided\nis carried forward from the current latest version. Requires base_version for\noptimistic concurrency.\n\nFor the body, you can either provide the full content via 'body', or use 'edits'\nfor incremental find/replace updates. Each edit must have 'old' (text to find,\nmust match exactly once) and 'new' (replacement text). Edits are applied\nsequentially. Only one of 'body' or 'edits' may be provided.\n\nFor file changes, prefer the per-file tools rather than passing a 'files' list:\nskill-file-create / skill-file-delete / skill-file-rename handle\nadd/remove/rename one file at a time and return the updated skill (including the\nbumped version) so callers can chain further edits via base_version.\n\nFor per-file content updates, use 'file_edits' to apply find/replace updates to\nindividual files without resending the full file set — each entry targets one\nexisting file by path. Non-targeted files carry forward unchanged. 'file_edits'\ncannot add, remove, or rename files; use the per-file tools or 'files' (replace-all)\nfor that. 'files' and 'file_edits' are mutually exclusive.\n\nPassing a 'files' list here replaces ALL files and risks data loss if any file is\nomitted — use it only when you intentionally want to replace the entire bundle.\n\nTo change who owns the skill, pass 'owners' (a list of project-member user UUIDs) —\nthis replaces the owner set. Omit it to leave owners unchanged; pass an empty list to\nclear them. Ownership is independent of the version, so a body edit alone never\nchanges it.","category": "Skills","feature": "skills","summary": "Update skill",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f35ebf631282..5f15b5dc8572 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36362,6 +36362,8 @@ export namespace Schemas {metadata?: LLMSkillMetadata;/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string;+ /** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */+ readonly owners: readonly UserBasic[];/** Bundled files manifest. Each entry carries path, content_type, and line/char counts — no content; fetch content via /llm_skills/name/{name}/files/{path}/. */readonly files: readonly LLMSkillFileManifest[];/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */@@ -36398,7 +36400,7 @@ export namespace Schemas {}/**- * Create serializer — accepts bundled files as write-only input on POST.+ * Create serializer — accepts bundled files and owners as write-only input on POST.*/export interface LLMSkillCreate {readonly id: string;@@ -36437,6 +36439,11 @@ export namespace Schemas {metadata?: LLMSkillCreateMetadata;/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string;+ /**+ * User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners.+ * @maxItems 25+ */+ owners?: string[];/** Bundled files to include with the initial version (scripts, references, assets). */files?: LLMSkillFileInput[];/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */@@ -36564,6 +36571,8 @@ export namespace Schemas {metadata?: LLMSkillListMetadata;/** Server-owned classification — set by the producing system (the Signals harness stamps "scout"), not writable via the API. Empty for an ordinary skill. Groups skills into their own surface (e.g. the Scouts tab) independently of the skill name. */readonly category: string;+ /** Users who own this skill, seed-creator first. Ownership is keyed on the logical skill (not a version), so it's stable across edits. Prefer this over created_by to learn who to route reviews or questions to. Set via the owners field on create/update (a list of user UUIDs). Empty for scout sandbox fetches of skills that haven't opted into the report channel. */+ readonly owners: readonly UserBasic[];/** Flat list of markdown headings parsed from the skill body. Useful as a lightweight table of contents. */readonly outline: readonly LLMSkillOutlineEntry[];readonly version: number;@@ -49167,7 +49176,12 @@ export namespace Schemas {/** Per-file find/replace updates. Each entry targets one existing file by path and applies sequential edits to its content. Non-targeted files carry forward unchanged. Cannot add, remove, or rename files — use 'files' for that. Mutually exclusive with files. */file_edits?: LLMSkillFileEdit[];/**- * Latest version you are editing from. Used for optimistic concurrency checks.+ * Replace the skill's owners with these user UUIDs (each a member of this project). Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the logical skill, so setting them is independent of the version being published — a body edit alone never changes ownership.+ * @maxItems 25+ */+ owners?: string[];+ /**+ * Latest version you are editing from. Used for optimistic concurrency checks. Required when publishing content changes; optional for an owner-only update (when omitted, owners are replaced without a concurrency check).* @minimum 1*/base_version?: number;diff --git a/services/mcp/src/generated/skills/api.ts b/services/mcp/src/generated/skills/api.tsindex de4d886a9d63..575b12d001d5 100644--- a/services/mcp/src/generated/skills/api.ts+++ b/services/mcp/src/generated/skills/api.ts@@ -45,6 +45,8 @@ export const llmSkillsCreateBodyLicenseMax = 255export const llmSkillsCreateBodyCompatibilityMax = 500+export const llmSkillsCreateBodyOwnersMax = 25+export const llmSkillsCreateBodyFilesItemPathMax = 500export const llmSkillsCreateBodyFilesItemContentTypeDefault = `text/plain`@@ -76,6 +78,13 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod.optional().describe('List of pre-approved tools the skill may use. Tool names cannot contain whitespace.'),metadata: zod.record(zod.string(), zod.unknown()).optional().describe('Arbitrary key-value metadata.'),+ owners: zod+ .array(zod.string())+ .max(llmSkillsCreateBodyOwnersMax)+ .optional()+ .describe(+ "User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners."+ ),files: zod.array(zod.object({@@ -96,7 +105,7 @@ export const LlmSkillsCreateBody = /* @__PURE__ */ zod.optional().describe('Bundled files to include with the initial version (scripts, references, assets).'),})- .describe('Create serializer — accepts bundled files as write-only input on POST.')+ .describe('Create serializer — accepts bundled files and owners as write-only input on POST.')/*** Mint the user's read-only marketplace credential (or rotate it) and return the install command.@@ -181,6 +190,8 @@ export const llmSkillsNamePartialUpdateBodyFilesItemContentTypeMax = 100export const llmSkillsNamePartialUpdateBodyFileEditsItemPathMax = 500+export const llmSkillsNamePartialUpdateBodyOwnersMax = 25+export const LlmSkillsNamePartialUpdateBody = /* @__PURE__ */ zod.object({body: zod.string()@@ -261,11 +272,20 @@ export const LlmSkillsNamePartialUpdateBody = /* @__PURE__ */ zod.object({.describe("Per-file find\/replace updates. Each entry targets one existing file by path and applies sequential edits to its content. Non-targeted files carry forward unchanged. Cannot add, remove, or rename files — use 'files' for that. Mutually exclusive with files."),+ owners: zod+ .array(zod.string())+ .max(llmSkillsNamePartialUpdateBodyOwnersMax)+ .optional()+ .describe(+ "Replace the skill's owners with these user UUIDs (each a member of this project). Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the logical skill, so setting them is independent of the version being published — a body edit alone never changes ownership."+ ),base_version: zod.number().min(1).optional()- .describe('Latest version you are editing from. Used for optimistic concurrency checks.'),+ .describe(+ 'Latest version you are editing from. Used for optimistic concurrency checks. Required when publishing content changes; optional for an owner-only update (when omitted, owners are replaced without a concurrency check).'+ ),})export const llmSkillsNameArchiveCreatePathSkillNameRegExp = new RegExp('^[^\/]+$')diff --git a/services/mcp/src/tools/generated/skills.ts b/services/mcp/src/tools/generated/skills.tsindex 8bdf52a0c2e3..5eeba000583a 100644--- a/services/mcp/src/tools/generated/skills.ts+++ b/services/mcp/src/tools/generated/skills.ts@@ -45,7 +45,7 @@ const skillArchive = (): ToolBase<typeof SkillArchiveSchema, unknown> => ({const SkillCreateSchema = LlmSkillsCreateBody-const skillCreate = (): ToolBase<typeof SkillCreateSchema, Schemas.LLMSkillCreate> => ({+const skillCreate = (): ToolBase<typeof SkillCreateSchema, Schemas.LLMSkill> => ({name: 'skill-create',schema: SkillCreateSchema,handler: async (context: Context, params: z.infer<typeof SkillCreateSchema>) => {@@ -72,10 +72,13 @@ const skillCreate = (): ToolBase<typeof SkillCreateSchema, Schemas.LLMSkillCreatif (params.metadata !== undefined) {body['metadata'] = params.metadata}+ if (params.owners !== undefined) {+ body['owners'] = params.owners+ }if (params.files !== undefined) {body['files'] = params.files}- const result = await context.api.request<Schemas.LLMSkillCreate>({+ const result = await context.api.request<Schemas.LLMSkill>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/llm_skills/`,body,@@ -313,6 +316,9 @@ const skillUpdate = (): ToolBase<typeof SkillUpdateSchema, Schemas.LLMSkill> =>if (params.file_edits !== undefined) {body['file_edits'] = params.file_edits}+ if (params.owners !== undefined) {+ body['owners'] = params.owners+ }if (params.base_version !== undefined) {body['base_version'] = params.base_version}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.jsonindex 3efc490b4c23..432957fba576 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-create.json@@ -1,6 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema",- "description": "Create serializer — accepts bundled files as write-only input on POST.",+ "description": "Create serializer — accepts bundled files and owners as write-only input on POST.","properties": {"allowed_tools": {"description": "List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",@@ -65,6 +65,14 @@"description": "Unique skill name. Lowercase letters, numbers, and hyphens only. Max 64 characters.","maxLength": 64,"type": "string"+ },+ "owners": {+ "description": "User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners.",+ "items": {+ "type": "string"+ },+ "maxItems": 25,+ "type": "array"}},"required": ["name", "description", "body"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.jsonindex 170874d0e23f..8cb4ccedaa95 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-skill-update.json@@ -9,7 +9,7 @@"type": "array"},"base_version": {- "description": "Latest version you are editing from. Used for optimistic concurrency checks.",+ "description": "Latest version you are editing from. Used for optimistic concurrency checks. Required when publishing content changes; optional for an owner-only update (when omitted, owners are replaced without a concurrency check).","minimum": 1,"type": "number"},@@ -116,6 +116,14 @@},"type": "object"},+ "owners": {+ "description": "Replace the skill's owners with these user UUIDs (each a member of this project). Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the logical skill, so setting them is independent of the version being published — a body edit alone never changes ownership.",+ "items": {+ "type": "string"+ },+ "maxItems": 25,+ "type": "array"+ },"skill_name": {"pattern": "^[^/]+$","type": "string"diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.jsonindex 3efc490b4c23..432957fba576 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-create.json@@ -1,6 +1,6 @@{"$schema": "https://json-schema.org/draft/2020-12/schema",- "description": "Create serializer — accepts bundled files as write-only input on POST.",+ "description": "Create serializer — accepts bundled files and owners as write-only input on POST.","properties": {"allowed_tools": {"description": "List of pre-approved tools the skill may use. Tool names cannot contain whitespace.",@@ -65,6 +65,14 @@"description": "Unique skill name. Lowercase letters, numbers, and hyphens only. Max 64 characters.","maxLength": 64,"type": "string"+ },+ "owners": {+ "description": "User UUIDs to set as the skill's owners. Each must be a member of this project. Defaults to the creating user when omitted; pass an empty list to create with no owners.",+ "items": {+ "type": "string"+ },+ "maxItems": 25,+ "type": "array"}},"required": ["name", "description", "body"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.jsonindex 170874d0e23f..8cb4ccedaa95 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/skill-update.json@@ -9,7 +9,7 @@"type": "array"},"base_version": {- "description": "Latest version you are editing from. Used for optimistic concurrency checks.",+ "description": "Latest version you are editing from. Used for optimistic concurrency checks. Required when publishing content changes; optional for an owner-only update (when omitted, owners are replaced without a concurrency check).","minimum": 1,"type": "number"},@@ -116,6 +116,14 @@},"type": "object"},+ "owners": {+ "description": "Replace the skill's owners with these user UUIDs (each a member of this project). Omit to leave owners unchanged; pass an empty list to clear them. Owners are keyed on the logical skill, so setting them is independent of the version being published — a body edit alone never changes ownership.",+ "items": {+ "type": "string"+ },+ "maxItems": 25,+ "type": "array"+ },"skill_name": {"pattern": "^[^/]+$","type": "string"