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): tag AGENTS.md rules with what enforces them (#98192)

Julian Bez406f16b06506
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.md
index 9dddea6a2577..e4714f2b1b1e 100644
--- a/.agents/skills/authoring-ci-workflows/SKILL.md
+++ b/.agents/skills/authoring-ci-workflows/SKILL.md
@@ -359,6 +359,19 @@ Otherwise the fallback is full on drafts too: `ci-nodejs.yml` has a bare `pull_r
`turbo-discover.js` (`draft ? 'skip' : 'full'`) and `ci-frontend.yml`'s `fall_back` are the two reference implementations of the draft/ready split; `ci-nodejs.yml` and `ci-e2e-playwright.yml` are the reference for always-full.
Foot-gun: if the job that selects tests is cancelled mid-flight, its `mode` output is empty — normalize empty-mode **on a draft** to `skip`, or the draft grabs the full matrix and serializes the ready run behind it.
+### Forcing the full matrix on a draft
+
+The `run-ci-backend` and `run-ci-frontend` labels force the full matrix, but a label alone starts nothing.
+It takes effect on the next push, or when the PR is marked ready for review. An empty commit is enough:
+
+```bash
+git commit --allow-empty -m "chore(ci): run the full matrix" && git push
+```
+
+Do not add `labeled`/`unlabeled` back to a merge gate's `on.pull_request.types` to avoid that push.
+GitHub cannot filter a label trigger by name, so every unrelated label re-runs the full matrices against a commit CI has already covered.
+Guarding it inside the workflow is worse: skipping the gate job cascades to the `if: !cancelled()` aggregator, which counts a skipped dependency as success and posts a green required check with no tests behind it.
+
### A selector needs telemetry, or nobody knows whether it bites
A narrowing that falls back on most runs looks identical in the YAML to one that works.
diff --git a/.agents/skills/editing-agents-md/SKILL.md b/.agents/skills/editing-agents-md/SKILL.md
new file mode 100644
index 000000000000..e2b1e03d3537
--- /dev/null
+++ b/.agents/skills/editing-agents-md/SKILL.md
@@ -0,0 +1,116 @@
+---
+name: editing-agents-md
+description: >
+ Decide whether a rule belongs in an AGENTS.md / CLAUDE.md file, and write it so it holds.
+ Use before adding, editing, or removing any instruction in a root or nested AGENTS.md, when a
+ convention keeps getting broken and someone proposes documenting it, when reviewing a diff that
+ touches one, or when a file has grown and needs a trim. Carries the enforcement-tag convention
+ (`[lint: <id>]` / `[review]`), the six configuration smells to check against, and the size budget.
+ Trigger terms: AGENTS.md, CLAUDE.md, agent instructions, context file, add a rule, document this
+ convention, the file is too long.
+---
+
+# Editing AGENTS.md
+
+The root `AGENTS.md` loads in full at the start of every session, in every tool that reads it.
+A line you add is paid for by every task in the repo, forever, whether or not that task touches the subject.
+So the question is never "is this true?" — it is "is this worth loading into every session?"
+
+Two findings set the frame:
+
+- Adding a context file raises inference cost by over 20% on average, and does not reliably raise task success ([2602.11988](https://arxiv.org/abs/2602.11988)). A second study measured the opposite sign on runtime and tokens ([2601.20404](https://arxiv.org/abs/2601.20404)). The evidence is mixed, which argues for a small sharp file rather than no file.
+- File size, instruction position, file architecture, and contradictions between adjacent files each produced **no detectable effect** on whether an agent follows a rule, across 1,650 sessions ([2605.10039](https://arxiv.org/abs/2605.10039)).
+
+Read the second one carefully, because it kills a whole class of proposals.
+Moving a section higher "so the agent sees it" is churn against a null result.
+Do not reorder for attention. Reorder only when a heading makes a rule easier for a **human** to find or cite.
+
+## 1. Does this belong in the file at all?
+
+Work down this ladder and stop at the first rung that fits. It is the same ladder `AGENTS.md` states for itself.
+
+| Rung | Mechanism | Use when |
+| ---- | ------------------------------------------------------------ | ------------------------------------------------------- |
+| 1 | **Linter** — ruff, oxlint, semgrep (`.semgrep/rules/devex/`) | The violation is a code pattern a matcher can see |
+| 2 | **lint-staged / pre-commit** | It needs the file list or the working tree, not the AST |
+| 3 | **Skill** (`.agents/skills/`) | It applies to one kind of task, not every task |
+| 4 | **A rule in AGENTS.md** | None of the above can carry it |
+
+Rung 4 is the last resort, not the default.
+A convention that a semgrep rule could catch belongs in `.semgrep/rules/devex/` — read its README for the severity choice and the WARNING-to-ERROR ratchet.
+Put the migration playbook in the rule's `message:` field, because that is what an author actually reads when it fires.
+
+Rung 3 is the one people skip most.
+If a rule only matters while merging a PR, writing a migration, or building a workflow, it belongs in that skill, where it loads on demand and can be ten times longer.
+
+## 2. Check the six smells
+
+Measured across 100 popular repositories ([2606.15828](https://arxiv.org/abs/2606.15828)). Prevalence in brackets.
+
+- **Lint leakage [62%]** — the rule restates what a linter already blocks. This is the most common failure by a wide margin. Do not delete the reasoning, but cut it to the reason plus the rule id, and tag it. CI is the check; the prose is only the why.
+- **Context bloat [42%]** — content that does not apply to most sessions. Environment-specific setup, product documentation, anything a `docs/` page should hold. Target is under 200 lines.
+- **Skill leakage [35%]** — task-specific instructions sitting in the always-loaded file instead of a skill.
+- **Conflicting instructions [28%]** — two rules that disagree, often because one aged. Grep for the other statement before you add yours.
+- **Init fossilization [24%]** — text nobody has reviewed since it was generated. If you are editing near a stale rule, verify it still holds and fix it in the same diff.
+- **Blind references [16%]** — a link with no statement of what it holds and when to read it. Every link needs a "read this when …" clause, or an agent has no basis to spend a tool call on it.
+
+## 3. Write the rule as an invariant, not an instruction
+
+The file is read by authors and reviewers alike. An invariant serves both; an instruction has to be translated.
+
+- Say what must be true: "Every tenant-data model must have `team_id`."
+- Not what to do: "Remember to add `team_id` when you make a model."
+
+Be specific and imperative. A vague preference changes nothing.
+"Use `uv pip`, never `pip`" works. "We prefer uv" does not.
+Name the trigger the rule fires on, so a reader scanning a diff knows when it applies.
+
+Keep to the repo's prose conventions: ASD-STE100 Simplified Technical English, active voice, one idea per sentence, semantic line breaks, American English.
+
+## 4. Tag what enforces it
+
+Every rule in **Architecture guidelines** and **Code Style** carries a tag. Extend the convention when you add to those sections.
+
+```markdown
+- **Do not use `Team` or `Organization` rows as mutexes.** `[lint: hot-parent-row-select-for-update]` PostgreSQL takes …
+- **There is no implicit per-request transaction.** `[review]` PostHog does not enable `ATOMIC_REQUESTS` …
+```
+
+- `[lint: <id>]` — a semgrep rule id, a `ruff <CODE>`, or an invariant test filename. A reviewer skips it, because CI is the gate.
+- `[review]` — nothing catches this. A reader is the only control, so it earns its place in the file.
+
+Every rule in those two sections carries one of the two tags, and every tag must resolve against the repo.
+`posthog/test/repo_invariants/test_agents_md_enforcement_tags.py` fails the build on an untagged rule, and on a `[lint: …]` that names a rule, code, or file which no longer enforces anything.
+A ruff code moved to the `ignore` list stops counting, so a tag cannot survive its rule being switched off.
+That is the point: a stale tag is worse than no tag, because a reviewer trusts it and skips the check.
+When a tag names a command or a CI job rather than a single rule id, add it to `FREE_FORM` in that test — deliberately, not to silence a typo.
+
+A rule that stays `[review]` for a long time is a candidate for rung 1. That visibility is half the reason the tags exist.
+
+## 5. Root or nested?
+
+Both files get the same smells check. The budget differs.
+
+**Root `AGENTS.md`** — loads every session, in every tool, for every task. Strict. A rule earns its place only if it applies across the repo, or if getting it wrong is expensive and nothing catches it (the public-repo rules are the model). Keep the enforcement tags current.
+
+**Nested `AGENTS.md`** (about 27 of them: `posthog/temporal/`, `rust/`, `frontend/src/`, most of `products/`) — loads when an agent works in that subtree, so a local convention is cheap here and expensive in the root. Move a directory-specific rule down rather than up. No tag convention required, though it does no harm.
+
+Never state the same rule in both. That is how conflicting instructions start.
+
+## 6. Before you commit
+
+- The rule is on rung 4 because rungs 1 to 3 genuinely do not fit.
+- It reads as an invariant, with a trigger a reader can spot in a diff.
+- It is tagged, if it sits in Architecture guidelines or Code Style.
+- No other line in the file, or in a nested `AGENTS.md`, says something different.
+- Every link you added says when to read it.
+- Every link and skill reference resolves:
+
+```sh
+grep -oE '\]\(([a-zA-Z0-9_./-]+\.md[^)]*)\)' AGENTS.md | sed 's/](//;s/)$//;s/#.*//' | sort -u \
+ | while read -r f; do [ -e "$f" ] || echo "MISSING: $f"; done
+
+hogli test posthog/test/repo_invariants/test_agents_md_enforcement_tags.py
+```
+
+- The file got shorter, or you can say what the added characters buy every session in the repo.
diff --git a/.agents/skills/merging-prs/SKILL.md b/.agents/skills/merging-prs/SKILL.md
index 10475b0cd109..eec19dce18ad 100644
--- a/.agents/skills/merging-prs/SKILL.md
+++ b/.agents/skills/merging-prs/SKILL.md
@@ -151,6 +151,17 @@ gh pr comment <n> --body "/trunk cancel"
Confirm the check run reports cancelled.
+## The pre-push merge queue guard
+
+A pre-push hook refuses to push a branch whose PR sits in the queue, because that push would knock the PR out.
+A PR whose batch failed and waits for a retest does not block — Trunk drops it from the queue on push, which is what you want after a failure.
+
+When the guard blocks you, leave the branch alone and put further changes on a new branch with a new PR.
+To update the queued PR on purpose, run `trunk merge cancel <n>` (or comment `/trunk cancel`), wait for it to leave the queue, then push.
+
+The check fails open — missing `gh` or `trunk`, not logged in, offline, API errors — and `TRUNK_QUEUE_PUSH_CHECK_DISABLED=1` skips it.
+`trunk login` arms it, which is why the one-time interactive login is worth running even if you prefer the PR comments.
+
## Hard rules
- **Never** run `gh pr merge` — it's blocked and it's not how this repo merges.
diff --git a/.claude/rules/agents-md.md b/.claude/rules/agents-md.md
new file mode 100644
index 000000000000..7e2f60f36d58
--- /dev/null
+++ b/.claude/rules/agents-md.md
@@ -0,0 +1,18 @@
+---
+paths:
+ - 'AGENTS.md'
+ - 'CLAUDE.md'
+ - '**/AGENTS.md'
+ - '**/CLAUDE.md'
+---
+
+Invoke the `/editing-agents-md` skill before adding, editing, or removing any instruction here.
+
+The root file loads in full at the start of every session, so a line added to it is paid for by
+every task in the repo. The skill carries the ladder that decides whether a rule belongs in a
+linter, a skill, or this file at all; the six smells to check the diff against; and the
+`[lint: <id>]` / `[review]` tag convention that the root file's Architecture guidelines and Code
+Style sections use.
+
+Do not reorder sections to make a rule more prominent — instruction position has no measured
+effect on whether an agent follows it. Reorder only to help a human find or cite a rule.
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.yml
index 8448fcfdab15..cd13ceb820f5 100644
--- a/.depot/workflows/ci-backend.yml
+++ b/.depot/workflows/ci-backend.yml
@@ -301,6 +301,7 @@ jobs:
legacy: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && 'true' || (steps.filter.outputs.legacy || 'true') }}
schema: ${{ steps.filter.outputs.schema || 'true' }}
product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}
+ repo_invariants: ${{ steps.filter.outputs.repo_invariants || 'false' }}
product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}
steps:
# For pull requests it's not necessary to checkout the code, but we
@@ -520,6 +521,17 @@ jobs:
- 'posthog/product_db_router.py'
tasks_temporal:
- 'products/tasks/backend/temporal/**/*'
+ repo_invariants:
+ # posthog/test/repo_invariants/ reads AGENTS.md and the semgrep
+ # rule ids it names. Both are excluded from the backend filter
+ # (markdown is dropped outright, .semgrep is not listed), so a
+ # change to either would skip repo-checks and report green while
+ # leaving a tag pointing at a rule that no longer exists.
+ - 'AGENTS.md'
+ - '.semgrep/**'
+ - 'pyproject.toml'
+ - 'products/ruff.toml'
+ - '.github/scripts/**'
product_yamls:
- 'products/*/product.yaml'
- '**/owners.yaml'
@@ -1133,7 +1145,7 @@ jobs:
repo-checks:
needs: [changes]
# product_yamls: ownership-only PRs still need the owners.yaml lint below.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true') && github.event_name != 'push'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'push'
timeout-minutes: 10
permissions:
contents: read
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index f81ea1f8129e..147f4fc10943 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -136,6 +136,7 @@ jobs:
legacy: ${{ contains(github.event.pull_request.labels.*.name, 'run-ci-backend') && 'true' || (steps.filter.outputs.legacy || 'true') }}
schema: ${{ steps.filter.outputs.schema || 'true' }}
product_yamls: ${{ steps.filter.outputs.product_yamls || 'false' }}
+ repo_invariants: ${{ steps.filter.outputs.repo_invariants || 'false' }}
product_yamls_files: ${{ steps.filter.outputs.product_yamls_files }}
timing_scripts: ${{ steps.filter.outputs.timing_scripts }}
steps:
@@ -359,6 +360,17 @@ jobs:
- '.github/scripts/turbo-discover.js'
tasks_temporal:
- 'products/tasks/backend/temporal/**/*'
+ repo_invariants:
+ # posthog/test/repo_invariants/ reads AGENTS.md and the semgrep
+ # rule ids it names. Both are excluded from the backend filter
+ # (markdown is dropped outright, .semgrep is not listed), so a
+ # change to either would skip repo-checks and report green while
+ # leaving a tag pointing at a rule that no longer exists.
+ - 'AGENTS.md'
+ - '.semgrep/**'
+ - 'pyproject.toml'
+ - 'products/ruff.toml'
+ - '.github/scripts/**'
product_yamls:
# Validates owner team slugs against PostHog/posthog collaborator teams,
# and lints the distributed owners.yaml files (schema, conflicts, dead
@@ -1246,7 +1258,7 @@ jobs:
needs: [changes]
# product_yamls: ownership-only PRs still need the owners.yaml lint below.
# A per-commit check — the hourly scheduled run skips it as already covered.
- if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true') && github.event_name != 'schedule'
+ if: (needs.changes.outputs.backend == 'true' || needs.changes.outputs.product_yamls == 'true' || needs.changes.outputs.repo_invariants == 'true') && github.event_name != 'schedule'
timeout-minutes: 10
outputs:
deterministic_failure: ${{ steps.deterministic-failure.outputs.deterministic_failure || 'false' }}
diff --git a/AGENTS.md b/AGENTS.md
index 203d9080f6b6..0e4c42fa6b70 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -3,16 +3,16 @@
## Codebase Structure
- Key entry points: `posthog/api/__init__.py` (API URL routing skeleton; products register their own routes in `products/<name>/backend/routes.py` via `register_routes(routers)`), `posthog/settings/web.py` (Django settings, INSTALLED_APPS), `products/` (product apps)
-- [Monorepo layout](docs/internal/monorepo-layout.md) - high-level directory structure (products, services, common, tools)
-- [Products README](products/README.md) - how to create and structure products
-- [Products architecture](products/architecture.md) - DTOs, facades, isolated testing
+- [Monorepo layout](docs/internal/monorepo-layout.md) — read when you need to place a new directory, or to work out which tree owns something (products, services, common, tools)
+- [Products README](products/README.md) — read before creating a product or changing one's structure; covers the isolation rules `product:lint` enforces
+- [Products architecture](products/architecture.md) — read when designing a product's DTOs, facade, or contract with the rest of the repo
+- A directory may carry its own `AGENTS.md` that wins locally (`posthog/temporal/`, `rust/`, `frontend/src/`, most of `products/`). Check for one before working in an unfamiliar tree.
## Commands
- Environment:
- - This is a full dev environment, not a restricted patch-editing sandbox — it has `node`, `pnpm`, a package mirror, and `apt`, so tools and dependencies that aren't present yet can be installed, and tests, Storybook, and the app can actually be run. A missing `node_modules`, browser binary, or flox usually just means setup hasn't run yet (`pnpm install`, `npx playwright install --with-deps chromium`, or building the nested `@posthog/quill` workspace that `global.scss` imports), rather than that running things is impossible.
- - So the absence of a tool isn't evidence that a task can't be done — installing it is the first step. The honest signal that something genuinely can't run is an attempt that fails for a specific, nameable reason (no network access, `apt` unavailable, out of memory), which is worth reporting alongside whatever fallback you take.
- - This matters most for visual and UX work, where reading the code isn't the same as seeing the result. Rendering the affected surface (for example in Storybook via a headless browser) and comparing before and after is what actually confirms such a change, and is usually worth the setup cost.
+ - This is a full dev environment with `node`, `pnpm`, a package mirror and `apt`. A missing `node_modules`, browser binary or flox means setup has not run yet (`pnpm install`, `npx playwright install --with-deps chromium`), not that running things is impossible — install it and continue. Report "can't run" only for a specific, nameable failure (no network, no `apt`, out of memory), alongside whatever fallback you took.
+ - Visual and UX work is not confirmed by reading the code. Render the affected surface (Storybook via a headless browser) and compare before and after. Worth the setup cost.
- Use flox when available — prefer `flox activate -- bash -c "<command>"` if commands fail
- Never use `flox activate` in interactive sessions (it hangs if you try)
- Tests:
@@ -28,10 +28,7 @@
- Build:
- Frontend: `pnpm --filter=@posthog/frontend build`
- Start dev: `./bin/start` or `hogli start` (interactive TUI). Detached mode: `hogli up -d` paired with `hogli wait` / `hogli down`
- - Cloud task VMs (prebaked dev-stack image): run `bootstrap-dev-stack` first (restores compose host aliases, starts dockerd), then `uv sync`, `source .venv/bin/activate`, `hogli start -y -d`, and `hogli wait` (the detached start returns while the stack is still booting; `hogli wait` blocks until every process is ready) — always detached: the sandbox has no TTY, and phrocs under a pseudo-TTY balloons in memory until OOM-killed
- - Cloud task VMs: on user-created runs the backend usually starts the stack itself. While it does, `hogli start` exits without starting anything. Poll `/tmp/posthog-preview/status.json` until `state` is `ready` or `failed`. On `ready`, run `hogli wait`; it reports `not reachable` until the backend reaches the phrocs step, so retry it rather than forcing a second start. On `failed` (the backend does not retry), start the stack yourself with `hogli start -y -d`
- - Cloud task VMs, frontend work: `pnpm install --frozen-lockfile --prefer-offline` links from the prebaked pnpm store, and Playwright Chromium is preinstalled; product/Storybook builds still run from source
- - Cloud task VMs, tests: scope every run to what you changed, with `hogli test --changed` or the test files that cover the touched code. Run a whole module, package, or repo-wide suite at most once, right before you push, and only for a cross-cutting change. CI runs the full matrix; repeating it in the sandbox costs minutes per run and floods the context with output. In a sandbox `hogli test` runs pytest with `-q` (set `HOGLI_TEST_VERBOSE=1` to stream prints). `pytest.ini` already enables `--reuse-db`, and the prebaked dev-stack image seeds `test_posthog`; do not pass `--create-db` or override pytest `addopts`, because either discards the prewarmed schema. If pytest starts the full migration history, the VM image predates the database seed or the test database was replaced. Let that migration finish before retrying; interrupting it leaves a partial database that the next run must continue migrating.
+ - In a PostHog Tasks cloud run (`POSTHOG_TASK_RUN_ID` set), the boot sequence, prewarmed test database and scoped-test rules differ — read [Cloud task sandbox](docs/internal/cloud-task-sandbox.md) before starting the stack or running tests there
- OpenAPI/types: `hogli build:openapi` (regenerate after changing serializers/viewsets)
- LSP: Pyright is configured against the flox venv. Prefer LSP (`goToDefinition`, `findReferences`, `hover`) over grep when navigating or refactoring Python code.
- Dev experience feedback: `hogli devex:feedback "<message>"` sends feedback about repo tooling — hogli, the dev stack, tests, CI, migrations, this setup — straight to the devex team as a `hogli_feedback` event (add `-c bug|idea|praise|question`).
@@ -64,11 +61,10 @@ Examples:
### PR descriptions
-**Required:** Before creating any PR, read `.github/pull_request_template.md` and use its exact section structure.
-Do not invent a different format.
-**Shape:** invoke `/writing-pr-descriptions` before writing the body. Lead with the effect a person sees rather than the code path behind it, and hold Changes to that too: a bullet a person can notice says what they now see or do differently, and one line says which part is mechanical. Make the body stand alone for a reader who opens no files, and let its size track the change. Then one fact per bullet, sentences under 25 words, active voice, no idioms. A description that got longer as bullets was not cut.
-Always fill the `## 🤖 Agent context` section when creating PRs.
-NEVER share sensitive information in a PR description. Users may share sensitive data in an agent session, but those should never surface to a PR description, or comments.
+**Required:** Read `.github/pull_request_template.md` and use its exact section structure. Do not invent a different format.
+Invoke `/writing-pr-descriptions` before writing the body — it carries the shape rules.
+Always fill the `## 🤖 Agent context` section.
+NEVER put sensitive information in a PR description or comment. A user may share sensitive data in an agent session; none of it belongs on the PR.
**Screenshots:** Upload frontend/visual changes with `hogli pr:upload-image <file>` and embed the printed markdown. The first run only warns and uploads nothing; re-run with `--yes` to confirm. Only PostHog employees can upload, but the public can permanently view these assets, so only upload the image if you're certain it doesn't contain customer data (including customer names), secrets, or sensitive internal info.
@@ -89,66 +85,28 @@ That makes the first push of a branch the decision point, not a step you correct
So if any part of the work drew on something from your session rather than from this repository — a customer conversation, a support ticket, a log, an internal thread — check what is actually in the diff before that first push.
See [Public open source repo guidance](#public-open-source-repo-guidance) for what has to clear the bar.
-#### Forcing the full CI matrix on a draft
+#### Before you push
-Draft PRs run a narrowed matrix.
-The `run-ci-backend` and `run-ci-frontend` labels force the full one, but a label alone starts nothing: it takes effect on the next push, or when the PR is marked ready for review.
-An empty commit is enough.
-
-```bash
-git commit --allow-empty -m "chore(ci): run the full matrix" && git push
-```
-
-Do not add `labeled`/`unlabeled` back to a merge gate's `on.pull_request.types` to avoid that push.
-GitHub cannot filter a label trigger by name, so every unrelated label re-runs the full matrices against a commit CI has already covered.
-Guarding it inside the workflow is worse: skipping the gate job cascades to the `if: !cancelled()` aggregator, which counts a skipped dependency as success and posts a green required check with no tests behind it.
+- **Never bypass the pre-push hooks** (`--no-verify`). They run `hogli ci:preflight --strict` and a merge-queue guard. When one blocks you, fix what it reports — `/running-ci-preflight` has the loop, `/merging-prs` explains the queue guard.
+- **Never force-push a branch that is in the merge queue** — it removes the PR from the queue. That includes restacking a stack whose base is queued.
+- Draft PRs run a narrowed CI matrix. To force the full one, see "Forcing the full matrix on a draft" in `/authoring-ci-workflows`.
#### Stacked PRs
-GitHub's native stacked PRs are enabled on this repo — use the `gh stack` CLI and the `/stacking-prs` skill instead of hand-managing branch chains.
-A stack lands through the merge queue only after explicit user approval in the current conversation: comment `/trunk merge` on the top layer to enqueue the whole stack (the queue tests and merges it and every unmerged layer below it atomically), or land bottom-first one layer at a time; either way, `gh stack sync --prune` afterwards.
-Never `gh stack merge` — it merges the whole chain straight through GitHub's API, so the stack reaches `master` outside the queue.
-
-Restacking force-pushes every branch, and each push triggers a full CI fan-out.
-Never restack while any branch in the stack is sitting in the merge queue — the force-push removes it from the queue.
-Pushing a deep stack at once can exceed GitHub's per-repo dispatch cap (500 workflow runs / 10s).
-The overflow fails as `startup_failure` and takes unrelated runs in the same window down too.
-Draft status doesn't help, since runs are dispatched before draft/skip logic applies.
-
-- Keep stacks shallow; merge the base before extending.
-- Restack only when you need to, rather than rebasing the whole stack on master repeatedly.
-- When a restack must push many branches, stagger them instead of force-pushing all at once.
-
-#### Pre-push checks — merge queue guard
-
-The pre-push hook refuses to push a branch whose PR is sitting in the Trunk merge queue — a push there would knock the PR out of the queue.
-A PR whose batch failed and is waiting for a retest does not block, so you can push a fix then — Trunk drops the PR from the queue on push, which is what you want after a failure.
-When it blocks you, leave the branch alone and put further changes on a new branch with a new PR; to intentionally update the queued PR instead, run `trunk merge cancel <number>` (or comment `/trunk cancel`), wait for it to leave the queue, then push.
-The check fails open (missing `gh` or `trunk`, not logged in, offline, API errors), and `TRUNK_QUEUE_PUSH_CHECK_DISABLED=1` skips it.
-
-#### Pre-push checks — ci:preflight
-
-A pre-push hook runs `hogli ci:preflight --strict`, failing the push on deterministic CI breakage reachable from your diff (lint, lockfiles, migration conflicts). Never bypass it (`--no-verify`).
-If it blocks the push, run `hogli ci:preflight --fix`, resolve the remaining `✗ fail` lines, act on the `→ advisory` ones (regenerate OpenAPI types, merge master in), and push again.
-Advisories never block the push; in a cloud task sandbox, do not boot the dev stack only to clear one.
-In environments without hooks (no `node_modules`), run `hogli ci:preflight --fix` yourself before pushing or reporting a task done. If the command reports it is disabled, that's intentional — proceed.
+GitHub's native stacked PRs are enabled here. Use the `gh stack` CLI and `/stacking-prs` rather than hand-managing branch chains.
+Keep stacks shallow and merge the base before extending: restacking force-pushes every branch, and a deep stack pushed at once can exceed GitHub's dispatch cap and fail unrelated runs with it.
+Never `gh stack merge` — it lands the chain through GitHub's API, outside the queue.
### Merging PRs
All merges into `master` go through the Trunk merge queue.
Never run `gh pr merge` or click the GitHub merge button — both are blocked by branch ruleset.
-Agents must not enqueue, merge, re-enqueue, or otherwise cause a PR to land without explicit user approval in the current conversation for the identified PR or stack. Do not infer that approval from requests to prepare a PR, move it toward merge, make it ready, monitor it, or resolve its blockers. Agents may inspect status, fix code and CI, apply `stamphog` when approval is missing, and report that a PR is ready; then they must wait for a direct instruction to merge or enqueue it.
+**Agents must not enqueue, merge, re-enqueue, or otherwise cause a PR to land without explicit user approval in the current conversation for the identified PR or stack.**
+Do not infer that approval from requests to prepare a PR, move it toward merge, make it ready, monitor it, or resolve its blockers.
+Agents may inspect status, fix code and CI, apply the `stamphog` label when a required approval is missing, and report that a PR is ready — then wait for a direct instruction.
-- After explicit user approval: enqueue with `gh pr comment <number> --body "/trunk merge"`. Cancel: `gh pr comment <number> --body "/trunk cancel"`. Enqueueing a stacked PR also enqueues every unmerged layer below it — comment on the top PR to merge the whole stack. `--no-batch` opts the PR (or stack) out of batching.
-- The Trunk CLI is an alternative to the comments: `trunk merge <number>` enqueues, `trunk merge status <number>` inspects, `trunk merge cancel <number>` dequeues. `status` is also the only place Trunk's own reason for each queue transition is visible — a conflict, a PR that skipped the line, a human cancellation, the check that removed it — so read it before reconstructing a cause from CI, and see `/triaging-merge-queue-failures`. It ships in the flox environment and needs a one-time interactive `trunk login` — run it once even if you prefer the comments, because the same login arms the pre-push merge-queue guard that stops you from knocking a queued PR out of the queue. Agents and headless environments that can't complete the interactive login use the comments.
-- Missing required approval: apply the `stamphog` label (`gh pr edit <number> --add-label stamphog`) to trigger the automated review-and-approve flow, and re-apply it whenever it was stripped (`REFUSED`/`ESCALATE` verdict) once the feedback is addressed — re-applying is always safe.
-- After enqueueing, babysit the PR until it merges or fails — follow [`.agents/skills/merging-prs/SKILL.md`](./.agents/skills/merging-prs/SKILL.md) for the preflight, watch, and failure-handling loop.
-- Trunk publishes **no check run** in this repository, so there is nothing on the PR's head that reports queue progress.
- Read progress from `trunk merge status <number>`, or from the `trunk-io[bot]` sticky comment on the PR.
- The PR's own checks don't reflect the queue's testing either, because the queue runs CI on a `trunk-merge/**` branch.
-- On failure the Trunk bot comments with links to the failing workflows; fix and push if appropriate, then wait for explicit user approval before re-enqueueing.
-- Never force-push a branch while it is in the queue — it removes the PR from the queue.
+Once approved, follow `/merging-prs` for the enqueue, watch and failure loop. It also covers why the PR's own checks never show queue progress.
### Public open source repo guidance
@@ -177,64 +135,106 @@ Examples:
- `.nvmrc` controls the Node.js version for all CI workflows (via `actions/setup-node`) — changing it affects every CI job that runs Node
- CI uploads test results to Trunk Flaky Tests; the `trunk` MCP server in `.mcp.json` queries per-test flakiness on a PR or `master` (authenticate via `/mcp`, or a `TRUNK_API_TOKEN` bearer header when headless) — see `/debugging-ci-failures` and `/fixing-flaky-tests`
-- Every job in `.github/workflows/` must declare `timeout-minutes` — prevents stuck runners from burning credits indefinitely
-- **CI workflow changes must stay backwards compatible with open PRs that haven't rebased.** A workflow edit hits every in-flight PR immediately (it runs against the PR merged with master), but companion changes — a new dependency, file, or config — only reach a branch once it rebases. If the workflow starts requiring something an unrebased branch lacks, every such PR fails before its tests run. Make the new behavior degrade gracefully when the prerequisite is absent, or gate it so unrebased branches are unaffected. This has broken CI repeatedly.
+- **A workflow edit reaches every open PR before those branches rebase.** It runs against the PR merged with master, but a companion change — a new dependency, file, or config — only arrives when the branch rebases. A workflow that starts requiring something unrebased branches lack fails every in-flight PR before its tests run. Make the new behavior degrade gracefully, or gate it. This has broken CI repeatedly.
+- Mechanical workflow rules (`timeout-minutes`, concurrency, dispatch budget, path filters, gate hygiene) are enforced by `hogli lint:workflows` and actionlint, which are the source of truth. `/authoring-ci-workflows` explains the reasoning behind each.
## Security
-See [.agents/security.md](.agents/security.md) for security guidelines — least privilege, secrets & service-to-service auth (don't add new `INTERNAL_API_SECRET` callers), SQL, HogQL, and semgrep.
+Do not add new `INTERNAL_API_SECRET` callers.
+Read [.agents/security.md](.agents/security.md) before touching auth, secrets, service-to-service calls, raw SQL, or HogQL string building — it covers least privilege, the injection rules, and how to respond when semgrep flags your code.
+`.semgrep/rules/security/` is the enforced set; run `semgrep --config .semgrep/rules/security/ .` to check a change locally.
## Architecture guidelines
-- **Keep entrypoints thin.** The runtime calls the entrypoint first. Examples: a DRF view, a management command `handle()`, a Celery task body, an HTTP handler, a Rust `main()`, and a React component. An entrypoint reads the input, connects the dependencies, and formats the output. Put all other logic in a function that the entrypoint calls. Call that function directly in a test. If you cannot do this, move the logic out of the entrypoint. If the area already has a place for that logic, use it. Do not make a new one.
-- API views should declare request/response schemas — prefer `@validated_request` from `posthog.api.mixins` or `@extend_schema` from drf-spectacular. Plain `ViewSet` methods that validate manually need `@extend_schema(request=YourSerializer)` — without it, drf-spectacular can't discover the request body and generated code gets empty schemas
-- Django serializers are the source of truth for frontend API types — `hogli build:openapi` generates TypeScript via drf-spectacular + Orval. Generated files (`api.schemas.ts`, `api.ts`, `api.zod.ts`) live in `frontend/src/generated/core/` and `products/{product}/frontend/generated/` — don't edit them manually, change serializers and rerun. See [type system guide](docs/published/handbook/engineering/type-system.md) for the full pipeline
-- MCP tools are generated from the same OpenAPI spec — see [implementing MCP tools](docs/published/handbook/engineering/ai/implementing-mcp-tools.md) for the YAML config and codegen workflow
-- MCP UI apps (interactive visualizations for tool results) are defined in `products/*/mcp/tools.yaml` under `ui_apps` and auto-generated — see [services/mcp/CONTRIBUTING.md](services/mcp/CONTRIBUTING.md) or use the `implementing-mcp-ui-apps` skill
-- When touching a viewset or serializer, ensure schema annotations are present (`@extend_schema` or `@validated_request` on viewset methods, `help_text` on serializer fields) — these flow into generated frontend types and MCP tool schemas
-- New features should live in `products/`. **Create one with `hogli product:bootstrap <name>` — never hand-roll the directory.** The scaffold emits a product that is isolated from its first commit, and `product:lint --all` fails on a new product that is not (see "New products must be isolated" in [products/README.md](products/README.md); [products/architecture.md](products/architecture.md) covers the facade and contract design). Code a single product owns — not just backend/frontend, but scripts, CLIs, services, packages, MCP tools, skills — belongs under `products/<product>/`; reserve top-level `tools/`/`services/`/`packages/`/`cli/` for cross-product things
-- **Every tenant-data model must have `team_id`** — either as a FK (`models.ForeignKey("posthog.Team", ...)`) or a plain `BigIntegerField` (for multi-DB products). This is the primary tenant isolation boundary. Models without `team_id` must be org-scoped, user-scoped, or instance-global — never silently unscoped. New models should inherit from `TeamScopedRootMixin` (main DB) or `ProductTeamModel` (separate DB) so they start fail-closed — see `posthog/models/scoping/README.md`. CI enforces this via `posthog/models/scoping/baseline_unmigrated.txt`: any new team-scoped model not on a fail-closed manager fails the IDOR coverage check. In serializers, access the team via `self.context["get_team"]()`. When querying a fail-closed model for one team outside request context (Temporal activities, Celery tasks, management commands), use `Model.objects.for_team(team_id)` — not `Model.all_teams.filter(team_id=...)` or `objects.unscoped().filter(...)`; reserve `all_teams`/`unscoped()` for genuinely cross-team access and Django framework internals. Caveat: `for_team(...).get_or_create(...)`/`.create(...)` still need `team_id` passed explicitly — queryset filters don't propagate into row creation
-- **Do not add domain-specific fields to the `Team` model.** Use a Team Extension model instead — see `posthog/models/team/README.md` for the pattern and helpers
-- **PostHog event capture in Celery tasks:** Do not use `posthoganalytics.capture()` in Celery tasks — events are silently lost. Use `ph_scoped_capture` from `posthog.ph_client` instead (see its docstring for why and usage).
-- **Django admin `ForeignKey` fields need explicit widget config.** When adding a `ForeignKey`/`OneToOneField` to a model that's exposed in Django admin (including via inlines attached to a _related_ admin), list the new field in `autocomplete_fields`, `raw_id_fields`, or `readonly_fields` on **every** admin class that renders the model — otherwise the default `<select>` widget loads the entire target table per row on each change-page render. Prefer declaring the config on a shared base inline so per-parent variants (e.g., subclasses differentiated by `fk_name`) inherit it automatically.
-- **Use personhog client for all person/group data access — do not query persons DB tables via the Django ORM or raw SQL.** The `posthog/personhog_client/` gRPC client is the required interface for reading and writing person-related data. This applies to the following tables: `posthog_person`, `posthog_persondistinctid`, `posthog_cohortpeople`, `posthog_group`, `posthog_grouptypemapping`, and related override tables (`posthog_personoverride`, `posthog_pendingpersonoverride`, `posthog_flatpersonoverride`, `posthog_featureflaghashkeyoverride`, `posthog_personlessdistinctid`, `posthog_personoverridemapping`). Use the helpers in `posthog/models/person/util.py` (e.g. `get_person_by_uuid`, `get_persons_by_distinct_ids`, `get_person_by_distinct_id`) and `posthog/models/group_type_mapping.py` (`get_group_types_for_project`) — these already route through personhog with ORM fallback via `_personhog_routed()`. When adding new person/group data access, follow the same `_personhog_routed()` pattern: provide a `personhog_fn` using `get_personhog_client()` and an `orm_fn` fallback. Never add new direct ORM queries like `Person.objects.filter(...)` or `PersonDistinctId.objects.filter(...)` — use the existing routed helpers or create new ones following the established pattern. See `posthog/personhog_client/README.md` for client details and `posthog/personhog_client/client.py` for the full RPC interface.
-- **Personhog is for identity questions only; person properties and bulk person reads come from ClickHouse.** Use personhog for resolving distinct IDs to persons, point lookups by person id/UUID, and lifecycle writes. Use ClickHouse (HogQL over the `persons` table, `ActorsQueryRunner`) for loading person properties, hydrating lists of persons, and searching/filtering persons. Avoid reading the `properties` field from personhog where possible — the API will eventually stop surfacing it to users; single-person point lookups that need properties are exempt only while no ClickHouse primitive covers them, and never in bulk. See [docs/internal/person-data-access.md](docs/internal/person-data-access.md).
-- **PostHog does not enable `ATOMIC_REQUESTS` — there is no implicit per-request transaction.** Each database operation runs in autocommit mode unless explicitly wrapped. Use `with transaction.atomic():` around the specific writes that must succeed or fail together. Do not wrap an entire view method atomically — keep the block as narrow as possible around the related writes. Avoid performing irreversible side effects (sending emails, calling external APIs, enqueuing Celery tasks) inside an atomic block: if the transaction rolls back, those side effects have already happened. Schedule such side effects after the commit, or use `transaction.on_commit()` for Celery task dispatch.
-- **Do not use `Team` or `Organization` rows as mutexes.** PostgreSQL can take `KEY SHARE` locks on parent rows for foreign-key checks, and `FOR UPDATE` conflicts with them. An unrelated child-row write can therefore wait behind a transaction that locks a hot parent row. Where the lock guards one product's per-team settings, lock that product's `Team<Product>Config` extension row instead, and reach it through `get_or_create_team_extension` so the row exists before you lock it (see [posthog/models/team/README.md](posthog/models/team/README.md)). Contention then reaches only the writers of that one config, not every writer of a table that points at `Team`. Where the lock enforces a per-team count limit or allocates a per-team number, use a unique constraint, a conditional update, or a dedicated allocation row for that resource. Otherwise lock the quiet child or control row for the serialized resource, or take a transaction-scoped advisory lock keyed to it. Lock `Team` or `Organization` only when the transaction updates or deletes that parent row. Keep that transaction short, with no network calls or input-sized Python loops. The `hot-parent-row-select-for-update` Semgrep rule requires each exception to include a short `nosemgrep` justification.
-- **Object storage is SeaweedFS — do not add new MinIO dependencies.** Both S3-compatible stores in the dev/CI stack are SeaweedFS: the `objectstorage` service (S3 API on `:19000`) backs general object storage (`OBJECT_STORAGE_*` settings — exports, media uploads, error-tracking source maps, query cache, tasks), and the `seaweedfs` service (S3 API on `:8333`) backs session replay v2 (`SESSION_RECORDING_V2_S3_*` settings). MinIO now survives only as migration tooling: `docker-compose.hobby.yml` keeps it as a source for `bin/migrate-storage-hobby`, and `bin/upgrade-objectstorage` starts a throwaway MinIO to salvage objects off the pre-swap volume. Outside that, don't add docker-compose services, scripts, tests, or docs that stand up a `minio/minio` container. Code that talks to object storage should go through the existing `OBJECT_STORAGE_*` / `SESSION_RECORDING_V2_S3_*` config and a standard S3 client rather than hardcoding an endpoint — that keeps backends swappable. Note the `objectstorage` service registers its credentials at runtime via a bootstrap loop and returns `InvalidAccessKeyId` until that completes, so anything depending on it must wait for its readiness sentinel rather than just for the container to start.
-- **Temporal activity payloads have a ~2 MiB hard limit — pass large data by reference, not by value.** Activity inputs and outputs are serialized across a gRPC boundary that Temporal caps at ~2 MiB per payload (the server rejects larger payloads via `blobSizeLimitError`). As a conservative field-level rule, if a field could exceed ~256 KB once serialized (serialized query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres / S3 / object storage from _inside_ the activity and return only the reference (row ID, S3 key). The workflow already has access to any row ID created earlier in the same run; it does not need the content to flow back through. Shuttling large data through the workflow on the way to persistence is a foreseeable failure mode that produces `PayloadSizeError` (`TMPRL1103`) the moment the underlying data crosses the limit.
-- **Outbound calls to a third-party API that need rate-limiting or egress telemetry belong in `posthog/egress/` — add a `<domain>/` incarnation (GitHub is the reference) and route callers through its gated, recorded transport, never hand-rolled `requests`. See `posthog/egress/README.md`.**
-- **`services/llm-gateway` is under an unofficial code freeze while callers move to [`PostHog/ai-gateway`](https://github.com/PostHog/ai-gateway).** New callers and features belong on the Go gateway by default. A Python gateway change needs a documented parity blocker for an active caller and must stay limited to that blocker. Read [`services/llm-gateway/PARITY.md`](services/llm-gateway/PARITY.md). Invoke `/auditing-llm-gateway-parity` for gateway contract changes and parity refreshes, `/finding-llm-gateway-migration-candidates` when deciding what to migrate next, and `/migrating-llm-gateway-callers` when moving a selected caller. The gateway's Postgres role reads only an allowlisted set of tables, with grants maintained in posthog-cloud-infra: a new table read needs the SELECT grant landed there for every environment first, then a declaration in `services/llm-gateway/src/llm_gateway/db/required_tables.py`, which a test binds to the package's SQL. The readiness probe verifies the connected role holds every declared grant on every probe, so a missing grant holds a rollout, and a revoked grant unreadies the running fleet, instead of serving 500s.
+Each rule is tagged with what catches a violation.
+`[lint: <id>]` means a linter, semgrep rule, or invariant test blocks it, so CI is the check and this text is only the reasoning.
+`[review]` means nothing catches it automatically — a reader is the only control.
+
+### Entrypoints and layering
+
+- **Keep entrypoints thin.** `[review]` The runtime calls the entrypoint first: a DRF view, a management command `handle()`, a Celery task body, an HTTP handler, a Rust `main()`, a React component. An entrypoint reads the input, connects the dependencies, and formats the output. All other logic goes in a function the entrypoint calls, so a test can call it directly. If the area already has a place for that logic, use it rather than making a new one.
+- **A product under `products/` is scaffolded, not hand-rolled.** `[lint: hogli product:lint --all]` Create one with `hogli product:bootstrap <name>`, because the scaffold emits a product that is isolated from its first commit. See "New products must be isolated" in [products/README.md](products/README.md) for the isolation rules, and [products/architecture.md](products/architecture.md) for facade and contract design.
+- **Code a single product owns belongs under `products/<product>/`** — backend, frontend, scripts, CLIs, services, packages, MCP tools, skills. `[review]` Reserve top-level `tools/`, `services/`, `packages/` and `cli/` for cross-product things. `product:lint` only scans `products/`, so a single-product feature parked in a top-level directory is invisible to it.
+
+### Tenancy and scoping
+
+- **Every tenant-data model must have `team_id`**, as a FK to `posthog.Team` or a plain `BigIntegerField` for multi-DB products. `[lint: idor-lookup-without-team, check-idor-model-coverage.py]` This is the primary tenant isolation boundary. New models inherit `TeamScopedRootMixin` (main DB) or `ProductTeamModel` (separate DB) so they start fail-closed — see [posthog/models/scoping/README.md](posthog/models/scoping/README.md).
+- **Classifying a model as unscoped is a review decision, not a checked one.** `[review]` A model without `team_id` must be org-scoped, user-scoped, or instance-global, never silently unscoped. `check-idor-model-coverage.py` only warns when a name lands in `NEEDS_TEAM_ID`, and passes silently for `LEGITIMATELY_UNSCOPED`, so a wrongly exempted tenant model reaches master unless a reader catches it.
+- **Reading a fail-closed model outside request context** — Temporal activities, Celery tasks, management commands — uses `Model.objects.for_team(team_id)`. `[review]` Not `Model.all_teams.filter(team_id=...)` and not `objects.unscoped().filter(...)`; those are for genuinely cross-team access and Django internals. In serializers the team comes from `self.context["get_team"]()`. Caveat: `for_team(...).get_or_create(...)` and `.create(...)` still need `team_id` passed explicitly, because a queryset filter does not propagate into row creation.
+- **Do not add domain-specific fields to the `Team` model.** `[review]` Use a Team Extension model — see [posthog/models/team/README.md](posthog/models/team/README.md) for the pattern and helpers.
+
+### Person and group data
+
+- **All person/group access goes through the personhog client.** `[review]` Never query these via the Django ORM or raw SQL: `posthog_person`, `posthog_persondistinctid`, `posthog_cohortpeople`, `posthog_group`, `posthog_grouptypemapping`, and the override tables (`posthog_personoverride`, `posthog_pendingpersonoverride`, `posthog_flatpersonoverride`, `posthog_featureflaghashkeyoverride`, `posthog_personlessdistinctid`, `posthog_personoverridemapping`). Use the routed helpers in `posthog/models/person/util.py` and `posthog/models/group_type_mapping.py`. New access follows the same `_personhog_routed()` pattern: a `personhog_fn` using `get_personhog_client()`, plus an `orm_fn` fallback. See [posthog/personhog_client/README.md](posthog/personhog_client/README.md).
+- **Personhog answers identity questions only.** `[review]` Use it for resolving distinct IDs, point lookups by person id or UUID, and lifecycle writes. Person properties, list hydration, and search come from ClickHouse (HogQL over `persons`, `ActorsQueryRunner`). Avoid reading `properties` from personhog — the API will stop surfacing it. Single-person lookups that need properties are exempt only while no ClickHouse primitive covers them, never in bulk. See [docs/internal/person-data-access.md](docs/internal/person-data-access.md).
+
+### Transactions and locking
+
+- **There is no implicit per-request transaction** — PostHog does not enable `ATOMIC_REQUESTS`. `[review]` Every operation runs in autocommit unless wrapped. Put `with transaction.atomic():` around the specific writes that must succeed or fail together, never around a whole view method. Keep irreversible side effects out of the block: an email sent or an API called before a rollback has already happened. Schedule them after the commit, or dispatch Celery tasks with `transaction.on_commit()`.
+- **Do not use `Team` or `Organization` rows as mutexes.** `[lint: hot-parent-row-select-for-update]` PostgreSQL takes `KEY SHARE` locks on parent rows for foreign-key checks, and `FOR UPDATE` conflicts with them, so an unrelated child-row write can wait behind a transaction holding a hot parent row. Lock the product's `Team<Product>Config` extension row instead, reached through `get_or_create_team_extension` so the row exists first. For a per-team count limit or number allocation, use a unique constraint, a conditional update, or a dedicated allocation row. Otherwise lock the quiet child row, or take a transaction-scoped advisory lock. Lock `Team` or `Organization` only when the transaction updates or deletes that row, and keep it short — no network calls, no input-sized loops. Each exception needs a short `nosemgrep` justification.
+
+### API schemas and generated types
+
+- **API views declare request/response schemas.** `[review]` Prefer `@validated_request` from `posthog.api.mixins`, or `@extend_schema` from drf-spectacular. A plain `ViewSet` method that validates manually needs `@extend_schema(request=YourSerializer)`; without it drf-spectacular cannot discover the request body and generated code gets an empty schema. Serializer fields need `help_text`. These flow into both frontend types and MCP tool schemas.
+- **Django serializers are the source of truth for frontend API types.** `[lint: build:openapi CI gate, prefer-codegen-api]` `hogli build:openapi` generates TypeScript via drf-spectacular and Orval into `frontend/src/generated/core/` and `products/{product}/frontend/generated/`. Never hand-edit `api.schemas.ts`, `api.ts` or `api.zod.ts` — change the serializer and regenerate. [Type system guide](docs/published/handbook/engineering/type-system.md) has the full pipeline.
+- MCP tools and MCP UI apps are generated from the same OpenAPI spec. `[review]` See [implementing MCP tools](docs/published/handbook/engineering/ai/implementing-mcp-tools.md) covers the YAML config and codegen. MCP UI apps live in `products/*/mcp/tools.yaml` under `ui_apps` — see [services/mcp/CONTRIBUTING.md](services/mcp/CONTRIBUTING.md) or `/implementing-mcp-ui-apps`.
+
+### Async, storage and outbound calls
+
+- **Do not use `posthoganalytics.capture()` in a Celery task** — events are silently lost. `[review]` Use `ph_scoped_capture` from `posthog.ph_client`; its docstring explains why.
+- **Temporal activity payloads cap at ~2 MiB — pass large data by reference.** `[review]` Activity inputs and outputs cross a gRPC boundary the server rejects above that (`blobSizeLimitError`). As a field-level rule: if a field could exceed ~256 KB serialized (query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres or object storage from inside the activity and return only the row ID or S3 key. The workflow already has any ID created earlier in the run. Shuttling large data through the workflow produces `PayloadSizeError` (`TMPRL1103`) as soon as the data crosses the limit.
+- **A Python `requests` call to GitHub or Slack under `common/`, `ee/`, `posthog/` or `products/` goes through `posthog/egress/`.** `[lint: github-api-calls-go-through-egress, slack-api-calls-go-through-egress]` Route it through the gated, recorded transport.
+- **Every other call to those hosts is on review.** `[review]` The rules match an inline URL in a Python `requests` call inside those four directories. A URL bound to a variable first, another transport such as `httpx`, another language, or a caller under `tools/` all pass CI.
+- **Any other third-party API that needs rate-limiting or egress telemetry belongs there too.** `[review]` Add a `<domain>/` incarnation (GitHub is the reference). No semgrep rule covers a new domain, so a raw client for one reaches master unless a reader catches it. See [posthog/egress/README.md](posthog/egress/README.md).
+- **Object storage is SeaweedFS — do not add new MinIO dependencies.** `[review]` Both S3-compatible stores are SeaweedFS: `objectstorage` (`:19000`, `OBJECT_STORAGE_*`) for general storage, `seaweedfs` (`:8333`, `SESSION_RECORDING_V2_S3_*`) for session replay v2. MinIO survives only as migration tooling in `docker-compose.hobby.yml` and `bin/upgrade-objectstorage`. Do not add compose services, scripts, tests or docs that stand up a `minio/minio` container. Talk to storage through the existing config and a standard S3 client, never a hardcoded endpoint. Note `objectstorage` registers credentials at runtime and returns `InvalidAccessKeyId` until that finishes, so wait for its readiness sentinel rather than the container start.
+
+### Django admin
+
+- **A new `ForeignKey`/`OneToOneField` on an admin-exposed model needs explicit widget config.** `[review]` List the field in `autocomplete_fields`, `raw_id_fields`, or `readonly_fields` on **every** admin class that renders the model, including inlines attached to a related admin. Otherwise the default `<select>` loads the entire target table per row on each change-page render. Declare it on a shared base inline so per-parent variants inherit it.
+
+### LLM gateway
+
+- **`services/llm-gateway` is under an unofficial code freeze** while callers move to [`PostHog/ai-gateway`](https://github.com/PostHog/ai-gateway). `[review]` New callers and features belong on the Go gateway. A Python gateway change needs a documented parity blocker for an active caller and stays limited to it — read [`services/llm-gateway/PARITY.md`](services/llm-gateway/PARITY.md). Its Postgres role reads only allowlisted tables: a new table read needs the SELECT grant landed in posthog-cloud-infra for every environment first, then a declaration in `required_tables.py`. The readiness probe checks every declared grant on every probe, so a missing grant holds a rollout instead of serving 500s. Use `/auditing-llm-gateway-parity` for contract changes, `/finding-llm-gateway-migration-candidates` to pick the next caller, `/migrating-llm-gateway-callers` to move one.
## Code Style
-- Python: Write as if mypy `--strict` is enabled — annotate all function signatures (arguments + return types), avoid `Any`, use `TYPE_CHECKING` imports for type-only references. When a change is type-risky, run mypy the way CI does — `uv run mypy --cache-fine-grained .`, repo-wide, never a file subset (it follows imports, so a subset misses reverse-dependency breakage); `hogli ci:preflight` reminds you, and CI blocks on the same command. The config isn't fully strict yet, but new code should be
-- Python imports: keep imports at module level — not inside functions, methods, or conditionals. Inline imports hide dependencies from static analysis, slow hot paths with repeated lookups, and mask circular-import problems instead of fixing them; ruff's `PLC0415` enforces this. Defer an import only to (1) break a true unavoidable circular import (fix the structure first if you can), (2) reference types under `TYPE_CHECKING`, or (3) keep a heavy/optional dependency off the import path so it loads only when its code runs. For (3), add a justified `# noqa: PLC0415` on the import line (e.g. `# noqa: PLC0415 — keeps the heavy dep off the import path`) — never blanket-suppress the rule
-- Python dataclasses: invoke `/writing-dataclasses` before adding or changing a dataclass, returning or passing several values, or passing a dataclass through layers. House decorator is `@frozen` from `posthog.dataclasses`; a bare `@dataclass` without an explicit `frozen=` fails the ratchet in `posthog/test/repo_invariants/test_dataclass_defaults.py`
-- Frontend: for any frontend work — the main app (`frontend/src/`) **or** a product frontend (`products/*/frontend/`) — follow [frontend/src/AGENTS.md](frontend/src/AGENTS.md): reuse existing Lemon/quill components instead of hand-rolling tables/badges/labels, import generated `*Api` types instead of handwriting them, and run typecheck/typegen at the right moments. Product frontends share the same components and generated types, so the same rules apply there
-- Frontend: TypeScript required, explicit return types
-- Frontend: If there is a kea logic file, write all business logic there, avoid React hooks at all costs.
-- Frontend (quill design system): before writing UI that imports `@posthog/quill` / `lib/ui/quill`, read [packages/quill/packages/primitives/AGENTS.md](packages/quill/packages/primitives/AGENTS.md) — component choice (dropdown vs select vs combobox, accordion vs collapsible, etc.), composition, and spacing rules. Charts: [working-with-charts](.agents/skills/working-with-charts/SKILL.md) for consumers; [package guide](packages/quill/packages/charts/AGENTS.md) for library changes. DataTable/DateTimePicker: [packages/quill/packages/components/AGENTS.md](packages/quill/packages/components/AGENTS.md)
-- Frontend (quill vs LemonUI): quill is for MCP apps and the desktop app. It is deliberately more compact than LemonUI, so its components look out of place in the main app, and there is no active migration of the main app onto it. In `frontend/src/` and `products/*/frontend/`, use LemonUI, including for menus — `LemonMenu` with a `LemonButton` trigger is the default there. `lib/ui/DropdownMenu` (Radix) is legacy; don't add new ones. Where quill is the right library, don't mix quill and Lemon components within one component's internals, and note that quill uses Base UI's `render` prop rather than Radix's `asChild`, so don't carry `asChild` over when converting
-- Frontend: Any button or form submit that triggers a network request must guard against double-submission — disable the button and show a loading state (`loading` / `disabledReason` on `LemonButton`, or equivalent) while the request is in flight. Never leave a submit button clickable during an active mutation; reset the state in both success and error paths. This applies to `<form onSubmit>` handlers, `onClick` handlers that call `api.*`, and any kea `listener` that issues a request — wire the in-flight state (loader `*Loading` selectors, local `useState`, or a reducer) into the trigger's disabled/loading props.
-- Frontend: Any UI a person reads must hold up in a narrow scene. The nav sidebar and an open side panel leave a 1280px window about 520px of scene, so break on container queries rather than `md:`/`lg:`/`xl:`, wrap or truncate instead of clipping, and stack halves that no longer fit. Render the surface at a few widths before calling the work done. We do not support mobile — don't add phone-width layouts or touch-sized targets. See "Rule 6" in [frontend/src/AGENTS.md](frontend/src/AGENTS.md)
-- Imports: Use oxfmt import sorting (automatically runs on format), avoid direct dayjs imports (use lib/dayjs)
-- CSS: Use tailwind utility classes instead of inline styles
-- Error handling: Prefer explicit error handling with typed errors
-- Naming: Use descriptive names, camelCase for JS/TS, snake_case for Python
-- Comments: default to short or 1-line comments. Explain _why_, not _what_, and only when a future reader (with no access to this PR or chat) would otherwise be confused
-- Comments: use mostly ASD-STE100 Simplified Technical English. Use active voice, simple tenses, one idea per sentence, and consistent terms
-- Comments: never log change history or chat context in code — no "previously did X, now does Y", "per <task/PR>", "changed because…", or "AI:"/"agent:" notes. That goes in the commit message and PR description
-- Comments: when refactoring or moving code, preserve existing comments unless they are explicitly made obsolete by the change
-- Python tests: do not add doc comments
-- Python: leave `__init__.py` alone unless a check asks for it. Whether a directory needs one depends on what sits above it. `hogli product:lint` and `posthog/test/repo_invariants/test_pytest_module_collisions.py` say where, and print the fix
-- jest tests: when writing jest tests, prefer a single top-level describe block in a file
-- Node.js Jest tests: use `.test.ts` by default. Use `.serial.test.ts` only when shared mutable infrastructure cannot be isolated, such as tests that reset a shared database.
-- Tests: when adding coverage, prefer extending a relevant existing test over creating a new standalone test when practical. Prefer parameterized cases (use the `parameterized` library in Python and `test.each` in Jest) when testing variations of the same behavior
-- Tests must earn their place: every new test has to catch a realistic regression no existing test already catches (if you can't name it, don't add it), assert observable behavior through the public interface rather than implementation details, and stay cheap — deterministic, isolated, and at the lowest level that catches the bug (see `/writing-tests`)
-- Reduce nesting: Use early returns, guard clauses, and helper methods to avoid deeply nested code
-- Markdown: prefer semantic line breaks; no hard wrapping
-- Use American English spelling
+Same tags as above: `[lint: <id>]` is machine-enforced, `[review]` is not.
+
+### Python
+
+- **Write as if mypy `--strict` were on.** `[review]` Annotate every signature, avoid `Any`, put type-only references under `TYPE_CHECKING`. The config is not fully strict yet; new code should be. When a change is type-risky run mypy the way CI does — `uv run mypy --cache-fine-grained .`, repo-wide, never a file subset. It follows imports, so a subset misses reverse-dependency breakage.
+- **Imports stay at module level.** `[review]` ruff's `PLC0415` catches this, but `posthog/**`, `ee/**`, `common/**`, `tools/**` and most of `products/` are on grandfathered exemption lists, so CI does not block it in the trees you are most likely to be editing. Defer one only to break a true unavoidable circular import, to reference types under `TYPE_CHECKING`, or to keep a heavy or optional dependency off the import path. For the last case add a justified `# noqa: PLC0415 — keeps the heavy dep off the import path` on the line. Never blanket-suppress the rule.
+- **A stdlib `@dataclass` must declare `frozen=` explicitly.** `[lint: prefer-frozen-dataclasses, test_dataclass_defaults.py]` A bare `@dataclass` fails the ratchet; `@dataclass(frozen=False)` passes it, so intentional mutability is a choice you state.
+- **The house decorator is `@frozen` from `posthog.dataclasses`.** `[review]` Neither check prefers it over a declared stdlib `@dataclass`. Invoke `/writing-dataclasses` before adding or changing one, before returning or passing several values together, and before passing a dataclass through layers.
+- **`product:lint` and the pytest collision test say where an `__init__.py` is required, and print the fix.** `[lint: product:lint, test_pytest_module_collisions.py]` Run them rather than reasoning about it.
+- **Do not add or delete an `__init__.py` speculatively.** `[review]` Whether a directory needs one depends on what sits above it. Neither check objects to a needless one outside `products/` that creates no module-name collision, so only a reader catches that.
+- Prefer classes over loose functions unless a class genuinely does not fit. `[review]` Use `pathlib` over `os.path`. Order functions and methods so a definition appears before its first call.
+
+### Frontend
+
+- **Follow [frontend/src/AGENTS.md](frontend/src/AGENTS.md) for all frontend work** — the main app and `products/*/frontend/` alike, since they share components and generated types. `[review]` It covers reusing Lemon/quill components instead of hand-rolling tables, badges and labels, importing generated `*Api` types instead of handwriting them, and when to run typecheck and typegen.
+- **TypeScript with explicit return types. Business logic goes in the kea logic file, not a React hook.** `[review]`
+- **Guard every network-triggering button against double submission.** `[review]` Disable it and show a loading state (`loading` / `disabledReason` on `LemonButton`, or equivalent) while the request is in flight, and reset in both the success and error paths. Applies to `<form onSubmit>`, any `onClick` that calls `api.*`, and any kea `listener` that issues a request. Wire in the in-flight state from a loader `*Loading` selector, a reducer, or local `useState`.
+- **Every surface must hold up narrow.** `[review]` The nav sidebar plus an open side panel leave a 1280px window about 520px of scene. Break on container queries, not `md:`/`lg:`/`xl:`. Wrap or truncate rather than clip, and stack halves that no longer fit. Render at a few widths before calling it done. We do not support mobile — no phone-width layouts, no touch-sized targets. See "Rule 6" in [frontend/src/AGENTS.md](frontend/src/AGENTS.md).
+- **quill is for MCP apps and the desktop app; LemonUI is for everything else.** `[review]` quill is deliberately more compact, so it looks out of place in the main app, and there is no migration of the main app onto it. In `frontend/src/` and `products/*/frontend/` use LemonUI, including menus — `LemonMenu` with a `LemonButton` trigger. `lib/ui/DropdownMenu` (Radix) is legacy; do not add new ones. Where quill is right, do not mix the two inside one component, and remember quill uses Base UI's `render` prop, not Radix's `asChild`. Read [primitives/AGENTS.md](packages/quill/packages/primitives/AGENTS.md) before importing quill — it covers component choice and spacing. Charts: [/working-with-charts](.agents/skills/working-with-charts/SKILL.md) for consumers, [charts/AGENTS.md](packages/quill/packages/charts/AGENTS.md) for library changes. DataTable and DateTimePicker: [components/AGENTS.md](packages/quill/packages/components/AGENTS.md).
+- Use tailwind utility classes over inline styles, and `lib/dayjs` over a direct dayjs import. `[review]` oxlint warns on a `style` prop through `react/forbid-dom-props`, but a warning does not block.
+
+### Comments
+
+- **Explain _why_, not _what_,** and only where a future reader with no access to this PR or chat would otherwise be confused. `[review]` Default to one line. Python tests get no doc comments.
+- **Never log change history or chat context in code.** `[review]` No "previously did X, now does Y", no "per <task/PR>", no "changed because…", no "AI:" or "agent:" notes. That belongs in the commit message and PR description.
+- **When refactoring or moving code, keep the existing comments** unless the change actually makes them obsolete. `[review]`
+- Use ASD-STE100 Simplified Technical English: active voice, simple tenses, one idea per sentence, consistent terms. `[review]`
+
+### Tests
+
+- **Every new test must catch a realistic regression no existing test catches.** `[review]` If you cannot name that regression, do not add the test. Assert observable behavior through the public interface, not implementation details, and keep it cheap — deterministic, isolated, at the lowest level that catches the bug. See `/writing-tests`.
+- **Extend a relevant existing test rather than adding a standalone one** where practical, and parameterize variations of the same behavior (`parameterized` in Python, `test.each` in Jest). `[review]`
+- Jest: one top-level `describe` per file. `[review]` Node.js Jest: `.test.ts` by default, `.serial.test.ts` only when shared mutable infrastructure cannot be isolated (a test that resets a shared database).
+
+### Markdown and prose
+
+- Semantic line breaks, no hard wrapping. American English spelling. `[review]`
## User-facing copy
@@ -261,7 +261,8 @@ A warn-only check belongs in the `pre-commit` hook body rather than in a lint-st
### Mandatory skill invocation
-ALWAYS invoke the matching skill **before** writing or reviewing code in these areas — do not skip, do not attempt the work without loading the skill first.
+Each entry below is a trigger, not a task list: it fires on what the diff contains, whether you are writing that code or reading someone else's.
+ALWAYS invoke the matching skill **first** — do not skip it, and do not attempt the work or the review without loading it.
**Always invoke:**
@@ -291,6 +292,7 @@ ALWAYS invoke the matching skill **before** writing or reviewing code in these a
- `/sending-notifications` — adding notification support
- `/adding-activity-logging` — adding activity logging (the audit trail) to a model, writing or changing a `model_activity_signal` receiver or an activity describer, auditing which write paths of a model are logged, or debugging a change that is missing from the activity log
- `/writing-skills` — creating or updating skills in `.agents/skills/`
+- `/editing-agents-md` — adding, editing or removing a rule in any `AGENTS.md` or `CLAUDE.md`, root or nested
- `/writing-evals` — adding or changing eval suites, cases, scorers, or seeders under `products/posthog_ai/evals/` or `products/*/evals/`, touching the harness in `products/posthog_ai/eval_harness/`, or running those evals
- [`ee/hogai/eval/AGENTS.md`](ee/hogai/eval/AGENTS.md) — writing eval cases or fixture data by hand anywhere (not a skill, and not covered by `/writing-evals`): where that data may come from, and why anonymizing a real conversation does not make it publishable
- `/authoring-ci-workflows` — adding or editing any `.github/workflows` workflow, composite action, or reusable workflow
diff --git a/docs/internal/cloud-task-sandbox.md b/docs/internal/cloud-task-sandbox.md
new file mode 100644
index 000000000000..bba115c001ea
--- /dev/null
+++ b/docs/internal/cloud-task-sandbox.md
@@ -0,0 +1,44 @@
+# Cloud task sandbox (dev-stack VM)
+
+Applies only inside a PostHog Tasks cloud run, on the prebaked `posthog-dev-stack` VM image.
+Local developers and CI are unaffected by everything on this page.
+`POSTHOG_TASK_RUN_ID` is set in that environment.
+
+## Booting the stack
+
+Run `bootstrap-dev-stack` first — it restores the compose host aliases and starts dockerd.
+Then `uv sync`, `source .venv/bin/activate`, `hogli start -y -d`, and `hogli wait`.
+
+Always detached. The sandbox has no TTY, and phrocs under a pseudo-TTY grows in memory until the OOM killer takes it.
+The detached start returns while the stack is still booting, so `hogli wait` is what blocks until every process is ready.
+
+On user-created runs the backend usually starts the stack itself, to serve the run's preview.
+While it does, `hogli start` exits 0 without starting anything, so a second stack cannot starve the VM.
+Poll `/tmp/posthog-preview/status.json` until `state` is `ready` or `failed`:
+
+- `ready` — run `hogli wait`. It reports `not reachable` until the backend reaches the phrocs step, so retry it rather than forcing a second start.
+- `failed` — the backend does not retry. Start the stack yourself with `hogli start -y -d`.
+
+## Frontend work
+
+`pnpm install --frozen-lockfile --prefer-offline` links from the prebaked pnpm store, and Playwright Chromium is preinstalled.
+Product and Storybook builds still run from source.
+
+## Tests
+
+Scope every run to what you changed, with `hogli test --changed` or the test files that cover the touched code.
+Run a whole module, package, or repo-wide suite at most once, right before you push, and only for a cross-cutting change.
+CI runs the full matrix anyway; repeating it here costs minutes per run and floods the agent's context with output.
+
+`hogli test` runs pytest with `-q` in a sandbox. Set `HOGLI_TEST_VERBOSE=1` to stream prints.
+
+The image seeds `test_posthog` and `pytest.ini` already enables `--reuse-db`.
+Do not pass `--create-db` or override pytest `addopts` — either one discards the prewarmed schema.
+
+If pytest starts the full migration history, the VM image predates the database seed, or the test database was replaced.
+Let that migration finish before retrying. Interrupting it leaves a partial database that the next run must continue migrating.
+
+## Other differences
+
+- `hogli devex:feedback` is a no-op here. Do not run it from a cloud task.
+- A `ci:preflight` advisory never needs the stack. Do not boot it only to clear one.
diff --git a/posthog/test/repo_invariants/test_agents_md_enforcement_tags.py b/posthog/test/repo_invariants/test_agents_md_enforcement_tags.py
new file mode 100644
index 000000000000..c0d7aa555822
--- /dev/null
+++ b/posthog/test/repo_invariants/test_agents_md_enforcement_tags.py
@@ -0,0 +1,125 @@
+import re
+import tomllib
+from pathlib import Path
+
+MARKER = re.compile(r"\[lint:([^\]]+)\]")
+SEMGREP_ID = re.compile(r"^\s*-?\s*id:\s*(\S+)", re.MULTILINE)
+RUFF_CODE = re.compile(r"^ruff ([A-Z]+[0-9]*)$")
+WELL_FORMED = re.compile(r"`\[lint:[^\]]+\]`|`\[review\]`")
+LEGEND_PLACEHOLDER = "<id>"
+
+# A file tag must name something CI executes. A data file the check reads is not
+# the check: delete the step that reads it and the file still sits there.
+EXECUTED_CHECK_ROOTS = ("posthog/test/repo_invariants", ".github/scripts")
+
+# The rule trees ci-security.yaml loads. A rule parked anywhere else in .semgrep
+# is not loaded by a blocking job, so it cannot back a tag.
+LOADED_SEMGREP_ROOTS = (".semgrep/rules/security", ".semgrep/rules/devex")
+
+# Sections whose every rule must declare what enforces it.
+TAGGED_SECTIONS = (("## Architecture guidelines", "## Code Style"), ("## Code Style", "## User-facing copy"))
+
+# Tags naming a command or CI job rather than a rule id. Add to this set only
+# when no single rule id covers the check.
+FREE_FORM = {
+ "hogli product:lint --all",
+ "product:lint",
+ "build:openapi CI gate",
+}
+
+
+def _repo_root() -> Path:
+ return Path(__file__).resolve().parents[3]
+
+
+def _agents_md(repo_root: Path) -> str:
+ return (repo_root / "AGENTS.md").read_text()
+
+
+def _tags(agents_md: str) -> list[str]:
+ tags = (tag.strip() for marker in MARKER.findall(agents_md) for tag in marker.split(","))
+ return [tag for tag in tags if tag != LEGEND_PLACEHOLDER]
+
+
+def _rules(agents_md: str) -> list[str]:
+ rules: list[str] = []
+ for start, end in TAGGED_SECTIONS:
+ section = agents_md[agents_md.index(start) : agents_md.index(end)]
+ rules.extend(line for line in section.split("\n") if line.startswith("- "))
+ return rules
+
+
+def _semgrep_ids(repo_root: Path) -> set[str]:
+ ids: set[str] = set()
+ for root in LOADED_SEMGREP_ROOTS:
+ for path in (repo_root / root).rglob("*.y*ml"):
+ ids.update(SEMGREP_ID.findall(path.read_text(errors="ignore")))
+ return ids
+
+
+def _ruff_enforces(repo_root: Path, code: str) -> bool:
+ lint = tomllib.loads((repo_root / "pyproject.toml").read_text())["tool"]["ruff"].get("lint", {})
+ # Ruff selectors are prefixes and the longest match wins, so a category-level
+ # ignore switches off every code under it unless a longer select overrides.
+ ignored = max((e for e in lint.get("ignore", []) if code.startswith(e)), key=len, default="")
+ selected = lint.get("select", []) + lint.get("extend-select", [])
+ chosen = max((e for e in selected if code.startswith(e)), key=len, default="")
+ if ignored and len(ignored) >= len(chosen):
+ return False
+ # A code exempted for whole trees does not hold repo-wide, so a bare tag would
+ # tell a reviewer CI covers paths where it accepts the violation.
+ for config, table in ((lint, "per-file-ignores"), (_products_ruff(repo_root), "per-file-ignores")):
+ if any(code in codes for codes in config.get(table, {}).values()):
+ return False
+ return bool(chosen)
+
+
+def _products_ruff(repo_root: Path) -> dict:
+ path = repo_root / "products" / "ruff.toml"
+ if not path.exists():
+ return {}
+ config = tomllib.loads(path.read_text())
+ return config.get("lint", config)
+
+
+def _resolves(tag: str, repo_root: Path, semgrep_ids: set[str]) -> bool:
+ if tag in FREE_FORM:
+ return True
+ ruff = RUFF_CODE.match(tag)
+ if ruff:
+ return _ruff_enforces(repo_root, ruff.group(1))
+ if tag.endswith(".py"):
+ return any(path.is_file() for root in EXECUTED_CHECK_ROOTS for path in (repo_root / root).rglob(tag))
+ return tag in semgrep_ids
+
+
+def test_agents_md_lint_tags_name_something_real() -> None:
+ # A stale tag is worse than no tag: a reviewer trusts it and skips the check.
+ repo_root = _repo_root()
+ semgrep_ids = _semgrep_ids(repo_root)
+
+ tags = _tags(_agents_md(repo_root))
+ assert tags, "AGENTS.md has no [lint: ...] tags — did the marker format change?"
+
+ unresolved = [tag for tag in tags if not _resolves(tag, repo_root, semgrep_ids)]
+
+ assert not unresolved, (
+ f"AGENTS.md tags these as machine-enforced, but nothing by that name enforces them: {unresolved}. "
+ "Either the rule was renamed or deleted, or a ruff code moved to `ignore` or a per-file exemption "
+ "list (fix the tag, or retag the "
+ f"rule as [review]), or the tag names a command rather than a rule id (add it to FREE_FORM in {Path(__file__).name})."
+ )
+
+
+def test_every_architecture_and_code_style_rule_is_tagged() -> None:
+ # An untagged rule reads as review-only without saying so, which is the ambiguity the tags remove.
+ rules = _rules(_agents_md(_repo_root()))
+ assert rules, "Found no rules to check — did the section headings change?"
+
+ untagged = [rule[:80] for rule in rules if not WELL_FORMED.search(rule)]
+
+ assert not untagged, (
+ f"These AGENTS.md rules carry no well-formed enforcement tag: {untagged}. "
+ "Add `[lint: <rule-id>]` when a linter or invariant test blocks the violation, or `[review]` when "
+ "nothing catches it. An empty or unclosed marker does not count."
+ )