: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
chore(devex): lint cyclomatic complexity of changed files (#91305)
Paul D'Ambra947f31885616
diff --git a/.agents/skills/running-ci-preflight/SKILL.md b/.agents/skills/running-ci-preflight/SKILL.mdindex e05561adc50b..9aa375d9732c 100644--- a/.agents/skills/running-ci-preflight/SKILL.md+++ b/.agents/skills/running-ci-preflight/SKILL.md@@ -24,7 +24,7 @@ hogli ci:preflight --fix```1. Run with `--fix` — it formats, lints, and auto-fixes what is safe.-2. Read each line: `✓ pass`, `✗ fail`, `→ advisory` (do it yourself), `· skipped` (capability absent).+2. Read each line: `✓ pass`, `✗ fail`, `⚠ warning` (non-blocking finding), `→ advisory` (do it yourself), `· skipped` (capability absent).3. Resolve every `✗ fail` — these are what `--fix` could not (real lint error, broken lockfile, migration conflict). These block the push.4. Act on every `→ advisory` — e.g. `openapi` advisory → run `hogli build:openapi` and commit the drift; `staleness` advisory → `git merge origin/master`. Advisories never block, but ignoring them ships the failure to CI. **Resolve them before pushing, including drift you didn't introduce — you own the branch state you push.**5. Re-run until clean, then push.@@ -33,6 +33,7 @@ hogli ci:preflight --fix- **Strict = failures only.** `--strict` (what the hook runs) exits non-zero only on `✗ fail` — advisories are unverifiable-locally classes, so they warn without blocking. A clean exit means "nothing left to fix", not "CI will pass" — CI stays the authoritative gate. Non-blocking is a mechanism limit, not permission to skip.- **`type-check` is a nudge, not a run.** Only a repo-wide mypy run matches CI (mypy follows imports, so a changed-file subset misses reverse-dependency breakage), and that costs minutes cold — too much to tax every push with. So preflight names the command instead of running it: judge whether your change is type-risky and run it yourself. CI blocks on the same command, so a type error you skip here comes back as a full re-run.+- **`complexity` warns only.** Cyclomatic complexity above 10 in a changed file shows as `⚠ warning` and never blocks; CI annotates the same warning and posts it to the CI report comment. Simplify the function when you next touch it rather than gaming the number.- **Staleness is risk-based.** It fires when merging master _now_ would actually break something — textual merge conflicts (computed via `git merge-tree`, working tree untouched), migrations added on both sides, generated-file inputs changed on both sides, or CI workflows changed on master — plus a behind/age backstop, aggressive by default (5 commits / 2 days; env-tunable via `HOGLI_PREFLIGHT_STALE_COMMITS`/`HOGLI_PREFLIGHT_STALE_DAYS`) so we over-warn to start and tune down from telemetry. Merge master in when it fires. Advisory only, never auto-merged.- **`· skipped (needs stack/node)`** is expected on a bare checkout or sandbox. Start the stack with `hogli start` to run those, or let CI cover them. No hooks in your environment (no `node_modules`)? Run the loop yourself before pushing.- **Flags.** `--against <ref>` diffs against an explicit base; `--json` emits a machine-readable summary.diff --git a/.github/scripts/post-complexity-section.mjs b/.github/scripts/post-complexity-section.mjsnew file mode 100644index 000000000000..3b65edac69bd--- /dev/null+++ b/.github/scripts/post-complexity-section.mjs@@ -0,0 +1,51 @@+#!/usr/bin/env node+// Posts the complexity section of the shared CI report for one language. The+// complexity check is warn-only: this section informs review, it never fails+// the job. Findings JSON comes from `hogli lint:complexity --report` (Python)+// or `bin/lint-complexity.mjs --report` (TypeScript).+//+// Usage: node post-complexity-section.mjs <python|typescript> <findings.json>+import fs from 'node:fs'++import { markdownCell } from '../../frontend/bin/ci-report/format.mjs'+import { postSection } from '../../frontend/bin/ci-report/update-ci-report.mjs'++const SECTION_IDS = { python: 'complexity-python', typescript: 'complexity-ts' }++const [language, reportPath] = process.argv.slice(2)+const sectionId = SECTION_IDS[language]+if (!sectionId || !reportPath) {+ console.error('Usage: post-complexity-section.mjs <python|typescript> <findings.json>')+ process.exit(1)+}+if (!fs.existsSync(reportPath)) {+ console.info(`No findings report at ${reportPath} — skipping (branch predates the check?)`)+ process.exit(0)+}++const findings = JSON.parse(fs.readFileSync(reportPath, 'utf8'))+const maxComplexity = findings.reduce((max, finding) => Math.max(max, finding.complexity), 0)+const summary =+ findings.length > 0+ ? `${findings.length} function${findings.length === 1 ? '' : 's'} above 10 (max ${maxComplexity})`+ : 'clean'++const lines = [+ `Cyclomatic complexity above 10 in changed ${language} files. Warn only: worth simplifying when you next touch these functions.`,+ '',+]+if (findings.length > 0) {+ lines.push('| Function | Location | Complexity |', '| --- | --- | --- |')+ for (const finding of [...findings].sort((a, b) => b.complexity - a.complexity)) {+ lines.push(+ `| \`${markdownCell(finding.name)}\` | \`${markdownCell(finding.file)}:${finding.line}\` | ${finding.complexity} |`+ )+ }+}++await postSection({+ id: sectionId,+ status: findings.length > 0 ? 'warn' : 'ok',+ summary,+ body: lines.join('\n'),+})diff --git a/.github/workflows/ci-frontend.yml b/.github/workflows/ci-frontend.ymlindex 85a249fcc76f..aaa426a17b85 100644--- a/.github/workflows/ci-frontend.yml+++ b/.github/workflows/ci-frontend.yml@@ -61,6 +61,7 @@ jobs:&& (steps.exclude.outputs.outside_node_product_workspaces || 'true') == 'true' }}replay_shared: >-${{ (steps.filter.outputs.replay_shared || 'true') == 'true' }}+ complexity_files: ${{ steps.filter.outputs.complexity_files }}steps:# For pull requests it's not necessary to check out the code, but we# also want this to run on master, so we need to check out@@ -83,7 +84,17 @@ jobs:if: github.event_name != 'push' # Run all tests on master pushwith:token: ${{ steps.app-token.outputs.token || github.token }}+ list-files: 'escape'filters: |+ # Consumed as a file list (complexity_files) by the changed-file+ # complexity check — the PR files API, not a hand-rolled git diff.+ complexity:+ - 'frontend/**/*.ts'+ - 'frontend/**/*.tsx'+ - 'ee/**/*.ts'+ - 'ee/**/*.tsx'+ - 'products/**/*.ts'+ - 'products/**/*.tsx'frontend:# Avoid running frontend tests for irrelevant changes# NOTE: we are at risk of missing a dependency here.@@ -373,6 +384,36 @@ jobs:- name: Lint with Oxlintrun: pnpm exec oxlint --quiet+ # Oxlint has no cyclomatic complexity rule. Warn-only while the backlog+ # settles: findings annotate the diff and land in the shared CI report+ # comment, never a job failure. Scoped to the PR's own diff, no repo-wide+ # baseline. Skip on unrebased branches: bin/lint-complexity.mjs may not+ # exist yet.+ - name: Check cyclomatic complexity of changed files+ if: github.event_name == 'pull_request' && needs.changes.outputs.complexity_files != ''+ env:+ # Space-separated, from paths-filter (list-files: escape) — the PR+ # files API, so no git-diff plumbing to drift from what the PR changed.+ CHANGED_FILES: ${{ needs.changes.outputs.complexity_files }}+ run: |+ if [ ! -f bin/lint-complexity.mjs ]; then+ echo "bin/lint-complexity.mjs not present on this branch yet — skipping (rebase to pick it up)"+ exit 0+ fi+ # xargs re-parses the escape format, keeping escaped paths whole.+ printf '%s' "$CHANGED_FILES" | xargs -r node bin/lint-complexity.mjs --report complexity-findings-ts.json++ - name: Post CI report — complexity+ if: always() && github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/')+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ if [ -f .github/scripts/post-complexity-section.mjs ] && [ -f complexity-findings-ts.json ]; then+ node .github/scripts/post-complexity-section.mjs typescript complexity-findings-ts.json+ else+ echo "Skipping the complexity report section: script or findings not on this branch"+ fi+- name: Check markdown formatting with oxfmtrun: pnpm exec oxfmt --check "**/*.{md,mdx}"diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 4499561c0210..a098fd9f6ef1 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -24,6 +24,7 @@ jobs:# Set job outputs to values from filter stepoutputs:python: ${{ steps.filter.outputs.python || 'true' }}+ complexity_files: ${{ steps.filter.outputs.complexity_files }}steps:# For pull requests it's not necessary to checkout the code, but we# also want this to run on master so we need to checkout@@ -47,7 +48,14 @@ jobs:if: github.event_name != 'push' # Run all tests on master pushwith:token: ${{ steps.app-token.outputs.token || github.token }}+ list-files: 'escape'filters: |+ # Consumed as a file list (complexity_files) by the changed-file+ # complexity check — the PR files API, not a hand-rolled git diff.+ complexity:+ - 'posthog/**/*.py'+ - 'ee/**/*.py'+ - 'products/**/*.py'python:# ruff/mypy/ty run repo-wide (`.`) in code-quality, so any Python# file anywhere must trigger this workflow — otherwise an unformatted@@ -186,6 +194,36 @@ jobs:run: |npm run schema:build:python && git diff --exit-code+ # Warn-only while the pre-existing violation backlog settles: findings annotate+ # the diff and land in the shared CI report comment, never a job failure.+ # Scoped to the PR's own diff because C901 stays off repo-wide. Skip on+ # unrebased branches: the lint:complexity command may not be registered yet.+ - name: Check cyclomatic complexity of changed files+ if: github.event_name == 'pull_request' && needs.changes.outputs.complexity_files != ''+ shell: bash+ env:+ # Space-separated, from paths-filter (list-files: escape) — the PR+ # files API, so no git-diff plumbing to drift from what the PR changed.+ CHANGED_FILES: ${{ needs.changes.outputs.complexity_files }}+ run: |+ if [ ! -f tools/hogli-commands/hogli_commands/complexity_lint.py ]; then+ echo "hogli lint:complexity not present on this branch yet — skipping (rebase to pick it up)"+ exit 0+ fi+ # xargs re-parses the escape format, keeping escaped paths whole.+ printf '%s' "$CHANGED_FILES" | xargs -r ./bin/hogli lint:complexity --report complexity-findings-python.json++ - name: Post CI report — complexity+ if: always() && github.event_name == 'pull_request' && !startsWith(github.head_ref, 'trunk-merge/')+ env:+ GITHUB_TOKEN: ${{ github.token }}+ run: |+ if [ -f .github/scripts/post-complexity-section.mjs ] && [ -f complexity-findings-python.json ]; then+ node .github/scripts/post-complexity-section.mjs python complexity-findings-python.json+ else+ echo "Skipping the complexity report section: script or findings not on this branch"+ fi+- parallel:- name: Check for syntax errors, import sort, and code style violationsshell: bashdiff --git a/bin/lint-complexity.mjs b/bin/lint-complexity.mjsnew file mode 100644index 000000000000..3128a5732e2f--- /dev/null+++ b/bin/lint-complexity.mjs@@ -0,0 +1,157 @@+#!/usr/bin/env node+/**+ * Cyclomatic complexity linter for TypeScript/JavaScript files.+ *+ * Counts decision points per function (eslint `complexity` semantics: each+ * function starts at 1; if/loops/case/catch/ternary/&&/||/?? add 1). Oxlint has+ * no complexity rule yet, so this uses the TypeScript compiler API directly.+ *+ * Usage:+ * node bin/lint-complexity.mjs [--json] [--report <path>] <files...>+ *+ * Findings above WARN_AT are warnings; the check never fails a job (advisory+ * while the pre-existing backlog settles). `--json` emits the findings as+ * JSON for `hogli lint:complexity`, which owns human-readable output.+ * `--report <path>` writes the same JSON to a file while printing human+ * output and annotations (used by CI to post the CI report section). A test+ * binds the thresholds here to the Python side (test_complexity_lint.py).+ */++import { existsSync, readFileSync, writeFileSync } from 'fs'+import { createRequire } from 'module'+import { dirname, resolve } from 'path'+import { fileURLToPath } from 'url'++// typescript is a dependency of @posthog/frontend, not the workspace root, so+// pnpm's isolated layout only links it under frontend/node_modules.+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const require = createRequire(resolve(repoRoot, 'frontend', 'package.json'))+const ts = require('typescript')++const WARN_AT = 10++const FUNCTION_KINDS = new Set([+ ts.SyntaxKind.FunctionDeclaration,+ ts.SyntaxKind.FunctionExpression,+ ts.SyntaxKind.ArrowFunction,+ ts.SyntaxKind.MethodDeclaration,+ ts.SyntaxKind.Constructor,+ ts.SyntaxKind.GetAccessor,+ ts.SyntaxKind.SetAccessor,+])++const BRANCH_KINDS = new Set([+ ts.SyntaxKind.IfStatement,+ ts.SyntaxKind.ForStatement,+ ts.SyntaxKind.ForInStatement,+ ts.SyntaxKind.ForOfStatement,+ ts.SyntaxKind.WhileStatement,+ ts.SyntaxKind.DoStatement,+ ts.SyntaxKind.CaseClause,+ ts.SyntaxKind.CatchClause,+ ts.SyntaxKind.ConditionalExpression,+])++const SHORT_CIRCUIT_OPERATORS = new Set([+ ts.SyntaxKind.AmpersandAmpersandToken,+ ts.SyntaxKind.BarBarToken,+ ts.SyntaxKind.QuestionQuestionToken,+ ts.SyntaxKind.AmpersandAmpersandEqualsToken,+ ts.SyntaxKind.BarBarEqualsToken,+ ts.SyntaxKind.QuestionQuestionEqualsToken,+])++function isBranchNode(node) {+ if (BRANCH_KINDS.has(node.kind)) {+ return true+ }+ return ts.isBinaryExpression(node) && SHORT_CIRCUIT_OPERATORS.has(node.operatorToken.kind)+}++// Parent node kinds that hold the name a function expression is assigned to,+// e.g. `const foo = () => {}`, `{ foo: () => {} }`, `class C { foo = () => {} }`.+const NAME_HOLDER_CHECKS = [ts.isVariableDeclaration, ts.isPropertyAssignment, ts.isPropertyDeclaration]++function functionName(node) {+ if (node.name && ts.isIdentifier(node.name)) {+ return node.name.text+ }+ const parent = node.parent+ if (parent && NAME_HOLDER_CHECKS.some((isNameHolder) => isNameHolder(parent)) && ts.isIdentifier(parent.name)) {+ return parent.name.text+ }+ if (node.kind === ts.SyntaxKind.Constructor) {+ return 'constructor'+ }+ return '<anonymous>'+}++function lintFile(filePath) {+ const source = readFileSync(filePath, 'utf8')+ const scriptKind = filePath.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS+ const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, scriptKind)+ const findings = []++ function walk(node, frame) {+ if (FUNCTION_KINDS.has(node.kind)) {+ const inner = { complexity: 1 }+ node.forEachChild((child) => walk(child, inner))+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))+ findings.push({+ file: filePath,+ line: line + 1,+ column: character + 1,+ name: functionName(node),+ complexity: inner.complexity,+ })+ return+ }+ if (frame && isBranchNode(node)) {+ frame.complexity+++ }+ node.forEachChild((child) => walk(child, frame))+ }++ walk(sourceFile, null)+ return findings+}++// Not ours to lint: generated code, pnpm installs, type declarations, and+// products/desktop (Biome-linted by its own desktop-* CI).+const EXCLUDED = [/(^|\/)node_modules\//, /(^|\/)generated\//, /\.d\.ts$/, /^products\/desktop\//]++const args = process.argv.slice(2)+const asJson = args.includes('--json')+const reportIdx = args.indexOf('--report')+const reportPath = reportIdx === -1 ? null : args[reportIdx + 1]+const files = args.filter((arg, index) => arg !== '--json' && arg !== '--report' && index !== reportIdx + 1)++const findings = []+for (const file of files) {+ if (!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(file) || EXCLUDED.some((pattern) => pattern.test(file))) {+ continue+ }+ if (!existsSync(file)) {+ continue+ }+ findings.push(...lintFile(file).filter((finding) => finding.complexity > WARN_AT))+}++for (const finding of findings) {+ if (asJson) {+ continue+ }+ const message = `\`${finding.name}\` has cyclomatic complexity ${finding.complexity} (warn >${WARN_AT})`+ console.info(`${finding.file}:${finding.line}:${finding.column}: warning: ${message}`)+ if (process.env.GITHUB_ACTIONS === 'true') {+ console.info(+ `::warning file=${finding.file},line=${finding.line},col=${finding.column},title=lint:complexity::${message}`+ )+ }+}+if (asJson) {+ console.info(JSON.stringify(findings))+}+if (reportPath) {+ writeFileSync(reportPath, JSON.stringify(findings))+}diff --git a/frontend/bin/ci-report/format.mjs b/frontend/bin/ci-report/format.mjsindex fb4e11df7b37..ca5e74bf8caf 100644--- a/frontend/bin/ci-report/format.mjs+++ b/frontend/bin/ci-report/format.mjs@@ -47,3 +47,14 @@ export function totalComparison(bytes, baselineBytes, { warningThresholdPercenttotalLine: `**Total:** ${formatBytes(bytes)} · ${formatDelta(bytes, baselineBytes)}`,}}++// Makes untrusted text safe for a cell in a section's markdown table. Section+// writers interpolate PR-controlled strings (file paths, identifiers); git+// allows filenames containing backticks, pipes, and newlines, and the report+// parser treats `<!-- ci-report:section:... -->` sequences in the raw comment+// body as trusted section metadata. Stripping control characters removes the+// newlines those markers require, and removing backticks and pipes keeps the+// surrounding table well-formed.+export function markdownCell(value) {+ return String(value).replace(/[`|\p{C}]/gu, '')+}diff --git a/frontend/bin/ci-report/format.test.ts b/frontend/bin/ci-report/format.test.tsindex 8a38bb48eab0..71e1f5533c10 100644--- a/frontend/bin/ci-report/format.test.ts+++ b/frontend/bin/ci-report/format.test.ts@@ -1,4 +1,4 @@-import { totalComparison } from './format.mjs'+import { markdownCell, totalComparison } from './format.mjs'describe('ci-report formatting', () => {it('warns on any growth by default', () => {@@ -13,4 +13,24 @@ describe('ci-report formatting', () => {])('sets status for %i bytes with a 2%% warning floor', (bytes: number, expectedStatus: string) => {expect(totalComparison(bytes, 1000, { warningThresholdPercent: 2 }).status).toBe(expectedStatus)})++ it('strips control characters so a table cell cannot forge section markers', () => {+ const forged = '<!-- ci-report:section:bundle-size:e30= -->\nbody\n<!-- ci-report:section-end:bundle-size -->'+ const cell = markdownCell(`evil-${forged}`)+ // The section parser only matches markers delimited by newlines, so+ // removing the newlines is what disarms a forged marker.+ expect(cell).toBe(+ 'evil-<!-- ci-report:section:bundle-size:e30= -->body<!-- ci-report:section-end:bundle-size -->'+ )+ expect(cell).not.toContain('\n')+ })++ it.each([+ ['<anonymous>', '<anonymous>'],+ ['a|b', 'ab'],+ ['back`tick', 'backtick'],+ ['src/normal.ts', 'src/normal.ts'],+ ])('renders %s as %s', (input, expected) => {+ expect(markdownCell(input)).toBe(expected)+ })})diff --git a/frontend/bin/ci-report/update-ci-report.mjs b/frontend/bin/ci-report/update-ci-report.mjsindex 78ec2ea07071..63d5c81be129 100644--- a/frontend/bin/ci-report/update-ci-report.mjs+++ b/frontend/bin/ci-report/update-ci-report.mjs@@ -15,6 +15,8 @@ export const MARKER = '<!-- posthog-ci-report -->'// reviewed decision rather than an accident of which job happened to write first.export const SECTIONS = [{ id: 'trunk-lane', title: 'Trunk lane' },+ { id: 'complexity-python', title: 'Complexity (Python)' },+ { id: 'complexity-ts', title: 'Complexity (TypeScript)' },{ id: 'bundle-size', title: 'Bundle size' },{ id: 'eager-graph', title: 'Eager graph' },{ id: 'toolbar-size', title: 'Toolbar bundle' },diff --git a/hogli.yaml b/hogli.yamlindex 4fbbc885005a..0cbb8c309dbe 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -13,6 +13,7 @@ config:- mprocs-test.yaml- sandbox-entrypoint.py- lint-feature-flag-sorting.mjs+ - lint-complexity.mjs- render-jest-timings-example# Locally-built, gitignored binary (tools/phrocs). Referenced via cmd:/process# name, not bin_script:, so exclude it from auto-discovery to stop the manifest@@ -861,6 +862,9 @@ quality:lint:feature-flags:fix:cmd: node bin/lint-feature-flag-sorting.mjs --fixdescription: Auto-sort FEATURE_FLAGS in constants.tsx alphabetically+ lint:complexity:+ click: hogli_commands.complexity_lint:cmd_lint_complexity+ description: Check cyclomatic complexity of changed Python/TypeScript files (warn-only, above 10)lint:workflows:click: hogli_commands.workflow_lint.cli:cmd_lint_workflowsdescription: Lint .github/workflows/** for repo conventionsdiff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 695bc27ddeff..bfb8a58c0875 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -46,6 +46,7 @@ from hogli_commands.build import (_match_commands,)from hogli_commands.change_detection import changed_files, matches_globs+from hogli_commands.complexity_lint import PYTHON_SCOPE, TYPESCRIPT_SCOPEfrom hogli_commands.devenv.generator import TRACKED_MPROCS_FILESRequirement = Literal["node", "desktop-node", "stack", "clickhouse"]@@ -68,6 +69,10 @@ class DiffCheck:# so nested workspaces like products/desktop validate their own lockfile instead# of the root one. Capability (node_modules present) is checked per workspace.workspace_scoped: bool = False+ # A zero exit with output is a warning worth showing, not a clean pass —+ # for advisory checks whose findings print on stdout with exit 0. Warnings+ # never block and never count toward the advisory footer.+ soft: bool = Falsematched: list[str] = field(default_factory=list)@property@@ -122,6 +127,15 @@ DIFF_CHECKS: list[DiffCheck] = [fix=["ruff", "check", "--fix"],takes_files=True,),+ DiffCheck(+ key="complexity",+ label="cyclomatic complexity (warn >10)",+ # From complexity_lint.py so preflight and the command can't drift on scope.+ triggers=[*PYTHON_SCOPE, *TYPESCRIPT_SCOPE],+ verify=["hogli", "lint:complexity"],+ takes_files=True,+ soft=True,+ ),DiffCheck(key="ruff-format",label="Python format (ruff format)",@@ -299,7 +313,7 @@ def _unmet(chk: DiffCheck) -> list[Requirement]:return [req for req in chk.requires if not _capability_met(req)]-Status = Literal["pass", "fail", "advisory", "skipped"]+Status = Literal["pass", "fail", "warning", "advisory", "skipped"]# Generous: pnpm installs and migrations:check are legitimately slow, but a wedged# command must not hang the agent loop forever (output is captured, not streamed).@@ -396,6 +410,9 @@ def _run_diff_check(chk: DiffCheck, do_fix: bool) -> tuple[Status, str]:except subprocess.TimeoutExpired:return "fail", f"`{cmd[0]}` timed out after {_CHECK_TIMEOUT_SECONDS}s"if result.returncode == 0:+ if chk.soft and result.stdout.strip():+ warn_lines = result.stdout.strip().splitlines()+ return "warning", " · ".join(warn_lines[:3])return "pass", "fixed" if do_fix else "ok"lines = (result.stdout or result.stderr).strip().splitlines()return "fail", " · ".join(lines[:3]) if lines else f"exit {result.returncode}"@@ -570,8 +587,14 @@ def _staleness(branch_files: list[str]) -> tuple[Status, str, dict[str, Any]]:return "pass", f"{behind} commits behind master{synced} — no conflict or drift risk detected", props-_ICON: dict[Status, str] = {"pass": "✓", "fail": "✗", "advisory": "→", "skipped": "·"}-_COLOR: dict[Status, str] = {"pass": "green", "fail": "red", "advisory": "yellow", "skipped": "bright_black"}+_ICON: dict[Status, str] = {"pass": "✓", "fail": "✗", "warning": "⚠", "advisory": "→", "skipped": "·"}+_COLOR: dict[Status, str] = {+ "pass": "green",+ "fail": "red",+ "warning": "yellow",+ "advisory": "yellow",+ "skipped": "bright_black",+}def _emit_telemetry(summary: dict[str, Any]) -> None:diff --git a/tools/hogli-commands/hogli_commands/complexity_lint.py b/tools/hogli-commands/hogli_commands/complexity_lint.pynew file mode 100644index 000000000000..37b839cb19c6--- /dev/null+++ b/tools/hogli-commands/hogli_commands/complexity_lint.py@@ -0,0 +1,152 @@+"""Cyclomatic complexity lint, scoped to changed files.++Findings above a threshold of 10 are warnings; the check never fails a build+(advisory while the pre-existing violation backlog settles). Python goes+through ruff's C901 (repo-wide C901 stays off in pyproject.toml for the same+reason; this surfaces it for files a branch actually touches). TypeScript goes+through ``bin/lint-complexity.mjs`` because oxlint has no complexity rule.++ hogli lint:complexity # changed files vs origin/master+ hogli lint:complexity path/to/file.py # explicit files+ hogli lint:complexity --against <ref> # explicit diff base+"""++from __future__ import annotations++import os+import re+import json+import shutil+import subprocess+from dataclasses import asdict, dataclass++import click+from hogli.manifest import REPO_ROOT++from hogli_commands.change_detection import changed_files, matches_globs++# bin/lint-complexity.mjs declares the same threshold; a test binds the two.+WARN_AT = 10++# The complexity-linted trees: the posthog, ee, products, and frontend folders.+# Python exclusions (products/desktop, generated grammar) come from pyproject's+# ruff excludes (force-exclude honors them for explicitly passed files); the+# TypeScript ones live in bin/lint-complexity.mjs.+PYTHON_SCOPE = ("posthog/*.py", "ee/*.py", "products/*.py")+TYPESCRIPT_SCOPE = ("frontend/*.ts", "frontend/*.tsx", "ee/*.ts", "ee/*.tsx", "products/*.ts", "products/*.tsx")++_C901_MESSAGE = re.compile(r"`(?P<name>.+)` is too complex \((?P<complexity>\d+) > \d+\)")+++@dataclass(frozen=True, kw_only=True, slots=True)+class Finding:+ file: str+ line: int+ column: int+ name: str+ complexity: int+++def _python_findings(files: list[str]) -> list[Finding]:+ cmd = [+ "ruff",+ "check",+ "--select",+ "C901",+ # C901 sits in pyproject's lint.ignore (pre-existing violations); clear+ # the ignore list for this run — only C901 is selected anyway.+ "--config",+ "lint.ignore=[]",+ "--config",+ f"lint.mccabe.max-complexity={WARN_AT}",+ "--output-format",+ "json",+ *files,+ ]+ result = subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True)+ if result.returncode not in (0, 1):+ raise click.ClickException(f"ruff failed: {(result.stderr or result.stdout).strip()}")+ findings = []+ for violation in json.loads(result.stdout):+ match = _C901_MESSAGE.fullmatch(violation["message"])+ if match is None:+ continue+ findings.append(+ Finding(+ file=os.path.relpath(violation["filename"], REPO_ROOT),+ line=violation["location"]["row"],+ column=violation["location"]["column"],+ name=match["name"],+ complexity=int(match["complexity"]),+ )+ )+ return findings+++def _ts_findings(files: list[str]) -> list[Finding]:+ cmd = ["node", "bin/lint-complexity.mjs", "--json", *files]+ result = subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True)+ if result.returncode not in (0, 1):+ raise click.ClickException(f"lint-complexity.mjs failed: {result.stderr.strip()}")+ return [Finding(**item) for item in json.loads(result.stdout)]+++def _report(finding: Finding) -> None:+ message = f"`{finding.name}` has cyclomatic complexity {finding.complexity} (warn >{WARN_AT})"+ click.echo(f"{finding.file}:{finding.line}:{finding.column}: warning: {message}")+ if os.environ.get("GITHUB_ACTIONS") == "true":+ click.echo(+ f"::warning file={finding.file},line={finding.line},col={finding.column},title=lint:complexity::{message}"+ )+++ name="lint:complexity", help="Check cyclomatic complexity of changed Python/TypeScript files (warn-only)."+)[email protected]("files", nargs=-1)[email protected]("--against", default=None, help="Diff against this base ref instead of the branch default.")+ "--report",+ "report_path",+ type=click.Path(dir_okay=False, writable=True),+ default=None,+ help="Also write the findings as JSON to this path (used by the CI report poster).",+)+def cmd_lint_complexity(files: tuple[str, ...], against: str | None, report_path: str | None) -> None:+ paths = list(files) if files else changed_files(against)+ present = [f for f in paths if (REPO_ROOT / f).is_file()]+ python_files = [f for f in present if matches_globs(f, PYTHON_SCOPE)]+ ts_files = [f for f in present if matches_globs(f, TYPESCRIPT_SCOPE)]++ findings: list[Finding] = []+ checked = 0+ degraded = False+ if python_files:+ if shutil.which("ruff") is None:+ # Printed to stdout too: a soft preflight check treats non-empty stdout as+ # "warning", so a degraded run surfaces instead of reading as a clean pass.+ click.echo("complexity: ruff not found — skipping Python files")+ degraded = True+ else:+ findings += _python_findings(python_files)+ checked += len(python_files)++ if ts_files:+ # typescript is a @posthog/frontend dependency; without an install the+ # script cannot resolve it, so skip like preflight's node-needing checks.+ if not (REPO_ROOT / "frontend" / "node_modules").exists():+ click.echo("complexity: no node_modules — skipping TypeScript files")+ degraded = True+ else:+ findings += _ts_findings(ts_files)+ checked += len(ts_files)++ for finding in findings:+ _report(finding)+ summary = f"complexity: {checked} file(s) checked, {len(findings)} warning(s)"+ if degraded:+ summary += " (incomplete: some files were skipped, see above)"+ click.echo(summary, err=True)+ if report_path is not None:+ with open(report_path, "w") as f:+ json.dump([asdict(finding) for finding in findings], f)diff --git a/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.py b/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.pynew file mode 100644index 000000000000..b73961a46161--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_complexity_lint.py@@ -0,0 +1,101 @@+from __future__ import annotations++import pytest+from unittest.mock import MagicMock, patch++from click.testing import CliRunner+from hogli.cli import cli+from hogli.manifest import REPO_ROOT+from hogli_commands.complexity_lint import WARN_AT, Finding, _python_findings++runner = CliRunner()+++def _branchy_function(name: str, branches: int) -> str:+ checks = "".join(f" if n == {i}:\n return {i}\n" for i in range(branches))+ return f"def {name}(n: int) -> int:\n{checks} return -1\n"+++class TestComplexityLint:+ @pytest.mark.parametrize(+ ("branches", "name", "expected"),+ [+ pytest.param(9, "at_ten", [], id="at_threshold_not_reported"),+ pytest.param(11, "warns", [("warns", 12)], id="just_above_threshold_warns"),+ # No error tier: any complexity above the threshold is a warning only.+ pytest.param(16, "errors", [("errors", 17)], id="well_above_still_warns"),+ ],+ )+ def test_findings_above_threshold_are_warnings(self, tmp_path, branches: int, name: str, expected: list) -> None:+ # Complexity = branches + 1.+ target = tmp_path / "sample.py"+ target.write_text(_branchy_function(name, branches))++ findings = _python_findings([str(target)])++ assert [(f.name, f.complexity) for f in findings] == expected++ def test_cli_reports_warnings_without_failing(self, tmp_path) -> None:+ # The check is advisory: even a high-complexity finding must exit 0 and be+ # written to the --report file the CI report poster reads.+ finding = Finding(file="posthog/tasks/usage_report.py", line=1, column=1, name="f", complexity=17)+ report_path = tmp_path / "findings.json"+ with patch("hogli_commands.complexity_lint._python_findings", return_value=[finding]):+ result = runner.invoke(+ cli, ["lint:complexity", "posthog/tasks/usage_report.py", "--report", str(report_path)]+ )++ assert result.exit_code == 0+ assert "warning" in result.output+ assert "17" in result.output+ assert finding.name in report_path.read_text()++ @patch("hogli_commands.complexity_lint._python_findings", return_value=[])+ def test_only_scoped_files_are_checked(self, mock_findings: MagicMock) -> None:+ # Explicit paths outside posthog/ee/products (or deleted ones) must not reach ruff.+ # manage.py exists but sits outside PYTHON_SCOPE, so it exercises the scope filter+ # rather than the earlier is_file() check.+ result = runner.invoke(+ cli,+ [+ "lint:complexity",+ "posthog/tasks/usage_report.py",+ "manage.py",+ "posthog/deleted_file_does_not_exist.py",+ ],+ )+ assert result.exit_code == 0+ mock_findings.assert_called_once_with(["posthog/tasks/usage_report.py"])++ def test_thresholds_and_ci_contract_match_the_typescript_linter(self) -> None:+ # The mjs is invoked directly by ci-frontend.yml, so its threshold and its+ # --report flag (whose file the CI report poster reads) are pinned to the+ # Python side's contract.+ mjs = (REPO_ROOT / "bin" / "lint-complexity.mjs").read_text()+ assert f"const WARN_AT = {WARN_AT}\n" in mjs+ assert "indexOf('--report')" in mjs+++class TestPreflightSoftCheck:+ @patch("hogli_commands.ci_preflight._emit_telemetry")+ @patch("hogli_commands.ci_preflight._staleness", return_value=("pass", "even with master", {}))+ @patch("hogli_commands.ci_preflight._fetch_master")+ @patch("hogli_commands.ci_preflight.shutil.which", return_value="/usr/bin/hogli")+ @patch("hogli_commands.ci_preflight.subprocess.run")+ @patch("hogli_commands.ci_preflight.changed_files", return_value=["frontend/src/scenes/sceneTypes.ts"])+ def test_warnings_surface_as_advisory_without_blocking_strict(+ self,+ mock_changed: MagicMock,+ mock_run: MagicMock,+ mock_which: MagicMock,+ mock_fetch: MagicMock,+ mock_stale: MagicMock,+ mock_emit: MagicMock,+ ) -> None:+ warning = "frontend/src/scenes/sceneTypes.ts:1:1: warning: `f` has cyclomatic complexity 12 (warn >10)"+ mock_run.return_value = MagicMock(returncode=0, stdout=warning + "\n", stderr="")+ result = runner.invoke(cli, ["ci:preflight", "--strict"])+ assert result.exit_code == 0+ assert "cyclomatic complexity 12" in result.output+ # Soft warnings are not CI failures — they must not trip the advisory footer.+ assert "unpushed CI failures" not in result.output