Repository navigation
feat(skills): let staff make skills visible to everyone - #71359
ceyniustranberg wants to merge 3 commits into
Conversation
Adds a staff-only visibility action (POST llm_skills/name/<name>/visibility) that flips is_global across every version of a skill, and broadens the read paths so a global skill surfaces in every team's list, by-name resolution, marketplace git clone, and MCP skill-list — with a team's own same-named skill shadowing the global. Writes stay owner-scoped, so a non-owner can't edit or archive a global (it 404s). Exposes is_global and team_id read-only on the serializer (regenerated types included) so the UI can tell ownership. Generated-By: PostHog Code Task-Id: ff3f8fe9-0598-414b-b8b7-617108960d53
🤖 CI report✅ Bundle size — no changeUncompressed size of every built Total: 64.77 MiB · no change No file changed by more than 1000 B. Posted automatically by build-bundle-size-report · uncompressed bytes from dist-report ✅ Eager graph — within budgetHow much code each root ships on the eager path — downloaded and parsed before the surface is interactive. Measured from the esbuild output chunks (post-tree-shake, static imports only); lazy
🟢 Largest files eagerly shipped from
|
| Size | File |
|---|---|
| 126.8 KiB | ../node_modules/.pnpm/react-dom@18.3.1_react@18.3.1/node_modules/react-dom/cjs/react-dom.production.min.js |
| 24.6 KiB | ../node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js |
| 6.3 KiB | ../node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js |
| 4.5 KiB | ../node_modules/.pnpm/@jspm+core@2.1.0/node_modules/@jspm/core/nodelibs/browser/process.js |
| 3.9 KiB | ../node_modules/.pnpm/scheduler@0.23.2/node_modules/scheduler/cjs/scheduler.production.min.js |
| 1.4 KiB | ../node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js |
| 1.3 KiB | src/RootErrorBoundary.tsx |
| 912 B | ../node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js |
| 789 B | src/scenes/ChunkLoadErrorBoundary.tsx |
| 762 B | src/index.tsx |
Largest files eagerly shipped from src/scenes/AuthenticatedShell.tsx
| Size | File |
|---|---|
| 281.3 KiB | ../node_modules/.pnpm/posthog-js@1.402.2/node_modules/posthog-js/dist/rrweb.js |
| 267.7 KiB | ../node_modules/.pnpm/@posthog+icons@0.38.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/@posthog/icons/dist/posthog-icons.es.js |
| 235.5 KiB | src/taxonomy/core-filter-definitions-by-group.json |
| 222.9 KiB | ../node_modules/.pnpm/posthog-js@1.402.2/node_modules/posthog-js/dist/module.js |
| 164.0 KiB | src/queries/validators.js |
| 154.3 KiB | ../node_modules/.pnpm/re2js@0.4.1/node_modules/re2js/build/index.esm.js |
| 126.8 KiB | ../node_modules/.pnpm/react-dom@18.3.1_react@18.3.1/node_modules/react-dom/cjs/react-dom.production.min.js |
| 105.8 KiB | src/lib/api.ts |
| 93.3 KiB | ../node_modules/.pnpm/prosemirror-view@1.40.1/node_modules/prosemirror-view/dist/index.js |
| 92.7 KiB | ../packages/quill/packages/quill/dist/index.js |
Posted automatically by check-eager-graph · sizes are eager output bytes (shipped, post-tree-shake) from the esbuild metafile · part of #32479
✅ Dist folder size — 🔺 +1007 B (+0.0%)
Total size of the built frontend/dist folder (all assets), compared against the base branch.
Total: 1312.45 MiB · 🔺 +1007 B (+0.0%)
ℹ️ MCP UI apps size — 31 app(s), 16561.5 KB JS
Built size of each MCP UI app (main.js + styles.css).
| App | JS | CSS |
|---|---|---|
| debug | 598.2 KB | 179.2 KB |
| action | 456.5 KB | 179.2 KB |
| action-list | 563.0 KB | 179.2 KB |
| cohort | 455.4 KB | 179.2 KB |
| cohort-list | 562.0 KB | 179.2 KB |
| email-template | 455.3 KB | 179.2 KB |
| error-details | 471.1 KB | 179.2 KB |
| error-issue | 456.1 KB | 179.2 KB |
| error-issue-list | 562.9 KB | 179.2 KB |
| experiment | 560.1 KB | 179.2 KB |
| experiment-list | 563.8 KB | 179.2 KB |
| experiment-results | 561.8 KB | 179.2 KB |
| feature-flag | 565.8 KB | 179.2 KB |
| feature-flag-list | 569.5 KB | 179.2 KB |
| feature-flag-testing | 459.4 KB | 179.2 KB |
| insight-actors | 560.8 KB | 179.2 KB |
| invite-email-preview | 454.7 KB | 179.2 KB |
| llm-costs | 558.1 KB | 179.2 KB |
| session-recording | 457.2 KB | 179.2 KB |
| session-summary | 462.5 KB | 179.2 KB |
| survey | 457.0 KB | 179.2 KB |
| survey-global-stats | 560.9 KB | 179.2 KB |
| survey-list | 563.7 KB | 179.2 KB |
| survey-stats | 560.8 KB | 179.2 KB |
| trace-span | 455.8 KB | 179.2 KB |
| trace-span-list | 562.9 KB | 179.2 KB |
| workflow | 455.8 KB | 179.2 KB |
| workflow-list | 562.4 KB | 179.2 KB |
| query-results | 743.7 KB | 179.2 KB |
| render-ui | 824.0 KB | 179.2 KB |
| visual-review-snapshots | 460.3 KB | 179.2 KB |
⚠️ Backend coverage — 96.0% of changed backend lines covered — 8 uncovered
🧪 Backend test coverage
Patch coverage — changed backend lines (products + core): ███████████████████░ 96.0% (254 / 262)
| File | Patch | Uncovered changed lines |
|---|---|---|
products/skills/backend/api/skill_services.py |
81.2% | 131–133, 135, 159, 647 |
products/skills/backend/api/skill_serializers.py |
95.0% | 39 |
products/skills/backend/api/skills.py |
96.4% | 835 |
🤖 Agents: add a test covering the lines above, or note why under "How did you test this code?". Machine-readable gap list: the patch-coverage artifact on this run (gh run download 33065269187 -n patch-coverage), or the coverage-data block at the end of this comment.
Per-product line coverage (touched products)
| Product | Coverage | Lines |
|---|---|---|
platform_features |
██░░░░░░░░░░░░░░░░░░ 12.1% |
7 / 58 |
batch_exports |
████████░░░░░░░░░░░░ 39.7% |
8,425 / 21,220 |
demo |
███████████░░░░░░░░░ 56.2% |
1,497 / 2,663 |
warehouse_sources_queue |
████████████░░░░░░░░ 59.2% |
148 / 250 |
tasks |
█████████████░░░░░░░ 67.5% |
25,563 / 37,895 |
data_tools |
██████████████░░░░░░ 70.0% |
63 / 90 |
ai_gateway |
███████████████░░░░░ 75.0% |
9 / 12 |
signals |
████████████████░░░░ 79.1% |
19,049 / 24,073 |
data_modeling |
████████████████░░░░ 80.0% |
4,834 / 6,045 |
cdp |
████████████████░░░░ 80.7% |
3,118 / 3,864 |
wizard |
████████████████░░░░ 82.5% |
772 / 936 |
notebooks |
█████████████████░░░ 84.3% |
6,343 / 7,520 |
agent_platform |
█████████████████░░░ 84.7% |
3,273 / 3,862 |
cohorts |
█████████████████░░░ 86.1% |
4,022 / 4,671 |
actions |
█████████████████░░░ 86.6% |
717 / 828 |
product_tours |
█████████████████░░░ 87.5% |
1,266 / 1,447 |
exports |
██████████████████░░ 88.3% |
6,891 / 7,800 |
visual_review |
██████████████████░░ 88.5% |
5,565 / 6,287 |
business_knowledge |
██████████████████░░ 88.5% |
4,400 / 4,969 |
conversations |
██████████████████░░ 89.1% |
16,149 / 18,133 |
mcp_analytics |
██████████████████░░ 89.1% |
2,502 / 2,807 |
dashboards |
██████████████████░░ 89.2% |
5,725 / 6,418 |
error_tracking |
██████████████████░░ 89.6% |
9,718 / 10,852 |
alerts |
██████████████████░░ 89.9% |
3,638 / 4,046 |
engineering_analytics |
██████████████████░░ 90.1% |
5,105 / 5,665 |
streamlit_apps |
██████████████████░░ 90.4% |
2,499 / 2,764 |
slack_app |
██████████████████░░ 90.6% |
9,511 / 10,503 |
links |
██████████████████░░ 90.6% |
183 / 202 |
marketing_analytics |
██████████████████░░ 90.8% |
11,514 / 12,684 |
product_analytics |
██████████████████░░ 91.1% |
5,599 / 6,143 |
managed_migrations |
██████████████████░░ 91.9% |
908 / 988 |
data_warehouse |
██████████████████░░ 92.1% |
18,133 / 19,683 |
mcp_store |
██████████████████░░ 92.2% |
3,682 / 3,995 |
workflows |
██████████████████░░ 92.4% |
5,148 / 5,574 |
notifications |
███████████████████░ 92.7% |
1,026 / 1,107 |
web_analytics |
███████████████████░ 92.8% |
13,627 / 14,691 |
surveys |
███████████████████░ 92.9% |
5,660 / 6,094 |
ai_observability |
███████████████████░ 93.0% |
14,894 / 16,019 |
posthog_ai |
███████████████████░ 93.2% |
1,322 / 1,418 |
tracing |
███████████████████░ 93.3% |
2,435 / 2,611 |
approvals |
███████████████████░ 93.3% |
3,395 / 3,640 |
reminders |
███████████████████░ 93.4% |
468 / 501 |
warehouse_sources |
███████████████████░ 93.6% |
219,490 / 234,485 |
early_access_features |
███████████████████░ 93.8% |
848 / 904 |
legal_documents |
███████████████████░ 94.1% |
1,568 / 1,667 |
endpoints |
███████████████████░ 94.1% |
8,606 / 9,143 |
revenue_analytics |
███████████████████░ 94.5% |
3,598 / 3,809 |
messaging |
███████████████████░ 94.5% |
2,530 / 2,677 |
review_hog |
███████████████████░ 94.6% |
6,529 / 6,902 |
skills |
███████████████████░ 95.1% |
3,076 / 3,236 |
logs |
███████████████████░ 95.3% |
9,528 / 9,994 |
experiments |
███████████████████░ 95.7% |
24,170 / 25,256 |
growth |
███████████████████░ 95.8% |
2,836 / 2,959 |
replay_vision |
███████████████████░ 95.9% |
13,357 / 13,935 |
annotations |
███████████████████░ 96.2% |
732 / 761 |
feature_flags |
███████████████████░ 96.3% |
16,002 / 16,625 |
user_interviews |
███████████████████░ 96.4% |
2,242 / 2,325 |
access_control |
███████████████████░ 96.8% |
849 / 877 |
data_catalog |
███████████████████░ 97.1% |
2,035 / 2,095 |
customer_analytics |
███████████████████░ 97.2% |
7,480 / 7,698 |
analytics_platform |
████████████████████ 98.0% |
2,102 / 2,145 |
metrics |
████████████████████ 98.2% |
2,404 / 2,448 |
live_debugger |
████████████████████ 99.2% |
613 / 618 |
field_notes |
████████████████████ 99.4% |
158 / 159 |
Report-only. Patch coverage = changed backend lines covered vs origin/master. Sorted lowest first.
Known gaps: lines covered only by Temporal tests show as uncovered; core line numbers may drift if master changed the same file.
✅ Django migration risk — migration analysis complete
We've analyzed your migrations for potential risks.
Summary: 11 Safe | 4 Needs Review | 0 Blocked
⚠️ Needs Review
May have performance impact
agent_platform.0002_alter_agentapplication_slug
└─ #1 ⚠️ AlterField
Field alteration may cause table locks or data loss (check if changing type or constraints)
model: agentapplication, field: slug, field_type: SlugField
agent_platform.0003_agentapplication_global_slug_unique
└─ #1 ⚠️ RemoveConstraint: Unscored Django operation: RemoveConstraint (needs manual review)
└─ #2 ⚠️ AddConstraint
Adding constraint may lock table (use NOT VALID pattern)
model: agentapplication
agent_platform.0005_copy_encrypted_env_to_revisions
└─ #1 ⚠️ RunPython: RunPython data migration needs review for performance
agent_platform.0011_agentrevision_skill_refs
└─ #1 ⚠️ AddField
Adding NOT NULL field with callable default (list) - verify it's stable
model: agentrevision, field: skill_refs, default: list
✅ Safe
Brief or no lock, backwards compatible
agent_platform.0001_initial
└─ #1 ✅ CreateModel
Creating new table is safe
model: AgentApplication
└─ #2 ✅ CreateModel
Creating new table is safe
model: AgentRevision
└─ #3 ✅ AddField
Adding nullable field requires brief lock
model: agentapplication, field: live_revision
└─ #4 ✅ CreateModel
Creating new table is safe
model: AgentSandboxInstance
└─ #5 ✅ CreateModel
Creating new table is safe
model: AgentSession
└─ #6 ✅ CreateModel
Creating new table is safe
model: AgentSessionCredential
└─ #7 ✅ CreateModel
Creating new table is safe
model: AgentToolApprovalRequest
└─ #8 ✅ CreateModel
Creating new table is safe
model: AgentUser
│
└──> ℹ️ INFO:
ℹ️ Skipped operations on newly created tables (empty tables
don't cause lock contention).
agent_platform.0004_agentrevision_encrypted_env
└─ #1 ✅ AddField
Adding nullable field requires brief lock
model: agentrevision, field: encrypted_env
agent_platform.0006_remove_agentapplication_encrypted_env
└─ #1 ✅ SeparateDatabaseAndState: Only state operations (no database changes)
agent_platform.0007_agent_identity_linking
└─ #1 ✅ CreateModel
Creating new table is safe
model: AgentIdentityCredential
└─ #2 ✅ CreateModel
Creating new table is safe
model: AgentIdentityLinkState
│
└──> ℹ️ INFO:
ℹ️ Skipped operations on newly created tables (empty tables
don't cause lock contention).
agent_platform.0008_agent_identity_subject
└─ #1 ✅ SeparateDatabaseAndState: Only state operations (no database changes)
└─ #2 ✅ AddField
Adding nullable field requires brief lock
model: agentidentitycredential, field: subject
agent_platform.0009_agentsession_agenttoolapprovalrequest_is_preview
└─ #1 ✅ AddField
Adding NOT NULL field with constant default (safe in PG11+)
model: agentsession, field: is_preview
└─ #2 ✅ AddField
Adding NOT NULL field with constant default (safe in PG11+)
model: agenttoolapprovalrequest, field: is_preview
agent_platform.0010_remove_is_preview_state_only
└─ #1 ✅ SeparateDatabaseAndState: Only state operations (no database changes)
agent_platform.0012_agentsession_search_text_turn_count
└─ #1 ✅ AddField
Adding nullable field requires brief lock
model: agentsession, field: search_text
└─ #2 ✅ AddField
Adding NOT NULL field with constant default (safe in PG11+)
model: agentsession, field: turn_count
agent_platform.0013_agent_transport_binding
└─ #1 ✅ CreateModel
Creating new table is safe
model: AgentTransportBinding
│
└──> ℹ️ INFO:
ℹ️ Skipped operations on newly created tables (empty tables
don't cause lock contention).
skills.0004_llmskill_is_global
└─ #1 ✅ AddField
Adding NOT NULL field with constant default (safe in PG11+)
model: llmskill, field: is_global
skills.0005_llmskill_global_latest_index
└─ #1 ✅ SafeAddIndexConcurrently
PostHog concurrent-index helper: idempotent (timeout disabling + invalid-leftover recovery)
model: llmskill, index: llm_skill_global_latest
📚 How to Deploy These Changes Safely
AddConstraint:
Add constraints in 2 phases without locking, using the PostHog helpers:
-
AddConstraintNotValid (instant, validates new rows only, no table scan)
-
ValidateConstraint in a separate migration (scans table with non-blocking lock)
from posthog.migration_helpers import AddConstraintNotValid, ValidateConstraint
See the migration safety guide
AddField:
This operation acquires a brief lock but doesn't rewrite the table.
Deployment uses lock timeouts with automatic retries, so lock contention will cause retries rather than connection pile-up.
RunPython:
Use batching for large data migrations:
- Use
.iterator()to avoid loading all rows into memory - Use
.bulk_update()instead of saving individual objects - Batch size: 1,000-10,000 rows per batch
- Add pauses between batches
- Consider background jobs for very large updates (millions of rows)
See the migration safety guide
Last updated: 2026-08-19 08:16 UTC (18d5774)
🦔 Hogbox preview · ✅ ready▶ Open the preview
commit |
| category=current_latest.category, | ||
| # Visibility is likewise a property of the skill, not the version — carry it forward so | ||
| # publishing a new version of a global skill keeps it visible to everyone. | ||
| is_global=current_latest.is_global, |
There was a problem hiding this comment.
Keep global skills staff-controlled after publication
A staff member can make an ordinary tenant-owned skill global, but its tenant editors can subsequently publish arbitrary new bodies or files without a staff check. The newly created version retains is_global=True and is then distributed through the cross-team API, MCP tools, and marketplace clone. This turns a one-time staff publication into an ongoing cross-tenant content-poisoning path; skill bodies are consumed as agent instructions and bundled files can be fetched by every consuming team.
Prompt To Fix With AI
Make global publication immutable to non-staff writers. For every body/file update path, either require a staff authorization check when the current skill is global, or create the new version with is_global=False so it must be explicitly reviewed and republished. Apply the same rule to publish_skill_version and _create_next_version_with_files, and add regression tests showing a non-staff owner cannot alter content distributed as global.Severity: high | Confidence: 91% | React with 👍 if useful or 👎 if not
| queryset = get_latest_skills_queryset(self.team) | ||
| # Global skills (staff-published, owned by another team) surface in every team's list, | ||
| # read-only; a team's own same-named skill shadows the global (handled in the service layer). | ||
| queryset = get_latest_skills_queryset(self.team, include_global=True) |
There was a problem hiding this comment.
Do not expose global skill authors' user records
Global skills are serialized with LLMSkillSerializer, whose existing created_by = UserBasicSerializer returns the author’s email, UUID, distinct ID, name, verification status, and profile configuration. This new cross-team queryset therefore lets any member of any team enumerate those fields for the user who created a staff-published skill, including a customer user if staff globalizes their skill. Global visibility of skill content does not require disclosing the source tenant's user record.
Prompt To Fix With AI
Use a cross-tenant-safe skill representation for global rows. At minimum, omit or null `created_by` when `skill.team_id != requesting_team_id`; alternatively expose a deliberately minimal public attribution field with no user identifiers. Apply the same policy to the list, get-by-name, resolve/version summaries, export-related JSON, and MCP-facing serializers, and add a cross-team regression test asserting email/UUID/distinct_id are absent.Severity: medium | Confidence: 97% | React with 👍 if useful or 👎 if not
PR overviewThis pull request adds support for staff to make skills visible to everyone, touching the skills marketplace backend logic that determines which skill versions are available for discovery and cloning. One issue remains open: when a globally visible skill is later made private, marketplace caching can continue exposing an older globally cached version for cloning by users from other teams until the cache expires. The blast radius is limited to the affected skill and cache lifetime, and one prior issue has already been addressed, indicating the review findings are being worked down. Open issues (1)
Fixed/addressed: 1 · PR risk: 6/10 |
A global skill is readable across teams, but its created_by (the publishing PostHog staff member's name and email) was being serialized to every consuming customer. Mask created_by to null on a global skill when viewed by a team that doesn't own it — on the detail, list, and resolve (version history) paths. The owning team still sees it. Also add parametrized tests locking the write-path IDOR boundary: a non-owner cannot publish or add files to a global skill (they 404), matching the existing archive coverage. Generated-By: PostHog Code Task-Id: 72b94215-b225-45c6-b3be-2de5433abb8b
| latest = get_active_skill_queryset(team).filter(name=skill_name, is_latest=True).first() | ||
| if latest is None: | ||
| raise LLMSkillNotFoundError() | ||
| return latest |
There was a problem hiding this comment.
Race condition: latest fetch happens outside the transaction after the visibility update completes. If the skill is deleted or modified between the transaction commit (line 644) and this query (line 645), the function will raise LLMSkillNotFoundError despite successfully updating the visibility. This will return a 404 to the user even though the visibility change was persisted.
# Fix: Move the latest fetch inside the transaction
with transaction.atomic():
rows = list(
LLMSkill.objects.select_for_update()
.filter(team=team, name=skill_name, deleted=False)
.values_list("pk", flat=True)
)
if not rows:
raise LLMSkillNotFoundError()
LLMSkill.objects.filter(team=team, name=skill_name, deleted=False).update(
is_global=is_global,
updated_at=timezone.now(),
)
latest = get_active_skill_queryset(team).filter(name=skill_name, is_latest=True).first()
if latest is None:
raise LLMSkillNotFoundError()
return latest| latest = get_active_skill_queryset(team).filter(name=skill_name, is_latest=True).first() | |
| if latest is None: | |
| raise LLMSkillNotFoundError() | |
| return latest | |
| with transaction.atomic(): | |
| rows = list( | |
| LLMSkill.objects.select_for_update() | |
| .filter(team=team, name=skill_name, deleted=False) | |
| .values_list("pk", flat=True) | |
| ) | |
| if not rows: | |
| raise LLMSkillNotFoundError() | |
| LLMSkill.objects.filter(team=team, name=skill_name, deleted=False).update( | |
| is_global=is_global, | |
| updated_at=timezone.now(), | |
| ) | |
| latest = get_active_skill_queryset(team).filter(name=skill_name, is_latest=True).first() | |
| if latest is None: | |
| raise LLMSkillNotFoundError() | |
| return latest | |
Spotted by Graphite
Is this helpful? React 👍 or 👎 to let us know.
| latest = LLMSkill.objects.filter(team=team).aggregate(latest=Max("updated_at"))["latest"] | ||
| # Globals are included (set_skill_visibility bumps their updated_at) so a team's clone re-versions | ||
| # when a skill it consumes becomes — or stops being — globally visible. | ||
| latest = LLMSkill.objects.filter(Q(team=team) | Q(is_global=True)).aggregate(latest=Max("updated_at"))["latest"] |
There was a problem hiding this comment.
Low: Revoked global skill remains in marketplace cache
When a global skill is made private, this query drops its newly bumped row and can return an earlier version that was already cached while the skill was global. A user from another team can then clone the revoked skill until that repository cache expires. Use a monotonic visibility-change token in the consumer cache key, or explicitly invalidate affected repository caches when removing global visibility.
🦔 ReviewHog reviewed this pull requestFound 0 must fix, 3 should fix, 0 consider. Published 3 findings (view the review). |
|
ReviewHog Alpha 🦔 If you find any issues helpful - please reply "valid", "invalid", etc., for evaluation purposes 🙏 |
There was a problem hiding this comment.
ReviewHog Report
Changes
Issues: 3 issues
Files (10)
products/skills/backend/api/skill_serializers.pyproducts/skills/backend/api/skill_services.pyproducts/skills/backend/api/skills.pyproducts/skills/backend/marketplace/adapters.pyproducts/skills/backend/tools/skills.pyproducts/skills/frontend/generated/api.schemas.tsproducts/skills/frontend/generated/api.tsproducts/skills/frontend/generated/api.zod.tsproducts/skills/mcp/tools.yamlservices/mcp/src/api/generated.ts
Other findings (outside the changed lines)
Valid issues on this PR's files that sit on lines GitHub won't let us comment on inline.
Global-skill inclusion in the marketplace plugin-version query defeats the only index built for it, growing unbounded with total skill history across all teams
Priority: should_fix | File: products/skills/backend/marketplace/adapters.py:186-195 | Category: performance
Issue description
_team_plugin_version was previously LLMSkill.objects.filter(team=team).aggregate(latest=Max("updated_at")), which is served by the default FK index on team_id. This PR widens it to LLMSkill.objects.filter(Q(team=team) | Q(is_global=True)).aggregate(latest=Max("updated_at")) with no is_latest or deleted filter. The only index that covers is_global is the new partial index added in this stack (llm_skill_global_latest, see products/skills/backend/models/skills.py lines 42-46 and migration 0005_llmskill_global_latest_index.py), and its condition requires deleted=False AND is_global=True AND is_latest=True. Because this query's WHERE clause doesn't include is_latest/deleted predicates, Postgres cannot use that partial index for the is_global=True branch of the OR (a partial index is only usable when the query implies its predicate), and there is no unconditional index on is_global to fall back to. The planner is left to sequentially evaluate is_global across the whole llm_analytics_llmskill table (every team's every version row, since the field carries forward across publish_skill_version/_create_next_version_with_files per this same PR) for every call. This function runs on every info/refs, every git-upload-pack, and every auto-update poll (per the comment on _MARKETPLACE_VERSION_CACHE_TTL_SECONDS), gated only by a 15-second per-team cache — so as skill-store adoption grows, this becomes an increasingly expensive, unindexed, cross-tenant scan repeated at least once per 15s for every team actively using the marketplace, sitting directly in the synchronous git-clone request path.
Suggested fix
Scope the aggregation so it can use an index, e.g. restrict the is_global branch to is_latest=True, deleted=False (matching the existing partial index's condition) since only live/latest global rows should affect the plugin version anyway: LLMSkill.objects.filter(Q(team=team) | Q(is_global=True, is_latest=True, deleted=False)).aggregate(...). If archived-global rows must still bump the version, add a dedicated (non-partial) index on is_global (or (is_global, updated_at)) so the OR can be satisfied via a bitmap index scan instead of a sequential scan, and consider whether historical archived-global updates actually need to influence a future consuming team's cache key at all.
Why we think it's a valid issue
Verified and technically sound. Line 194 widens the plugin-version aggregate to filter(Q(team=team) | Q(is_global=True)) with no is_latest/deleted predicate. The only index covering is_global is the partial llm_skill_global_latest (models/skills.py:42-46, condition is_global=True AND is_latest=True AND deleted=False); a partial index is usable only when the query implies its predicate, and this query wants all is_global rows, so Postgres cannot use it for that OR branch and has no unconditional is_global index to fall back on — the planner seq-scans the whole llm_analytics_llmskill table (every version of every skill across all teams). This runs on the synchronous git-clone paths behind only a 15s-per-team cache, so it is a cross-tenant full scan repeated per active team, growing with total skill-store adoption — a real 'missing index on a hot path', introduced directly by this PR's Q(is_global=True) widening (pre-PR filter(team=team) was bounded by the team_id FK index). The reviewer's primary fix (restrict the is_global branch to is_latest/deleted) conflicts with the function's documented intent to include archived rows for version monotonicity (comment lines 187-191), but the reviewer offers the correct alternative — an unconditional (is_global, updated_at) index — so the finding's validity is independent of the fix choice. should_fix is well calibrated: the table is small at current scale and the 15s cache bounds frequency, so it is not launch-blocking, but the unindexed cross-tenant scan on a synchronous path is cheap to fix (add an index) and worth addressing before adoption grows. Keeping the reviewer's priority.
| def to_representation(self, instance: LLMSkill) -> dict[str, Any]: | ||
| data = super().to_representation(instance) | ||
| return _mask_foreign_global_author(instance, self.context, data) | ||
|
|
There was a problem hiding this comment.
Generated created_by type is non-nullable but the API can now return null for masked global skills
Priority: should_fix | Category: compatibility | Lines: 343-344, 440-443, 547-564
Issue description
LLMSkillSerializer.created_by (line 344) and LLMSkillVersionSummarySerializer.created_by (line 548) are declared as UserBasicSerializer(read_only=True) with no allow_null=True. The new _mask_foreign_global_author helper (lines 29-43), wired into both serializers' to_representation (lines 440-443, 561-564), can now overwrite data["created_by"] = None at runtime whenever a global skill owned by another team is viewed. Because drf-spectacular only introspects the declared field (non-nullable), the regenerated OpenAPI schema and downstream generated types still promise a UserBasicApi object is always present: products/skills/frontend/generated/api.schemas.ts:266 (readonly created_by: UserBasicApi) and :470 (LLMSkillVersionSummaryApi.readonly created_by: UserBasicApi), and likewise in services/mcp/src/api/generated.ts. Any consumer of these generated types (the stacked frontend PR, or an external client built from the OpenAPI/MCP schema) will treat created_by as always populated and will throw a runtime error the first time it renders/destructures created_by for a globally-visible skill surfaced from another team — which is now a supported, intended read path (list, get-by-name, resolve, MCP skill-list/skill-get).
Suggested fix
Declare both fields with allow_null=True (e.g. created_by = UserBasicSerializer(read_only=True, allow_null=True)) so drf-spectacular emits a nullable schema, then rerun hogli build:openapi so the generated TypeScript/zod types become created_by: UserBasicApi | null everywhere (api.schemas.ts, api.zod.ts, and services/mcp/src/api/generated.ts). This keeps the OpenAPI contract truthful for the frontend PR that consumes it next.
Why we think it's a valid issue
Valid contract-accuracy issue directly introduced by this PR. The new _mask_foreign_global_author helper (lines 29-43), wired into both serializers' to_representation (lines 442, 563), deliberately overwrites created_by with None whenever a non-owning team reads a global skill — a routine, intended read path per the PR (list, by-name resolve, MCP skill-list/get), not a rare accident. Yet both fields are declared UserBasicSerializer(read_only=True) with no allow_null=True, so the committed generated contracts promise a non-null object: api.schemas.ts:266 and :470, plus MCP generated.ts:32715. The runtime now diverges from the published schema on a supported path. The suggested fix is correct and has precedent: other serializers in the same MCP file already emit created_by: UserBasic | null (generated.ts:300, 1334), so adding allow_null=True and rerunning hogli build:openapi produces a truthful nullable type for the stacked frontend PR and any external OpenAPI/MCP client. I lowered the priority from must_fix to should_fix: the model field is already null=True and the codebase-wide convention already declares created_by non-null despite that (tolerated by defensive rendering), TS types don't enforce nullability at runtime, and no consumer in this diff actually crashes — so the reviewer's 'will throw a runtime error' framing is overstated. The genuine, worth-fixing problem is the schema inaccuracy the PR itself creates, which is trivial to correct and aligns with the PR's own goal of shipping accurate regenerated types.
Prompt to fix with AI (copy-paste)
## Context
@products/skills/backend/api/skill_serializers.py#L343-344
@products/skills/backend/api/skill_serializers.py#L440-443
@products/skills/backend/api/skill_serializers.py#L547-564
<issue_description>
`LLMSkillSerializer.created_by` (line 344) and `LLMSkillVersionSummarySerializer.created_by` (line 548) are declared as `UserBasicSerializer(read_only=True)` with no `allow_null=True`. The new `_mask_foreign_global_author` helper (lines 29-43), wired into both serializers' `to_representation` (lines 440-443, 561-564), can now overwrite `data["created_by"] = None` at runtime whenever a global skill owned by another team is viewed. Because drf-spectacular only introspects the declared field (non-nullable), the regenerated OpenAPI schema and downstream generated types still promise a `UserBasicApi` object is always present: `products/skills/frontend/generated/api.schemas.ts:266` (`readonly created_by: UserBasicApi`) and `:470` (`LLMSkillVersionSummaryApi.readonly created_by: UserBasicApi`), and likewise in `services/mcp/src/api/generated.ts`. Any consumer of these generated types (the stacked frontend PR, or an external client built from the OpenAPI/MCP schema) will treat `created_by` as always populated and will throw a runtime error the first time it renders/destructures `created_by` for a globally-visible skill surfaced from another team — which is now a supported, intended read path (list, get-by-name, resolve, MCP skill-list/skill-get).
</issue_description>
<issue_validation>
Valid contract-accuracy issue directly introduced by this PR. The new _mask_foreign_global_author helper (lines 29-43), wired into both serializers' to_representation (lines 442, 563), deliberately overwrites created_by with None whenever a non-owning team reads a global skill — a routine, intended read path per the PR (list, by-name resolve, MCP skill-list/get), not a rare accident. Yet both fields are declared UserBasicSerializer(read_only=True) with no allow_null=True, so the committed generated contracts promise a non-null object: api.schemas.ts:266 and :470, plus MCP generated.ts:32715. The runtime now diverges from the published schema on a supported path. The suggested fix is correct and has precedent: other serializers in the same MCP file already emit `created_by: UserBasic | null` (generated.ts:300, 1334), so adding allow_null=True and rerunning hogli build:openapi produces a truthful nullable type for the stacked frontend PR and any external OpenAPI/MCP client. I lowered the priority from must_fix to should_fix: the model field is already null=True and the codebase-wide convention already declares created_by non-null despite that (tolerated by defensive rendering), TS types don't enforce nullability at runtime, and no consumer in this diff actually crashes — so the reviewer's 'will throw a runtime error' framing is overstated. The genuine, worth-fixing problem is the schema inaccuracy the PR itself creates, which is trivial to correct and aligns with the PR's own goal of shipping accurate regenerated types.
</issue_validation>
## Task
Investigate the issue and solve it
<potential_solution>
Declare both fields with `allow_null=True` (e.g. `created_by = UserBasicSerializer(read_only=True, allow_null=True)`) so drf-spectacular emits a nullable schema, then rerun `hogli build:openapi` so the generated TypeScript/zod types become `created_by: UserBasicApi | null` everywhere (`api.schemas.ts`, `api.zod.ts`, and `services/mcp/src/api/generated.ts`). This keeps the OpenAPI contract truthful for the frontend PR that consumes it next.
</potential_solution>
| def _shadow_globals(team: Team, queryset: QuerySet[LLMSkill]) -> QuerySet[LLMSkill]: | ||
| """A team's own skill shadows a same-named global from another team. | ||
|
|
||
| Drops global rows (owned by a different team) whose name the current team already owns, so | ||
| reads never surface two skills with the same name and by-name resolution stays deterministic. | ||
| The team's own skills — including one it made global itself — are never shadowed. | ||
| """ | ||
| own_names = LLMSkill.objects.filter(team=team, deleted=False).values("name") | ||
| return queryset.exclude(Q(is_global=True) & ~Q(team=team) & Q(name__in=own_names)) |
There was a problem hiding this comment.
Two teams can both hold a globally-visible skill under the identical name, breaking deterministic by-name resolution and silently corrupting the marketplace git tree
Priority: should_fix | Category: bug | Lines: 92-100, 625-648
Issue description
_shadow_globals's docstring promises reads 'never surface two skills with the same name' and that 'by-name resolution stays deterministic', but nothing enforces that invariant across teams. LLMSkill.name is only unique per-team (unique_llm_skill_latest_per_team is scoped to team), and set_skill_visibility (the new endpoint added in this PR) flips is_global=True on whatever skill exists under (self.team, skill_name) with zero check for whether another team already has an active, globally-visible skill with that same name. _shadow_globals only excludes a foreign global when the requesting team owns a same-named local skill — it never dedupes two different foreign teams' globals against each other. Once staff globalize two different teams' skills that happen to share a name (very plausible for common skill names like 'code-review' or 'pr-shepherd'), every consumer of these shared queries breaks: get_skill_by_name_from_db (skill_services.py:116-143, used by get_by_name/export/get_file/the MCP tools) picks one of the two arbitrarily via order_by('-version', ...).first(), resolve_versions_page (skill_services.py:146-171) merges and interleaves both skills' unrelated version histories under one 'name', and — most concretely — build_marketplace_tree (products/skills/backend/marketplace/packaging.py:320-323) writes both exports into the same plugins/<plugin>/skills/<name>/... dict keys via plain assignment, so one team's global SKILL.md/files silently overwrite the other's with no error or log (contrast with the deliberate, logged skip in _skill_files_are_tree_safe for path collisions within one skill). Note that the model PR already added a non-unique partial index llm_skill_global_latest on name for exactly this query shape (products/skills/backend/migrations/0005_llmskill_global_latest_index.py) — the index anticipates the lookup pattern but doesn't enforce the uniqueness the read paths assume.
Suggested fix
Enforce (or explicitly check for) at most one active global skill per name before granting is_global=True. Either add a partial UniqueConstraint on name where (is_global=True, is_latest=True, deleted=False) and handle the resulting IntegrityError in set_skill_visibility, or add an explicit guard in set_skill_visibility that raises a clear conflict error when LLMSkill.objects.filter(is_global=True, is_latest=True, deleted=False, name=skill_name).exclude(team=team).exists(). Add a regression test creating two different teams' same-named skills and globalizing both, asserting the second call is rejected (or that build_team_marketplace_tree / get_skill_by_name_from_db behave deterministically instead of silently conflating them).
Why we think it's a valid issue
Verified against the codebase and the premise holds. LLMSkill uniqueness is per-team only (unique_llm_skill_latest_per_team on [team, name], models/skills.py:32-36), and the new llm_skill_global_latest index (models/skills.py:42-46) is a non-unique models.Index, so two teams can both hold an active global under the same name. set_skill_visibility (skill_services.py:641) flips is_global=True with no cross-team name check, and _shadow_globals (skill_services.py:100) only drops a foreign global when the REQUESTING team owns that name — it never dedupes two foreign globals against each other, despite its own docstring (lines 95-96) promising 'reads never surface two skills with the same name and by-name resolution stays deterministic'. build_team_marketplace_tree (adapters.py:97-102) repeats the same half-shadowing, and build_marketplace_tree (packaging.py:320-323) writes tree[f'{prefix}/skills/{skill.name}/{rel_path}'] by plain assignment, so a second same-named global silently overwrites the first with no log/error. Concrete consequence when two teams' same-named skills are both globalized: a third team sees arbitrary by-name resolution (order_by(...).first()), duplicate list rows, interleaved version histories, and silent cross-tenant file overwrite in the marketplace clone. This is a real correctness/data-integrity gap directly introduced by the PR, and the code violating its own documented invariant confirms it's a genuine oversight rather than defensive speculation. Lowered from must_fix to should_fix: the trigger requires staff to globalize two DIFFERENT teams' identically-named skills, which is not the default path — the maintainers' index comment notes the global set is 'small and staff-curated', lowering real-world likelihood below a launch-blocking certainty — but the silent, cross-tenant failure mode warrants closing the gap with a uniqueness constraint or an explicit conflict check in set_skill_visibility.
Prompt to fix with AI (copy-paste)
## Context
@products/skills/backend/api/skill_services.py#L92-100
@products/skills/backend/api/skill_services.py#L625-648
<issue_description>
`_shadow_globals`'s docstring promises reads 'never surface two skills with the same name' and that 'by-name resolution stays deterministic', but nothing enforces that invariant across teams. `LLMSkill.name` is only unique per-team (`unique_llm_skill_latest_per_team` is scoped to `team`), and `set_skill_visibility` (the new endpoint added in this PR) flips `is_global=True` on whatever skill exists under `(self.team, skill_name)` with zero check for whether another team already has an active, globally-visible skill with that same name. `_shadow_globals` only excludes a foreign global when the *requesting* team owns a same-named local skill — it never dedupes two different foreign teams' globals against each other. Once staff globalize two different teams' skills that happen to share a name (very plausible for common skill names like 'code-review' or 'pr-shepherd'), every consumer of these shared queries breaks: `get_skill_by_name_from_db` (skill_services.py:116-143, used by `get_by_name`/`export`/`get_file`/the MCP tools) picks one of the two arbitrarily via `order_by('-version', ...).first()`, `resolve_versions_page` (skill_services.py:146-171) merges and interleaves both skills' unrelated version histories under one 'name', and — most concretely — `build_marketplace_tree` (products/skills/backend/marketplace/packaging.py:320-323) writes both exports into the same `plugins/<plugin>/skills/<name>/...` dict keys via plain assignment, so one team's global SKILL.md/files silently overwrite the other's with no error or log (contrast with the deliberate, logged skip in `_skill_files_are_tree_safe` for path collisions within one skill). Note that the model PR already added a *non-unique* partial index `llm_skill_global_latest` on `name` for exactly this query shape (products/skills/backend/migrations/0005_llmskill_global_latest_index.py) — the index anticipates the lookup pattern but doesn't enforce the uniqueness the read paths assume.
</issue_description>
<issue_validation>
Verified against the codebase and the premise holds. LLMSkill uniqueness is per-team only (unique_llm_skill_latest_per_team on [team, name], models/skills.py:32-36), and the new llm_skill_global_latest index (models/skills.py:42-46) is a non-unique models.Index, so two teams can both hold an active global under the same name. set_skill_visibility (skill_services.py:641) flips is_global=True with no cross-team name check, and _shadow_globals (skill_services.py:100) only drops a foreign global when the REQUESTING team owns that name — it never dedupes two foreign globals against each other, despite its own docstring (lines 95-96) promising 'reads never surface two skills with the same name and by-name resolution stays deterministic'. build_team_marketplace_tree (adapters.py:97-102) repeats the same half-shadowing, and build_marketplace_tree (packaging.py:320-323) writes tree[f'{prefix}/skills/{skill.name}/{rel_path}'] by plain assignment, so a second same-named global silently overwrites the first with no log/error. Concrete consequence when two teams' same-named skills are both globalized: a third team sees arbitrary by-name resolution (order_by(...).first()), duplicate list rows, interleaved version histories, and silent cross-tenant file overwrite in the marketplace clone. This is a real correctness/data-integrity gap directly introduced by the PR, and the code violating its own documented invariant confirms it's a genuine oversight rather than defensive speculation. Lowered from must_fix to should_fix: the trigger requires staff to globalize two DIFFERENT teams' identically-named skills, which is not the default path — the maintainers' index comment notes the global set is 'small and staff-curated', lowering real-world likelihood below a launch-blocking certainty — but the silent, cross-tenant failure mode warrants closing the gap with a uniqueness constraint or an explicit conflict check in set_skill_visibility.
</issue_validation>
## Task
Investigate the issue and solve it
<potential_solution>
Enforce (or explicitly check for) at most one active global skill per name before granting `is_global=True`. Either add a partial `UniqueConstraint` on `name` where `(is_global=True, is_latest=True, deleted=False)` and handle the resulting `IntegrityError` in `set_skill_visibility`, or add an explicit guard in `set_skill_visibility` that raises a clear conflict error when `LLMSkill.objects.filter(is_global=True, is_latest=True, deleted=False, name=skill_name).exclude(team=team).exists()`. Add a regression test creating two different teams' same-named skills and globalizing both, asserting the second call is rejected (or that `build_team_marketplace_tree` / `get_skill_by_name_from_db` behave deterministically instead of silently conflating them).
</potential_solution>
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, please remove the |
|
This PR was closed due to lack of activity. Feel free to reopen if it's still relevant. |
Problem
Staff need a way to publish a skill to every customer, and customers need those global skills to show up where they already work with skills. Builds on the dormant
is_globalfield from the model PR.Note
Stacked on #71358 (model). Review that first — this PR targets that branch, so its diff is backend-only.
Changes
POST /api/projects/{team_id}/llm_skills/name/{name}/visibilitywith{ "is_global": bool }. Gated onuser.is_staff(same gate global dashboard templates use). Flipsis_globalacross every version of the skill and bumpsupdated_atso consumer marketplace clones re-version..zipexport, file fetch, the marketplace git clone, and the MCPskill-list/ get tools now surface globally-visible skills from other teams, via an opt-ininclude_globalflag threaded through the service layer.is_globalandteam_idread-only on the serializer so the UI (next PR) can tell whether the current project owns a skill. Regenerated frontend + MCP types included.How did you test this code?
Automated (run by me, the agent):
products/skills/backend/api/test/test_global_visibility.py(12 cases): staff togglesis_globalon all versions; non-staff gets 403; missing skill 404; a global reaches another team via list/by-name only withinclude_global; local shadows global; owning team is not shadowed from its own global;is_globalcarries forward across a published version and a file edit; another team sees + reads a global over the API; a non-owner cannot archive a global (404).listcase (global from another team is listed).products/skillsbackend suite still green (86 + additions).hogli build:openapiis idempotent against the committed generated files.No manual API calls — all coverage is automated.
Automatic notifications
Docs update
None. No public docs cover the skills store visibility model yet.
🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Directed by @ceyniustranberg, implemented by Claude (PostHog Code). Second of a 3-PR stack (model → backend → frontend). Invoked
/improving-drf-endpoints(serializer/viewset annotations,help_text, typed request/response for the new action) and/writing-tests(gated each new test to a named regression, kept the queryset/shadow/carry-forward logic at the cheap service level and only the staff gate + cross-team wiring at the endpoint level). Chose an opt-ininclude_globalparam over broadening the base queryset so write paths stay strictly team-scoped by default. Name-shadowing is the one real subtlety — a global and a same-named local would otherwise collide in the list, the marketplace tree, and by-name resolution.Created with PostHog Code