Skip to content

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

chore(ci): auto-label PRs by conventional-commit scope (#66227)

Phil Haack289469a7349f
diff --git a/.github/CODEOWNERS-soft b/.github/CODEOWNERS-soft
index 80775fb6895f..b6605ce2756e 100644
--- a/.github/CODEOWNERS-soft
+++ b/.github/CODEOWNERS-soft
@@ -98,6 +98,10 @@ frontend/src/scenes/cohorts/ @PostHog/team-feature-flags
posthog/tasks/calculate_cohort.py @PostHog/team-feature-flags
posthog/hogql_queries/hogql_cohort_query.py @PostHog/team-feature-flags
+# Auto-label scope mappings - owned by @PostHog/team-feature-flags so mappings
+# can change without editing the Auto Assign Labels workflow or its script
+.github/auto-assign-labels.json @PostHog/team-feature-flags
+
# Feature Flags frontend - owned by @PostHog/team-feature-flags
frontend/src/scenes/feature-flags/ @PostHog/team-feature-flags
frontend/src/scenes/FeatureFlagPermissions.tsx @PostHog/team-feature-flags
diff --git a/.github/auto-assign-labels.json b/.github/auto-assign-labels.json
new file mode 100644
index 000000000000..3dc065628e38
--- /dev/null
+++ b/.github/auto-assign-labels.json
@@ -0,0 +1,13 @@
+{
+ "_comment": "Maps a PR's conventional-commit scope (the part in parens of `type(scope): summary`) to labels the Auto Assign Labels workflow applies. Owned by @PostHog/team-feature-flags via CODEOWNERS-soft, so mappings can change without editing the workflow or script. Scopes are matched case-insensitively. Labels must already exist in the repo. Add a new object to `rules` to map more scopes.",
+ "rules": [
+ {
+ "scopes": ["flags", "feature-flags"],
+ "labels": ["feature/feature-flags", "team/feature-flags"]
+ },
+ {
+ "scopes": ["cohort", "cohorts"],
+ "labels": ["team/feature-flags", "feature/cohorts"]
+ }
+ ]
+}
diff --git a/.github/scripts/label-pr-from-title.js b/.github/scripts/label-pr-from-title.js
new file mode 100644
index 000000000000..7b48ea590510
--- /dev/null
+++ b/.github/scripts/label-pr-from-title.js
@@ -0,0 +1,127 @@
+#!/usr/bin/env node
+
+// Adds team/feature labels to a PR based on its conventional-commit scope
+// (`type(scope): summary`). Additive only — it never removes labels, so manual
+// labels and the ownership-based labeler (assign-reviewers.js) are left intact.
+//
+// The scope -> labels mapping lives in .github/auto-assign-labels.json, OUTSIDE
+// this script, so the owning team can adjust mappings without changing (and
+// re-approving) the workflow or this script. The config is read from the master
+// checkout, never the PR, so a fork PR can't inject its own mappings, and the
+// PR title only ever selects from a fixed, pre-approved set of labels.
+
+const fs = require('fs')
+const path = require('path')
+
+// Anchored to this script's location, not the cwd, so it resolves the same
+// whether the workflow runs `node .github/scripts/…` from the repo root or a
+// test invokes it from elsewhere.
+const DEFAULT_CONFIG_PATH = path.join(__dirname, '..', 'auto-assign-labels.json')
+
+function loadRules(configPath = process.env.CONFIG_PATH || DEFAULT_CONFIG_PATH) {
+ if (!fs.existsSync(configPath)) {
+ throw new Error(`No label config found at "${configPath}"`)
+ }
+ const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8'))
+ return Array.isArray(parsed.rules) ? parsed.rules : []
+}
+
+// Pull the scope tokens out of a conventional-commit subject: `type(scope): …`.
+// Requires the trailing colon so stray parentheses in prose don't match.
+// Supports comma-separated scopes (`feat(flags,cohorts):`) and is case-insensitive.
+function parseScopes(title) {
+ const match = /^\s*\w+\(([^)]+)\)!?:/.exec(title || '')
+ if (!match) {
+ return []
+ }
+ return match[1]
+ .split(',')
+ .map((scope) => scope.trim().toLowerCase())
+ .filter(Boolean)
+}
+
+// Map a title's scopes to the de-duplicated labels they should carry.
+function labelsForTitle(title, rules) {
+ const scopes = new Set(parseScopes(title))
+ const labels = new Set()
+
+ for (const rule of rules) {
+ if ((rule.scopes || []).some((scope) => scopes.has(String(scope).toLowerCase()))) {
+ for (const label of rule.labels || []) {
+ labels.add(label)
+ }
+ }
+ }
+
+ return Array.from(labels)
+}
+
+// Best-effort: a labeling failure must never fail the job. The workflow does
+// nothing but label, so a hard failure would only paint a non-blocking red ✗ on
+// the PR over a transient blip or config drift (e.g. a renamed label). We warn
+// loudly instead so the cause is visible in the Actions log.
+async function addLabels(labels) {
+ const { GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER } = process.env
+
+ if (labels.length === 0) {
+ console.info('ℹ️ Title has no labelable scope; nothing to do')
+ return
+ }
+
+ console.info(`Adding labels: ${labels.join(', ')}`)
+
+ try {
+ // Idempotent: GitHub keeps labels already present, so re-runs on title
+ // edits are safe. Additive — we never strip labels that no longer match.
+ const response = await fetch(`https://api.github.com/repos/${GITHUB_REPOSITORY}/issues/${PR_NUMBER}/labels`, {
+ method: 'POST',
+ headers: {
+ Authorization: `token ${GITHUB_TOKEN}`,
+ Accept: 'application/vnd.github.v3+json',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ labels }),
+ })
+
+ if (!response.ok) {
+ console.warn(
+ `⚠️ Could not apply labels: ${response.status} ${response.statusText}\n${await response.text()}`
+ )
+ return
+ }
+
+ console.info('✅ Labels applied')
+ } catch (error) {
+ // A non-Error throw has no `.message`; fall back to the value itself so
+ // the real reason still surfaces in the log.
+ console.warn(`⚠️ Skipping labels: ${error?.message ?? error}`)
+ }
+}
+
+async function main() {
+ const { GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER, PR_TITLE } = process.env
+ const missing = Object.entries({ GITHUB_TOKEN, GITHUB_REPOSITORY, PR_NUMBER })
+ .filter(([, value]) => !value)
+ .map(([name]) => name)
+
+ if (missing.length > 0) {
+ console.error(`Missing required environment variables: ${missing.join(', ')}`)
+ process.exit(1)
+ }
+
+ try {
+ const rules = loadRules()
+ const labels = labelsForTitle(PR_TITLE, rules)
+ console.info(`PR title: ${PR_TITLE || '(empty)'}`)
+ await addLabels(labels)
+ } catch (error) {
+ console.error('Error:', error?.message ?? error)
+ process.exit(1)
+ }
+}
+
+if (require.main === module) {
+ main()
+}
+
+module.exports = { parseScopes, labelsForTitle, loadRules }
diff --git a/.github/scripts/label-pr-from-title.test.js b/.github/scripts/label-pr-from-title.test.js
new file mode 100644
index 000000000000..a29e16a8f073
--- /dev/null
+++ b/.github/scripts/label-pr-from-title.test.js
@@ -0,0 +1,87 @@
+// Run with: node --test .github/scripts/label-pr-from-title.test.js
+//
+// Covers scope parsing and the scope -> labels mapping. The workflow runs under
+// pull_request_target, so this unit test is the only pre-merge signal that the
+// mapping logic is correct.
+
+const test = require('node:test')
+const assert = require('node:assert/strict')
+
+const { parseScopes, labelsForTitle, loadRules } = require('./label-pr-from-title')
+
+// Mirrors the rule shape in .github/auto-assign-labels.json so the logic is
+// exercised against the real structure without reading the file.
+const RULES = [
+ { scopes: ['flags', 'feature-flags'], labels: ['feature/feature-flags', 'team/feature-flags'] },
+ { scopes: ['cohort', 'cohorts'], labels: ['team/feature-flags', 'feature/cohorts'] },
+]
+
+const PARSE_SCOPES_CASES = [
+ { title: 'feat(flags): add thing', expected: ['flags'], description: 'extracts a single scope' },
+ { title: 'chore(cohorts)!: drop column', expected: ['cohorts'], description: 'handles the breaking-change bang' },
+ {
+ title: 'feat(Flags, Cohorts): x',
+ expected: ['flags', 'cohorts'],
+ description: 'lowercases and splits comma-separated scopes',
+ },
+ { title: 'chore: bump deps', expected: [], description: 'no scope -> empty' },
+ { title: 'fix a bug (really)', expected: [], description: 'ignores parentheses that are not a CC scope' },
+ { title: '', expected: [], description: 'empty title -> empty' },
+]
+
+test('parseScopes', async (t) => {
+ for (const { title, expected, description } of PARSE_SCOPES_CASES) {
+ await t.test(description, () => {
+ assert.deepEqual(parseScopes(title), expected)
+ })
+ }
+})
+
+const LABELS_FOR_TITLE_CASES = [
+ { title: 'feat(flags): x', expected: ['feature/feature-flags', 'team/feature-flags'], description: 'flags scope' },
+ {
+ title: 'fix(feature-flags): x',
+ expected: ['feature/feature-flags', 'team/feature-flags'],
+ description: 'feature-flags alias',
+ },
+ { title: 'fix(cohort): x', expected: ['team/feature-flags', 'feature/cohorts'], description: 'cohort scope' },
+ {
+ title: 'feat(cohorts)!: x',
+ expected: ['team/feature-flags', 'feature/cohorts'],
+ description: 'cohorts alias with bang',
+ },
+ { title: 'feat(insights): x', expected: [], description: 'unrelated scope -> no labels' },
+ { title: 'chore: bump', expected: [], description: 'no scope -> no labels' },
+ {
+ title: 'feat(flags,cohorts): x',
+ expected: ['feature/feature-flags', 'team/feature-flags', 'feature/cohorts'],
+ description: 'multi-scope de-dupes shared labels',
+ },
+]
+
+test('labelsForTitle', async (t) => {
+ for (const { title, expected, description } of LABELS_FOR_TITLE_CASES) {
+ await t.test(description, () => {
+ assert.deepEqual(labelsForTitle(title, RULES), expected)
+ })
+ }
+})
+
+// Catches a malformed or empty .github/auto-assign-labels.json in this PR's
+// ci-scripts run, rather than letting it silently disable labeling on master.
+test('the shipped config loads into well-formed rules', () => {
+ const rules = loadRules()
+ assert.ok(rules.length > 0, 'config has no rules')
+ for (const rule of rules) {
+ assert.ok(Array.isArray(rule.scopes) && rule.scopes.length > 0, 'rule missing scopes')
+ assert.ok(Array.isArray(rule.labels) && rule.labels.length > 0, 'rule missing labels')
+ }
+})
+
+// The logic tests above run against the local RULES mirror, so a config-only
+// edit (the supported workflow) that deletes or renames the `flags` rule would
+// ship green. Bind one known scope to the real config to catch that. Asserts
+// non-empty rather than exact labels so an intentional label rename doesn't fail.
+test('the shipped config still maps the flags scope to labels', () => {
+ assert.ok(labelsForTitle('feat(flags): x', loadRules()).length > 0, 'flags scope maps to no labels')
+})
diff --git a/.github/workflows/auto-assign-labels.yml b/.github/workflows/auto-assign-labels.yml
new file mode 100644
index 000000000000..e8f6fb66b4b7
--- /dev/null
+++ b/.github/workflows/auto-assign-labels.yml
@@ -0,0 +1,56 @@
+name: Auto Assign Labels
+
+# Adds team/feature labels to a PR based on its conventional-commit scope, e.g.
+# `feat(flags): …` -> `feature/feature-flags` + `team/feature-flags`. The
+# scope -> label mappings live in .github/auto-assign-labels.json so the owning
+# team can change them without editing this workflow or the script.
+#
+# NOTE: This uses `pull_request_target` so it can also label fork PRs (their
+# normal token is read-only). That trigger runs with a write token regardless of
+# the PR's contents, so we are careful to NEVER execute untrusted code:
+# - we check out `master` and run the script from there, not the PR branch;
+# - the PR title is passed via `env` (never interpolated into a shell line);
+# - the title only selects from the fixed set of labels in the config, so a
+# malicious title can at most apply a pre-approved label, never inject one.
+# A consequence (as with auto-assign-reviewers): changes here only take effect
+# once merged to master.
+# nosemgrep: semgrep.rules.github-actions-pull-request-target
+on:
+ pull_request_target:
+ types: [opened, edited, reopened, ready_for_review]
+
+permissions:
+ contents: read
+ pull-requests: write
+ issues: write
+
+# A PR being opened then quickly edited (title/base) queues redundant runs.
+# Labeling is idempotent, so drop any in-flight run for the same PR.
+concurrency:
+ group: auto-assign-labels-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
+jobs:
+ assign-labels:
+ runs-on: 'ubuntu-22.04'
+ timeout-minutes: 5
+
+ steps:
+ - name: Checkout master branch
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # MUST be `master` so we never execute untrusted PR code.
+ ref: master
+
+ - name: Setup Node.js
+ uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: .nvmrc
+
+ - name: Run label assignment script
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ PR_TITLE: ${{ github.event.pull_request.title }}
+ GITHUB_REPOSITORY: ${{ github.repository }}
+ run: node .github/scripts/label-pr-from-title.js
diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml
index 7b339ea4b932..025ea0ff4e1a 100644
--- a/.github/workflows/ci-scripts.yml
+++ b/.github/workflows/ci-scripts.yml
@@ -7,6 +7,7 @@ on:
pull_request:
paths:
- .github/scripts/**
+ - .github/auto-assign-labels.json
- .github/workflows/ci-scripts.yml
concurrency:
@@ -38,9 +39,12 @@ jobs:
run: python -m pip install --quiet pytest
# `-c /dev/null` skips the repo pytest.ini (its --reuse-db addopt needs
- # pytest-django, which we don't install here).
+ # pytest-django, which we don't install here). `--noconftest` skips the
+ # root conftest.py, whose autouse fixtures import the posthog package
+ # (and thus Django) — not installed in this lightweight job. The test
+ # is standalone and needs no conftest fixtures beyond pytest's tmp_path.
- name: Schema-usage scanner tests (Python)
- run: python -m pytest .github/scripts/test_schema_usage_scan.py -v -c /dev/null -p no:cacheprovider
+ run: python -m pytest .github/scripts/test_schema_usage_scan.py -v -c /dev/null -p no:cacheprovider --noconftest
# Shells out to schema_usage_scan.py via python3 (preinstalled on ubuntu).
- name: Schema-impact tests (Node)
@@ -51,3 +55,6 @@ jobs:
- name: Rate-limit monitor tests (Node)
run: node --test .github/scripts/monitor-github-rate-limit.test.js
+
+ - name: PR title labeler tests (Node)
+ run: node --test .github/scripts/label-pr-from-title.test.js