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(devex): block new directories of unowned tests (#118632)

Raúl Negrón-Oterob8b3db37bf8b
diff --git a/.agents/skills/writing-tests/SKILL.md b/.agents/skills/writing-tests/SKILL.md
index 2823c8051bb2..2bbbb035f0b6 100644
--- a/.agents/skills/writing-tests/SKILL.md
+++ b/.agents/skills/writing-tests/SKILL.md
@@ -49,6 +49,12 @@ That sets the limit too: fold in variations of the same behavior, and don't bolt
Search before you write.
If you haven't looked for the nearest existing test, you can't answer this question.
+A new test file also needs a team owner, because ownership routes its failures and flakes.
+Put it next to the code it tests, inside `products/<name>/` when one product owns that behavior, so it inherits that owner.
+Check with `hogli owners:who <path>`.
+If no team owns it, name the team responsible for the behavior it checks in the nearest `owners.yaml`, not the team of a helper it imports.
+CI fails a test file in a new directory that no team owns, and `hogli ci:preflight` runs the same check before you push.
+
## Don't write it — the five no's
Most low-value tests fall into one of these. Recognize and skip them.
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index fe030d8f5100..96200846a360 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -536,6 +536,12 @@ jobs:
# _EXTERNAL_COMPANION_SKILL_DIRS in products/signals/backend/scout_harness/lazy_seed.py
# names this companion skill from another product.
- 'products/replay_vision/skills/exploring-replay-vision-observations/**'
+ # A test file added or deleted, Jest included, can change the baseline that
+ # test_unowned_test_directories.py enforces. Keep in step with runner_for_path
+ # in packages/owners-yaml/owners_yaml/census.py.
+ - added|deleted: '**/test_*.py'
+ - added|deleted: '**/*_test.py'
+ - added|deleted: '**/*.{test,spec}.{js,jsx,ts,tsx}'
sdk_manifests:
# Everything the SDK major-version guard reads. Lockfiles are listed
# because a floor-only or `*` spec can move to a new major through
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 2b559dc95fc4..1a2dbfe6da0a 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -66,6 +66,7 @@
- No duplicate: when this PR fixes something believed to be live on master, no open PR already fixes it. A broken master attracts parallel agents, so search before opening — `gh pr list --state open --search "<keywords>" --limit 20`, which lists drafts too, and most agent PRs start as drafts. Say here which PR you found and why this one is still needed, or that the search found nothing.
- Patch coverage: the lines this PR changed are covered, or the uncovered ones are justified under "How did you test this code?". Don't pad untouched code to lift the number. Check the "🧪 Backend test coverage" PR comment (and its patch-coverage artifact).
- New events schema: Backend CI reruns the paths in `.github/new-events-schema-targets.txt` against the native-JSON events table. A new directory of tests that read event properties is added to that file. Add `test-new-events-schema` when the diff should run the whole backend suite on both tables: event ingestion or cleaning, or event reads whose tests are outside the list. Apply it while draft, or push another commit after labeling, because label events do not start Backend CI. State the result under "How did you test this code?".
+ - Test ownership: every test file this PR adds resolves to a team (`hogli owners:who <path>`). Say under "How did you test this code?" which team you named for any that had none, and why.
- CI report: every section of the "🤖 CI report" comment is ✅, or you considered each finding: fixed it, explained in the PR body why it does not apply, or escalated it to a person. Warn-only sections, such as eager graph budgets, pass the checks while still open. See AGENTS.md, "The CI report".
- Public artifact: nothing in this PR — code, fixtures and sample data, comments, commit messages, or this description — carries material from the agent session that isn't already public. If the work drew on a customer conversation, ticket, or log, say so here and state that the committed data is invented. Renaming people, hosts, and identifiers does not clear real material; see AGENTS.md "Public open source repo guidance".
-->
diff --git a/owners.yaml b/owners.yaml
index 5e88cd2adf58..08ace5d990b9 100644
--- a/owners.yaml
+++ b/owners.yaml
@@ -169,13 +169,16 @@ rules:
- '/posthog/test/repo_invariants/test_model_enum_defaults.py'
- '/posthog/test/repo_invariants/test_squash_partial_fallback.py'
- '/posthog/test/repo_invariants/test_startup_import_budget.py'
+ - '/posthog/test/repo_invariants/test_unowned_test_directories.py'
- '/products/README.md'
- '/products/architecture.md'
- '/products/isolation_baseline.txt'
- '/tools/openapi-codegen/'
owners: team-devex
sensitive: true
- - match: '/products/model_crossing_uses_baseline.txt'
+ - match:
+ - '/posthog/test/repo_invariants/unowned_test_directories_baseline.txt'
+ - '/products/model_crossing_uses_baseline.txt'
owners: team-devex
- match: '/posthog/management/commands/find_enum_collisions.py'
owners: team-devex
diff --git a/packages/owners-yaml/CHANGELOG.md b/packages/owners-yaml/CHANGELOG.md
index a62dca3871ad..704106effb34 100644
--- a/packages/owners-yaml/CHANGELOG.md
+++ b/packages/owners-yaml/CHANGELOG.md
@@ -15,11 +15,17 @@ the GitHub Release body, so add the entry here before you cut the tag.
- An optional `sensitive` field, at file level and in rules, marks paths where a small change can change behavior far outside the change. The nearest value wins, as for `status`. The format only states the fact; a consumer decides what to do with it, for example a review assigner that requests the owners for each change. It never makes a review required. An alias file such as `product.yaml` can set it too, so a manifest that already used a `sensitive` key for another purpose now marks its paths as sensitive. `SPEC.md` section 3.7 defines it.
- The resolver response carries a `sensitive` member, and `Resolution` a `sensitive` field. A consumer treats a missing member as `false`.
- `lint` warns about a sensitive path that has no owners, because a consumer has no owner to request a review from.
+- `unowned_test_directories(resolver, paths)` returns the directories that hold a test file no team owns.
+- `GitRefSource` reads ownership files as a git ref holds them, so a check can read what a push carries.
### Changed
- A field that a tool does not know is a warning, not an error, at the top level, in a rule, in `teams`, and in `codeowners`. A file that uses a field from a newer release then still passes an older `lint`. `parse_owners_file` takes an optional `warnings` list that collects them. SPEC section 3 adds the rule that an amendment only adds a field that a tool can safely ignore.
+### Fixed
+
+- `census` no longer counts files that `owners: null` exempts under `unowned`, as SPEC section 3.1 requires.
+
## 0.3.0
### Added
diff --git a/packages/owners-yaml/owners_yaml/__init__.py b/packages/owners-yaml/owners_yaml/__init__.py
index f4f10f70d362..73cfaa0256a0 100644
--- a/packages/owners-yaml/owners_yaml/__init__.py
+++ b/packages/owners-yaml/owners_yaml/__init__.py
@@ -1,6 +1,6 @@
"""Distributed ownership: owners.yaml matcher, schema, resolver, and CLI."""
-from .census import TeamTestCensus, census, first_team_owner, runner_for_path
+from .census import TeamTestCensus, census, first_team_owner, runner_for_path, unowned_test_directories
from .codeowners import CodeownersProjection, owner_handle, package_dirs_from, project, spellings
from .github import GitHubLookupError, GitHubOrg
from .matcher import compile_pattern, normalize_path, path_matches_pattern
@@ -8,6 +8,7 @@ from .resolver import (
Addition,
BatchOwnershipSource,
DiskSource,
+ GitRefSource,
OwnershipSource,
OwnersResolver,
PathKind,
@@ -27,6 +28,7 @@ __all__ = [
"CodeownersProjection",
"DiskSource",
"GitHubLookupError",
+ "GitRefSource",
"GitHubOrg",
"OwnersResolver",
"PathKind",
@@ -52,4 +54,5 @@ __all__ = [
"spellings",
"team_channel",
"teams_registry",
+ "unowned_test_directories",
]
diff --git a/packages/owners-yaml/owners_yaml/census.py b/packages/owners-yaml/owners_yaml/census.py
index bb1c0fdc8085..2b526301e7f0 100644
--- a/packages/owners-yaml/owners_yaml/census.py
+++ b/packages/owners-yaml/owners_yaml/census.py
@@ -4,9 +4,9 @@ map. A static read of the tree, so it carries the denominator the signal-only CI
import re
from collections.abc import Iterable
from dataclasses import dataclass
-from pathlib import Path
+from pathlib import Path, PurePosixPath
-from .resolver import OwnersResolver
+from .resolver import OwnersResolver, Resolution
UNOWNED_TEAM = "unowned"
@@ -19,6 +19,13 @@ def first_team_owner(owners: list[str] | None) -> str:
return next((owner for owner in owners or [] if not owner.startswith("@")), "")
+def owning_team(resolution: Resolution) -> str | None:
+ """``None`` for an ``owners: null`` exemption (SPEC 3.1), ``unowned`` when no team owns the file."""
+ if resolution.unowned_by_design:
+ return None
+ return first_team_owner(resolution.owners) or UNOWNED_TEAM
+
+
def runner_for_path(path: str) -> str | None:
if _PYTEST_FILE.search(path):
return "pytest"
@@ -27,6 +34,16 @@ def runner_for_path(path: str) -> str | None:
return None
+def unowned_test_directories(resolver: OwnersResolver, paths: Iterable[str]) -> set[str]:
+ """Directories, not files, so the baseline holds while files come and go. A file owned only by
+ ``@handles`` counts: a person is not a routing target."""
+ return {
+ str(PurePosixPath(path).parent)
+ for path in paths
+ if runner_for_path(path) and owning_team(resolver.resolve(path)) == UNOWNED_TEAM
+ }
+
+
@dataclass(frozen=True, kw_only=True, slots=True)
class TeamTestCensus:
owner_team: str
@@ -49,14 +66,17 @@ class TeamTestCensus:
def census(paths: Iterable[str], repo_root: Path) -> list[TeamTestCensus]:
"""Count test files per owning team over repo-relative ``paths``, most tests first.
- Uncovered files and files owned only by ``@handles`` count under ``unowned``."""
+ Uncovered files and files owned only by ``@handles`` count under ``unowned``, and files that
+ ``owners: null`` exempts are left out."""
resolver = OwnersResolver(repo_root)
counts: dict[str, dict[str, int]] = {}
for path in paths:
runner = runner_for_path(path)
if runner is None:
continue
- team = first_team_owner(resolver.resolve(path).owners) or UNOWNED_TEAM
+ team = owning_team(resolver.resolve(path))
+ if team is None:
+ continue
counts.setdefault(team, {"pytest": 0, "jest": 0})[runner] += 1
return sorted(
(
diff --git a/packages/owners-yaml/owners_yaml/resolver.py b/packages/owners-yaml/owners_yaml/resolver.py
index 5fa1d0c493f8..d5e4a004a522 100644
--- a/packages/owners-yaml/owners_yaml/resolver.py
+++ b/packages/owners-yaml/owners_yaml/resolver.py
@@ -277,6 +277,46 @@ class DiskSource:
return "dir" if stat.S_ISDIR(mode) else "file"
+class GitRefSource:
+ """Ownership files as a git ref holds them, for a check on what a push carries rather than the worktree."""
+
+ def __init__(self, repo_root: Path, ref: str = "HEAD") -> None:
+ self._git = ["git", "-C", str(repo_root)]
+ self.ref = ref
+ listing = subprocess.run(
+ [*self._git, "ls-tree", "-r", "-z", "--name-only", ref], capture_output=True, text=True, check=True
+ )
+ self.files: frozenset[str] = frozenset(path for path in listing.stdout.split("\0") if path)
+ self._texts_by_name: dict[str, dict[str, str]] = {}
+
+ def read(self, path: str) -> str | None:
+ if path not in self.files:
+ return None
+ name = path.rsplit(SEP, 1)[-1]
+ if name not in self._texts_by_name:
+ self._texts_by_name[name] = self._cat([p for p in self.files if p.rsplit(SEP, 1)[-1] == name])
+ return self._texts_by_name[name][path]
+
+ def _cat(self, paths: list[str]) -> dict[str, str]:
+ """One ``git cat-file --batch`` per file name. The resolver asks for an ownership file per
+ directory, and a ``git show`` for each takes seconds on this repo."""
+ batch = subprocess.run(
+ [*self._git, "cat-file", "--batch"],
+ input="".join(f"{self.ref}:{path}\n" for path in paths).encode(),
+ capture_output=True,
+ check=True,
+ ).stdout
+ texts: dict[str, str] = {}
+ position = 0
+ for path in paths:
+ header_end = batch.index(b"\n", position)
+ size = int(batch[position:header_end].rsplit(b" ", 1)[-1])
+ position = header_end + 1
+ texts[path] = batch[position : position + size].decode()
+ position += size + 1
+ return texts
+
+
def first_new_path(path: str, path_kind: Callable[[str], PathKind | None]) -> str | None:
"""The part of ``path`` nearest the root that the tree does not hold, or None when the tree
holds ``path``. An ancestor counts as new unless the tree holds it as a directory, so a change
diff --git a/packages/owners-yaml/tests/test_owners.py b/packages/owners-yaml/tests/test_owners.py
index e711fb0ac8a3..34f454d119d2 100644
--- a/packages/owners-yaml/tests/test_owners.py
+++ b/packages/owners-yaml/tests/test_owners.py
@@ -827,7 +827,9 @@ def test_census_counts_test_files_per_team_and_folds_gaps_into_unowned(tmp_path:
_write(tmp_path, "owners.yaml", "version: 1\nowners: []\n")
_write(tmp_path, "products/a/owners.yaml", "version: 1\nowners: [team-a]\n")
_write(tmp_path, "products/p/owners.yaml", "version: 1\nowners: ['@someone']\n")
+ _write(tmp_path, "vendor/owners.yaml", "version: 1\nowners: null\n")
paths = [
+ "vendor/lib/test_vendored.py",
"products/a/backend/test_api.py",
"products/a/backend/queries_test.py",
"products/a/frontend/thing.test.tsx",
diff --git a/posthog/test/repo_invariants/test_unowned_test_directories.py b/posthog/test/repo_invariants/test_unowned_test_directories.py
new file mode 100644
index 000000000000..061069e2a9b9
--- /dev/null
+++ b/posthog/test/repo_invariants/test_unowned_test_directories.py
@@ -0,0 +1,18 @@
+from hogli_commands.ownership_lint import BLOCKING_FROM, baseline_drift, drift_problems, prune_baseline
+
+from posthog.test.repo_invariants.ratchet import enforce_baseline
+
+
+def test_no_new_directories_of_unowned_tests() -> None:
+ drift = baseline_drift()
+ message = "\n".join(
+ [
+ "A failing test with no team owner reaches nobody. `hogli owners:who <path>` shows which owners.yaml applies.",
+ *drift_problems(drift),
+ ]
+ )
+ enforce_baseline(added=drift.added, removed=drift.removed, blocking_from=BLOCKING_FROM, message=message)
+
+
+if __name__ == "__main__":
+ prune_baseline()
diff --git a/posthog/test/repo_invariants/unowned_test_directories_baseline.txt b/posthog/test/repo_invariants/unowned_test_directories_baseline.txt
new file mode 100644
index 000000000000..24f59c2b24fd
--- /dev/null
+++ b/posthog/test/repo_invariants/unowned_test_directories_baseline.txt
@@ -0,0 +1,349 @@
+.depot/actions/paths-filter/__tests__
+.github/scripts
+.semgrep/rules/security
+common/esbuilder
+common/hogvm/python/test
+common/hogvm/typescript/src/__tests__
+common/ingestion/acceptance_tests
+common/replay-headless/src/__tests__
+common/replay-shared/src
+common/replay-shared/src/canvas
+common/replay-shared/src/rrweb-plugins
+common/replay-shared/src/snapshot-processing
+ee/api/test
+ee/api/tests
+ee/clickhouse/models/test
+ee/clickhouse/queries/test
+ee/clickhouse/test
+ee/clickhouse/views/test
+ee/models/test
+ee/partners/stripe/api/provisioning/test
+ee/tasks/test
+frontend/src
+frontend/src/exporter
+frontend/src/exporter/ExportedInsight
+frontend/src/exporter/scenes
+frontend/src/layout/ErrorBoundary
+frontend/src/layout/ai
+frontend/src/layout/navigation
+frontend/src/layout/navigation-3000
+frontend/src/layout/navigation-3000/sidepanel
+frontend/src/layout/navigation-3000/sidepanel/panels/access_control
+frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2
+frontend/src/layout/navigation-3000/sidepanel/panels/activity
+frontend/src/layout/navigation-3000/sidepanel/panels/max
+frontend/src/layout/navigation-3000/sidepanel/panels/support
+frontend/src/layout/navigation/Breadcrumbs
+frontend/src/layout/navigation/ImpersonationNotice
+frontend/src/layout/panel-layout
+frontend/src/layout/panel-layout/ProjectTree
+frontend/src/layout/panel-layout/ProjectTree/menus
+frontend/src/layout/panel-layout/navbar
+frontend/src/layout/panel-layout/navbar/tabs
+frontend/src/layout/scenes
+frontend/src/layout/scenes/components
+frontend/src/layout/today
+frontend/src/lib
+frontend/src/lib/charts
+frontend/src/lib/components
+frontend/src/lib/components/Account
+frontend/src/lib/components/AccountAssignmentFilter
+frontend/src/lib/components/ActivityLog
+frontend/src/lib/components/ActivityLog/activityDescriptions
+frontend/src/lib/components/AddToDashboard
+frontend/src/lib/components/AgentObjectTags
+frontend/src/lib/components/AgentPromptButton
+frontend/src/lib/components/Alerting/AlertWizard
+frontend/src/lib/components/AnalyticsMetricCard
+frontend/src/lib/components/AnnotationsOverlay
+frontend/src/lib/components/AppMetrics
+frontend/src/lib/components/AuthorizedUrlList
+frontend/src/lib/components/Cards/ButtonTileCard
+frontend/src/lib/components/Cards/InsightCard
+frontend/src/lib/components/Cards/TextCard
+frontend/src/lib/components/ChartFilter
+frontend/src/lib/components/ChartLegendSeriesMenu
+frontend/src/lib/components/ChartOptions
+frontend/src/lib/components/CodeSnippet
+frontend/src/lib/components/Command
+frontend/src/lib/components/CommandKSearch
+frontend/src/lib/components/Comments
+frontend/src/lib/components/CompareFilter
+frontend/src/lib/components/CyclotronJob
+frontend/src/lib/components/CyclotronJob/integrations
+frontend/src/lib/components/DateFilter
+frontend/src/lib/components/DateFilter/DateRangePicker
+frontend/src/lib/components/DatePicker
+frontend/src/lib/components/DefinitionPopover
+frontend/src/lib/components/DomainConnect
+frontend/src/lib/components/EmailPreviewThumbnail
+frontend/src/lib/components/EmojiPicker
+frontend/src/lib/components/Errors
+frontend/src/lib/components/Errors/Frame
+frontend/src/lib/components/ExportButton
+frontend/src/lib/components/FacetRail
+frontend/src/lib/components/FeaturePreviews
+frontend/src/lib/components/FeedbackSurveyButton
+frontend/src/lib/components/FlagCalledMoveNotice
+frontend/src/lib/components/FlagCalledRebuildBanner
+frontend/src/lib/components/Git
+frontend/src/lib/components/GuidedWizard
+frontend/src/lib/components/HTMLElementsDisplay
+frontend/src/lib/components/HelpMenu
+frontend/src/lib/components/IngestionControls/triggers/triggerGroups
+frontend/src/lib/components/InsightLabel
+frontend/src/lib/components/MCPHint
+frontend/src/lib/components/MarkdownEditor/inline
+frontend/src/lib/components/MarkdownEditor/rich
+frontend/src/lib/components/MarkdownEditor/shared
+frontend/src/lib/components/Metalytics
+frontend/src/lib/components/NotificationsMenu
+frontend/src/lib/components/ObjectTags
+frontend/src/lib/components/PathCleanFilters
+frontend/src/lib/components/PayGateMini
+frontend/src/lib/components/ProductSetup
+frontend/src/lib/components/PropertiesTable
+frontend/src/lib/components/PropertyFilters
+frontend/src/lib/components/PropertyFilters/components
+frontend/src/lib/components/QuickFilters
+frontend/src/lib/components/ReleaseStageTag
+frontend/src/lib/components/SceneDashboardChoice
+frontend/src/lib/components/Scenes
+frontend/src/lib/components/Scenes/InsightOrDashboard
+frontend/src/lib/components/Search
+frontend/src/lib/components/SearchAutocomplete
+frontend/src/lib/components/SessionTimeline
+frontend/src/lib/components/SessionTimeline/timeline
+frontend/src/lib/components/SessionTimeline/timeline/items
+frontend/src/lib/components/Sharing
+frontend/src/lib/components/Shortcuts
+frontend/src/lib/components/Support
+frontend/src/lib/components/SurveyResponseDisplay
+frontend/src/lib/components/TZLabel
+frontend/src/lib/components/TablePreview
+frontend/src/lib/components/TaxonomicFilter
+frontend/src/lib/components/TaxonomicFilter/utils
+frontend/src/lib/components/TaxonomicPopover
+frontend/src/lib/components/TerraformExporter
+frontend/src/lib/components/TimeSensitiveAuthentication
+frontend/src/lib/components/TimezoneSelect
+frontend/src/lib/components/UniversalFilters
+frontend/src/lib/components/ViewRecordingButton
+frontend/src/lib/components/ViewTraceButton
+frontend/src/lib/components/VisualImageDiffViewer
+frontend/src/lib/forms
+frontend/src/lib/hooks
+frontend/src/lib/insights
+frontend/src/lib/integrations
+frontend/src/lib/logic
+frontend/src/lib/logic/billing
+frontend/src/lib/logic/scenes
+frontend/src/lib/memory
+frontend/src/lib/monaco
+frontend/src/lib/monaco/__tests__
+frontend/src/lib/monaco/languages
+frontend/src/lib/signals
+frontend/src/lib/utils
+frontend/src/mocks
+frontend/src/models
+frontend/src/queries
+frontend/src/queries/Query
+frontend/src/queries/nodes/DataNode
+frontend/src/queries/nodes/DataTable
+frontend/src/queries/nodes/DataTable/ColumnConfigurator
+frontend/src/queries/nodes/DataTable/TableView
+frontend/src/queries/nodes/DataVisualization
+frontend/src/queries/nodes/DataVisualization/Components
+frontend/src/queries/nodes/DataVisualization/Components/Charts
+frontend/src/queries/nodes/DataVisualization/Components/Heatmap
+frontend/src/queries/nodes/DataVisualization/Components/Variables
+frontend/src/queries/nodes/HogQLX
+frontend/src/queries/nodes/InsightQuery/utils
+frontend/src/queries/nodes/InsightViz
+frontend/src/queries/schema
+frontend/src/scenes
+frontend/src/scenes/PreflightCheck
+frontend/src/scenes/StripeConfirmInstall
+frontend/src/scenes/analytics
+frontend/src/scenes/code-canvas
+frontend/src/scenes/debug
+frontend/src/scenes/integrations/aws-s3
+frontend/src/scenes/integrations/components
+frontend/src/scenes/library
+frontend/src/scenes/organization/ConfirmOrganization
+frontend/src/scenes/product-tours/editor
+frontend/src/scenes/project
+frontend/src/scenes/project-files
+frontend/src/scenes/real-time-usage
+frontend/src/scenes/settings
+frontend/src/scenes/settings/environment
+frontend/src/scenes/settings/organization
+frontend/src/scenes/settings/organization/Approvals
+frontend/src/scenes/settings/project
+frontend/src/scenes/settings/user
+frontend/src/scenes/settings/user/passkeys
+frontend/src/scenes/sites
+frontend/src/scenes/team-activity/customer_analytics_config
+frontend/src/scenes/terminal
+frontend/src/styles
+frontend/src/taxonomy
+frontend/src/test
+nodejs/src/common/api
+nodejs/src/common/api/middleware
+nodejs/src/common/config
+nodejs/src/common/groups
+nodejs/src/common/groups/repositories
+nodejs/src/common/kafka
+nodejs/src/common/kafka/consumer
+nodejs/src/common/metrics
+nodejs/src/common/outputs
+nodejs/src/common/personhog
+nodejs/src/common/persons
+nodejs/src/common/persons/repositories
+nodejs/src/common/services
+nodejs/src/common/tracing
+nodejs/src/common/usage-ingestion
+nodejs/src/common/utils
+nodejs/src/common/utils/db
+nodejs/src/common/utils/event-ingestion-restrictions
+nodejs/src/logs
+nodejs/src/logs/framework
+nodejs/src/logs/metrics-rules
+nodejs/src/logs/pipeline
+nodejs/src/logs/retention
+nodejs/src/logs/sampling
+nodejs/src/logs/services
+nodejs/src/logs/transformations
+nodejs/src/logs/transformations/benchmarks
+nodejs/src/messaging/push-subscriptions
+nodejs/src/schema-check
+nodejs/src/servers
+nodejs/src/session-replay/recording-api
+packages/llm-normalizer/src
+packages/llm-normalizer/src/normalizer/recipe
+packages/llm-normalizer/src/normalizer/recipe/ast/expr
+packages/llm-normalizer/src/normalizer/recipe/ast/predicate
+packages/llm-normalizer/src/normalizer/recipe/ast/rule
+packages/llm-normalizer/src/normalizer/recipe/compile
+packages/llm-normalizer/src/normalizer/recipe/runtime
+playwright/e2e
+playwright/e2e/experiments
+playwright/e2e/persons
+playwright/e2e/product-analytics
+playwright/e2e/product-analytics/insights
+posthog/admin
+posthog/api/advanced_activity_logs
+posthog/api/file_system/test
+posthog/api/scim/test
+posthog/api/test
+posthog/api/test/notebooks
+posthog/api/test/rust_integration
+posthog/api/wizard/test
+posthog/async_migrations/examples
+posthog/async_migrations/test
+posthog/clickhouse
+posthog/clickhouse/client/test
+posthog/clickhouse/migrations
+posthog/clickhouse/test
+posthog/credentials_service/test
+posthog/dags
+posthog/dags/tests
+posthog/emoji_search
+posthog/helpers
+posthog/helpers/tests
+posthog/hogql_queries/legacy_compatibility/test
+posthog/hogql_queries/test
+posthog/hogql_queries/utils/test
+posthog/hogql_queries/validation
+posthog/kafka_client/test
+posthog/llm
+posthog/local_bootstrap
+posthog/logging/test
+posthog/management/commands
+posthog/management/commands/test
+posthog/management/migration_profiling/test
+posthog/models/async_deletion
+posthog/models/distinct_id_usage/test
+posthog/models/exchange_rate/test
+posthog/models/file_system/test
+posthog/models/group
+posthog/models/person_group_membership/test
+posthog/models/property/test
+posthog/models/scoping
+posthog/models/team
+posthog/models/team/test
+posthog/models/test
+posthog/models/test/integration
+posthog/models/tophog/test
+posthog/models/usage_report_events_preagg/test
+posthog/object_tags/test
+posthog/ownership/test
+posthog/personhog_client
+posthog/plugins/test
+posthog/query_cache/test
+posthog/query_scan/test
+posthog/resource_limits/test
+posthog/scheduling/test
+posthog/schema_migrations/test
+posthog/security/test
+posthog/session/test
+posthog/settings
+posthog/slo/test
+posthog/storage/test
+posthog/tasks/test
+posthog/taxonomic_search_intent
+posthog/temporal/billing_active_sync/tests
+posthog/temporal/common
+posthog/temporal/health_checks/rollups/tests
+posthog/temporal/health_checks/tests
+posthog/temporal/ingestion_acceptance_test
+posthog/temporal/tests
+posthog/temporal/tests/ai
+posthog/temporal/tests/backfill_group_type_created_at
+posthog/temporal/tests/backfill_materialized_property
+posthog/temporal/tests/cleanup_property_definitions
+posthog/temporal/tests/common
+posthog/temporal/tests/data_modeling
+posthog/temporal/tests/delete_persons
+posthog/temporal/tests/delete_teams
+posthog/temporal/tests/dlq_replay
+posthog/temporal/tests/ingestion_acceptance_test
+posthog/temporal/tests/salesforce_enrichment
+posthog/temporal/tests/session_replay/copy_recording
+posthog/temporal/tests/session_replay/count_playlist_items
+posthog/temporal/tests/session_replay/delete_recordings
+posthog/temporal/tests/session_replay/enforce_max_replay_retention
+posthog/temporal/tests/session_replay/rasterize_recording
+posthog/temporal/tests/session_replay/replay_count_metrics
+posthog/temporal/tests/session_replay/surfacing_score_export_sweep
+posthog/temporal/tests/session_replay/surfacing_scoring_sweep
+posthog/temporal/tests/sync_events_retention
+posthog/temporal/tests/usage_report
+posthog/temporal/tests/warehouse_sources_queue_partition_management
+posthog/test
+posthog/test/repo_invariants
+posthog/usage_ingestion
+posthog/user_scripts
+posthog/user_scripts/v10
+posthog/user_scripts/v11
+posthog/user_scripts/v12
+posthog/user_scripts/v13
+posthog/user_scripts/v5
+posthog/user_scripts/v6
+posthog/user_scripts/v7
+posthog/user_scripts/v8
+posthog/user_scripts/v9
+posthog/workload_identity/test
+products/field_notes/backend/test
+products/games/frontend/ShipIt
+products/product_tours/backend/api/test
+products/product_tours/frontend/emptyState
+rust/deltalite/python/tests
+services/credentials-service/tests/integration
+services/credentials-service/tests/unit
+services/stripe-mock/tests
+tools
+tools/hogbox-preview/tests
+tools/infra-scripts/clitools
+tools/traffic-sim/tests
+tools/workflow-plan/tests
diff --git a/tools/hogli-commands/hogli_commands/change_detection.py b/tools/hogli-commands/hogli_commands/change_detection.py
index 919f72c357d3..cc9325e02d3f 100644
--- a/tools/hogli-commands/hogli_commands/change_detection.py
+++ b/tools/hogli-commands/hogli_commands/change_detection.py
@@ -28,7 +28,8 @@ def changed_files(against: str | None = None, *, include_worktree: bool = True)
what CI diffs against and what the staleness check compares to) and degrades to
working-tree-only detection when neither exists (single-branch clones, bare
sandboxes). ``-z`` output keeps paths with spaces/non-ASCII unquoted, and
- ``--untracked-files=all`` lists files inside brand-new directories.
+ ``--untracked-files=all`` lists files inside brand-new directories. ``--no-renames``
+ lists both paths of a rename, so a check triggered by the old name still runs.
``include_worktree=False`` restricts the result to the committed branch diff,
dropping uncommitted and untracked work — the correct scope for a pre-push gate,
@@ -37,7 +38,7 @@ def changed_files(against: str | None = None, *, include_worktree: bool = True)
"""
files: set[str] = set()
for base in [against] if against is not None else ["origin/master", "master"]:
- diff = _git("diff", "--name-only", "-z", f"{base}...HEAD")
+ diff = _git("diff", "--name-only", "-z", "--no-renames", f"{base}...HEAD")
if diff.returncode == 0:
files.update(path for path in diff.stdout.split("\0") if path)
break
diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.py
index d4885452fa7b..4ffe96d590ce 100644
--- a/tools/hogli-commands/hogli_commands/ci_preflight.py
+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py
@@ -51,6 +51,7 @@ from hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIP
from hogli_commands.depot_mirrors import mirror_violations
from hogli_commands.devenv.generator import TRACKED_MPROCS_FILES
from hogli_commands.lockfile_merge import LOCKFILE_GLOBS, missing_resolutions
+from hogli_commands.ownership_lint import OWNERSHIP_FILE_GLOBS, TEST_FILE_GLOBS, check_test_owners
from hogli_commands.preflight_checks import (
SEMGREP_SCOPE,
SNAPSHOT_MANIFEST,
@@ -172,6 +173,13 @@ DIFF_CHECKS: list[DiffCheck] = [
takes_diff_scope=True,
soft=True,
),
+ DiffCheck(
+ key="test-owners",
+ label="test ownership (new directory of unowned tests, or a stale baseline entry)",
+ triggers=[*TEST_FILE_GLOBS, *OWNERSHIP_FILE_GLOBS],
+ verify=None,
+ run=check_test_owners,
+ ),
DiffCheck(
key="ruff-format",
label="Python format (ruff format)",
diff --git a/tools/hogli-commands/hogli_commands/ownership_lint.py b/tools/hogli-commands/hogli_commands/ownership_lint.py
new file mode 100644
index 000000000000..e6e5d5d3bb8f
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/ownership_lint.py
@@ -0,0 +1,99 @@
+"""Compare the directories that hold unowned tests with the baseline.
+
+Shared by test_unowned_test_directories.py (the CI gate) and the `test-owners` preflight check.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Iterable
+from dataclasses import dataclass
+from datetime import date
+from pathlib import Path
+
+from hogli.manifest import REPO_ROOT
+from owners_yaml import GitRefSource, OwnersResolver, runner_for_path, unowned_test_directories
+from owners_yaml.schema import DEFAULT_ALIAS_FILES, OWNERS_FILENAME
+
+from hogli_commands.change_detection import matches_globs
+from hogli_commands.preflight_checks import Outcome, Scope
+
+BASELINE = Path("posthog/test/repo_invariants/unowned_test_directories_baseline.txt")
+PRUNE = "PYTHONPATH=.:tools/hogli-commands python posthog/test/repo_invariants/test_unowned_test_directories.py"
+BLOCKING_FROM = date.fromisoformat("2026-11-11")
+
+# fnmatch: `*` spans `/`.
+TEST_FILE_GLOBS = (
+ "test_*.py",
+ "*/test_*.py",
+ "*_test.py",
+ *(f"*.{kind}.{ext}" for kind in ("test", "spec") for ext in ("js", "jsx", "ts", "tsx")),
+)
+OWNERSHIP_FILE_GLOBS = (
+ OWNERS_FILENAME,
+ *(f"*/{name}" for name in (OWNERS_FILENAME, *DEFAULT_ALIAS_FILES)),
+ str(BASELINE),
+)
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class BaselineDrift:
+ added: list[str]
+ removed: list[str]
+
+
+def _git_paths(*args: str) -> set[str]:
+ result = subprocess.run(["git", "-C", str(REPO_ROOT), *args, "-z"], capture_output=True, text=True, check=True)
+ return {path for path in result.stdout.split("\0") if path}
+
+
+def _tree(committed_only: bool) -> tuple[OwnersResolver, Iterable[str]]:
+ """HEAD for a push, or the working tree, untracked files included, for a local run."""
+ if committed_only:
+ head = GitRefSource(REPO_ROOT)
+ return OwnersResolver(REPO_ROOT, source=head), head.files
+ files = _git_paths("ls-files", "--cached", "--others", "--exclude-standard") - _git_paths("ls-files", "--deleted")
+ return OwnersResolver(REPO_ROOT), files
+
+
+def _baseline(resolver: OwnersResolver) -> set[str]:
+ return set((resolver.source.read(str(BASELINE)) or "").split())
+
+
+def baseline_drift(committed_only: bool = False) -> BaselineDrift:
+ resolver, files = _tree(committed_only)
+ current = unowned_test_directories(resolver, files)
+ baseline = _baseline(resolver)
+ return BaselineDrift(added=sorted(current - baseline), removed=sorted(baseline - current))
+
+
+def prune_baseline() -> None:
+ """Never adds a directory, so a new gap stays a failure."""
+ resolver, files = _tree(committed_only=False)
+ remaining = sorted(_baseline(resolver) & unowned_test_directories(resolver, files))
+ (REPO_ROOT / BASELINE).write_text("".join(f"{directory}\n" for directory in remaining), encoding="utf-8")
+
+
+def drift_problems(drift: BaselineDrift) -> list[str]:
+ return [
+ *(
+ f"{directory} holds tests that no team owns: name the team in its nearest owners.yaml"
+ for directory in drift.added
+ ),
+ *(f"{directory} has no unowned tests left: run `{PRUNE}`" for directory in drift.removed),
+ ]
+
+
+def check_test_owners(scope: Scope) -> Outcome:
+ # `*/test_*.py` also matches `test_utils/foo.py`.
+ if not any(runner_for_path(path) or matches_globs(path, OWNERSHIP_FILE_GLOBS) for path in scope.files):
+ return "pass", "no test or ownership file changed"
+ drift = baseline_drift(scope.committed_only)
+ problems = drift_problems(drift)
+ if not problems:
+ return "pass", "no new directory of unowned tests"
+ detail = " · ".join(problems[:3]) + (f" · and {len(problems) - 3} more" if len(problems) > 3 else "")
+ # Mirrors enforce_baseline in posthog/test/repo_invariants/ratchet.py.
+ if drift.removed or date.today() >= BLOCKING_FROM:
+ return "fail", detail
+ return "warning", f"not blocking until {BLOCKING_FROM.isoformat()}: {detail}"
diff --git a/tools/hogli-commands/hogli_commands/tests/conftest.py b/tools/hogli-commands/hogli_commands/tests/conftest.py
index fe84df7f326e..1ec3e18cf184 100644
--- a/tools/hogli-commands/hogli_commands/tests/conftest.py
+++ b/tools/hogli-commands/hogli_commands/tests/conftest.py
@@ -3,3 +3,33 @@
These tests do not require Django. Run from the repo root with:
pytest tools/hogli-commands/hogli_commands/tests/ -p no:django -o 'addopts=' -o 'DJANGO_SETTINGS_MODULE='
"""
+
+import subprocess
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+
+
+def git() -> Callable[..., str]:
+ def run(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ [
+ "git",
+ "-C",
+ str(repo),
+ "-c",
+ "user.name=t",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ *args,
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+ return run
diff --git a/tools/hogli-commands/hogli_commands/tests/test_change_detection.py b/tools/hogli-commands/hogli_commands/tests/test_change_detection.py
index 1147861d6df0..1a73a5d5df32 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_change_detection.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_change_detection.py
@@ -1,9 +1,13 @@
from __future__ import annotations
+from collections.abc import Callable
+from pathlib import Path
+
import pytest
from unittest.mock import MagicMock, patch
import click
+from hogli_commands import change_detection
from hogli_commands.change_detection import changed_files, matches_globs
@@ -12,6 +16,20 @@ def _completed(stdout: str = "", returncode: int = 0, stderr: str = "") -> Magic
class TestChangedFiles:
+ def test_committed_rename_lists_both_paths(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, git: Callable[..., str]
+ ) -> None:
+ monkeypatch.setattr(change_detection, "REPO_ROOT", tmp_path)
+ (tmp_path / "test_a.py").write_text("def test_x():\n pass\n")
+ git(tmp_path, "init", "-q")
+ git(tmp_path, "add", "-A")
+ git(tmp_path, "commit", "-q", "-m", "init")
+ base = git(tmp_path, "rev-parse", "HEAD")
+ git(tmp_path, "mv", "test_a.py", "a.py")
+ git(tmp_path, "commit", "-q", "-m", "rename")
+
+ assert changed_files(base, include_worktree=False) == ["a.py", "test_a.py"]
+
@patch("hogli_commands.change_detection.subprocess.run")
def test_combines_branch_diff_and_working_tree(self, mock_run: MagicMock) -> None:
mock_run.side_effect = [
diff --git a/tools/hogli-commands/hogli_commands/tests/test_ownership_lint.py b/tools/hogli-commands/hogli_commands/tests/test_ownership_lint.py
new file mode 100644
index 000000000000..16e641c89907
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_ownership_lint.py
@@ -0,0 +1,110 @@
+from __future__ import annotations
+
+from collections.abc import Callable
+from datetime import date
+from pathlib import Path
+
+import pytest
+
+from hogli_commands import ownership_lint
+from hogli_commands.preflight_checks import Scope
+
+OWNERS_YAML = """\
+version: 1
+owners: []
+rules:
+ - match: '/team/'
+ owners: team-billing
+ - match: '/person/'
+ owners: '@alice'
+ - match: '/by_design/'
+ owners: null
+"""
+
+
+def repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, git: Callable[..., str]) -> Path:
+ (tmp_path / "owners.yaml").write_text(OWNERS_YAML)
+ for path in ("team/test_a.py", "person/test_b.py", "nobody/test_c.py", "by_design/test_d.py", "helpers/util.py"):
+ (tmp_path / path).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / path).write_text("def test_x():\n pass\n")
+ (tmp_path / ownership_lint.BASELINE).parent.mkdir(parents=True)
+ (tmp_path / ownership_lint.BASELINE).write_text("nobody\nperson\n")
+ git(tmp_path, "init", "-q")
+ git(tmp_path, "add", "-A")
+ git(tmp_path, "commit", "-q", "-m", "init")
+ monkeypatch.setattr(ownership_lint, "REPO_ROOT", tmp_path)
+ monkeypatch.setattr(ownership_lint, "BLOCKING_FROM", date.min)
+ return tmp_path
+
+
+def _check(*files: str, committed_only: bool = False) -> tuple[str, str]:
+ return ownership_lint.check_test_owners(
+ Scope(files=list(files), changed=list(files), merge_base="HEAD", committed_only=committed_only)
+ )
+
+
+class TestCheckTestOwners:
+ @pytest.mark.parametrize(
+ ("baseline", "blocking_from", "status", "named"),
+ [
+ pytest.param("nobody\nperson\n", date.min, "pass", None, id="baseline_matches"),
+ pytest.param("nobody\n", date.min, "fail", "person holds tests", id="person_only_owner_is_a_new_gap"),
+ pytest.param("nobody\n", date.max, "warning", "not blocking until", id="new_gap_warns_in_the_grace_period"),
+ pytest.param(
+ "nobody\nperson\nteam\n",
+ date.max,
+ "fail",
+ "team has no unowned tests left",
+ id="stale_entry_fails_in_the_grace_period",
+ ),
+ ],
+ )
+ def test_compares_unowned_test_directories_with_the_baseline(
+ self,
+ repo: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ baseline: str,
+ blocking_from: date,
+ status: str,
+ named: str | None,
+ ) -> None:
+ monkeypatch.setattr(ownership_lint, "BLOCKING_FROM", blocking_from)
+ (repo / ownership_lint.BASELINE).write_text(baseline)
+
+ result_status, detail = _check(str(ownership_lint.BASELINE))
+
+ assert result_status == status
+ assert named is None or named in detail
+
+ @pytest.mark.parametrize(
+ ("path", "committed_only", "status"),
+ [
+ pytest.param("helpers/test_fixtures/util.py", False, "pass", id="non_test_file_skips_the_scan"),
+ pytest.param("elsewhere/test_new.py", False, "fail", id="untracked_test_is_scanned_locally"),
+ pytest.param("elsewhere/test_new.py", True, "pass", id="untracked_test_is_not_in_the_push"),
+ ],
+ )
+ def test_scans_the_tree_the_scope_names(self, repo: Path, path: str, committed_only: bool, status: str) -> None:
+ (repo / ownership_lint.BASELINE).write_text("nobody\n")
+ (repo / path).parent.mkdir(exist_ok=True)
+ (repo / path).write_text("def test_y():\n pass\n")
+
+ assert _check(path, committed_only=committed_only)[0] == status
+
+ @pytest.mark.parametrize(
+ ("committed_only", "status"),
+ [
+ pytest.param(True, "pass", id="strict_reads_head"),
+ pytest.param(False, "fail", id="local_reads_the_working_tree"),
+ ],
+ )
+ def test_an_uncommitted_owners_yaml_counts_only_locally(
+ self, repo: Path, committed_only: bool, status: str
+ ) -> None:
+ (repo / "owners.yaml").write_text(OWNERS_YAML + " - match: '/nobody/'\n owners: team-billing\n")
+
+ result_status, detail = _check("owners.yaml", committed_only=committed_only)
+
+ assert result_status == status
+ assert status == "pass" or "nobody has no unowned tests left" in detail