:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): stop new side generators and gate projections together (#107222)
Julian Bez65bfe6b16305
diff --git a/.claude/rules/task-model-catalog.md b/.claude/rules/task-model-catalog.mdindex 3a8ff7ad2b22..0f3e76858f69 100644--- a/.claude/rules/task-model-catalog.md+++ b/.claude/rules/task-model-catalog.md@@ -1,7 +1,7 @@---paths:- 'products/tasks/backend/model_catalog.py'- - 'products/tasks/scripts/build_model_catalog.py'+ - 'products/tasks/scripts/model_catalog_projection.py'- 'products/tasks/frontend/modelCatalog.generated.ts'- 'products/desktop/packages/shared/src/model-catalog.generated.ts'---@@ -9,11 +9,11 @@ paths:`products/tasks/backend/model_catalog.py` is the single definition of a task run's triple: runtime adapter, model, and reasoning effort.The web composer and the desktop app each read a checked-in TypeScript projection of it, and the backend validates runs against the module itself.-After changing the catalog, run `hogli build:task-model-catalog` and commit both regenerated files.+After changing the catalog, run `hogli build:projections` and commit both regenerated files.The command needs no dev stack and takes well under a second, so run it rather than reasoning about whether the output moved.Never hand-edit `products/tasks/frontend/modelCatalog.generated.ts` or `products/desktop/packages/shared/src/model-catalog.generated.ts`.-A test re-renders both and compares them byte for byte, so an edit that the generator would not produce fails CI rather than shipping.+`hogli build:projections --check` re-renders both and compares them byte for byte in CI, so an edit that the renderer would not produce fails CI rather than shipping.Adding a model means one row in `MODELS`. Two things do not follow from that row and are worth checking:diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex 6ca79799db86..246c52f31ce1 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -403,7 +403,6 @@ jobs:- products/tasks/mcp/tools.yaml- 'products/canvas/packages/canvas_builder/**'- bin/build-schema-latest-versions.py- - bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- pyproject.toml@@ -496,7 +495,6 @@ jobs:- 'packages/personhog-proto/**'- 'posthog/**/*'- bin/build-schema-latest-versions.py- - bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- pyproject.toml@@ -588,6 +586,13 @@ jobs:- 'AGENTS.md'- '.semgrep/**'- 'pyproject.toml'+ # A generated file in a frontend-only PR still needs a known producer.+ - '**/*.generated.*'+ - '**/generated/**'+ # test_generated_files_are_registered.py also reads the projection+ # registry and the ci-python paths filter it must stay in step with.+ - 'tools/hogli-commands/hogli_commands/projections.py'+ - '.github/workflows/ci-python.yml'- 'products/ruff.toml'- '.github/scripts/**'product_yamls:@@ -605,14 +610,6 @@ jobs:- 'products/*/frontend/generated/**/*'- 'services/mcp/src/generated/**/*'- 'services/mcp/src/api/generated.ts'- # Task run model catalog: one Python module projected into a- # checked-in .generated.ts per workspace. Only the outputs are- # named — neither sits in a generated/ directory, and the- # desktop one is under products/desktop, which the backend- # filter excludes. The catalog and its generator are .py under- # products/, so the backend filter already catches both.- - 'products/tasks/frontend/modelCatalog.generated.ts'- - 'products/desktop/packages/shared/src/model-catalog.generated.ts'- 'tools/openapi-codegen/**/*'- 'services/mcp/scripts/lib/**'- 'frontend/bin/generate-openapi-types.mjs'diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 0b31aea30a72..dae5ea04c0b0 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -262,7 +262,6 @@ jobs:- products/tasks/mcp/tools.yaml- 'products/canvas/packages/canvas_builder/**'- bin/build-schema-latest-versions.py- - bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- pyproject.toml@@ -355,7 +354,6 @@ jobs:- 'packages/personhog-proto/**'- 'posthog/**/*'- bin/build-schema-latest-versions.py- - bin/build-taxonomy-json.py- bin/check_uv_python_compatibility.py- bin/find_python_dependencies.py- pyproject.toml@@ -446,6 +444,13 @@ jobs:- 'AGENTS.md'- '.semgrep/**'- 'pyproject.toml'+ # A generated file in a frontend-only PR still needs a known producer.+ - '**/*.generated.*'+ - '**/generated/**'+ # test_generated_files_are_registered.py also reads the projection+ # registry and the ci-python paths filter it must stay in step with.+ - 'tools/hogli-commands/hogli_commands/projections.py'+ - '.github/workflows/ci-python.yml'- 'products/ruff.toml'- '.github/scripts/**'product_yamls:@@ -467,14 +472,6 @@ jobs:- 'products/*/frontend/generated/**/*'- 'services/mcp/src/generated/**/*'- 'services/mcp/src/api/generated.ts'- # Task run model catalog: one Python module projected into a- # checked-in .generated.ts per workspace. Only the outputs are- # named — neither sits in a generated/ directory, and the- # desktop one is under products/desktop, which the backend- # filter excludes. The catalog and its generator are .py under- # products/, so the backend filter already catches both.- - 'products/tasks/frontend/modelCatalog.generated.ts'- - 'products/desktop/packages/shared/src/model-catalog.generated.ts'- 'tools/openapi-codegen/**/*'- 'services/mcp/scripts/lib/**'- 'frontend/bin/generate-openapi-types.mjs'diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 7b71cdcb5f90..0ff43c9196df 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -123,13 +123,18 @@ jobs:- 'frontend/src/queries/schema.json'# Products changes need to trigger Python CI to validate the json usage is still valid- 'frontend/src/products.json'- # A hand-edit to either generated taxonomy output must reach the drift check+ # A hand-edit to a projection output must reach the drift check. Lists+ # every output in hogli_commands/projections.py, not a *.generated.* glob,+ # so unrelated generated files skip mypy and ty.+ # test_generated_files_are_registered.py keeps the two in step.- 'frontend/src/taxonomy/core-filter-definitions-by-group.json'- 'services/mcp/src/lib/trace-property-allowlist.generated.ts'- # Same for the generated object-tag registries- - 'frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts'- 'products/desktop/packages/core/src/inbox/objectKinds.generated.ts'- 'products/desktop/packages/shared/src/objectTagKinds.generated.ts'+ - 'frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts'+ - 'products/tasks/frontend/modelCatalog.generated.ts'+ - 'products/desktop/packages/shared/src/model-catalog.generated.ts'+ - 'services/mcp/src/lib/oauth-scopes.generated.ts'# hogli CLI changes need validation- 'tools/hogli/**'- 'tools/hogli-commands/hogli_commands/**'@@ -319,19 +324,19 @@ jobs:run: |npm run schema:build:python && git diff --exit-code- # Calls the generator directly because this job installs neither pnpm nor- # node_modules. Keep the step after "Install Python dependencies": importing- # posthog.taxonomy.taxonomy pulls in Django via posthog/__init__.py, so the- # generator needs the full synced dependency set, not just stdlib.- - name: Check if the taxonomy JSON is up to date+ # Every projection renderer is Python, so this job needs neither pnpm nor+ # node_modules. Keep the step after "Install Python dependencies": the taxonomy+ # and object-tag renderers import posthog/__init__.py, which pulls in Django,+ # so they need the full synced dependency set, not just stdlib.+ # Skip on unrebased branches: the build:projections command may not exist yet.+ - name: Check if the generated projections are up to dateshell: bashrun: |- python3 bin/build-taxonomy-json.py --check-- - name: Check if the generated object-tag registries are up to date- shell: bash- run: |- python3 bin/build-object-tags-registry.py --check+ if [ ! -f tools/hogli-commands/hogli_commands/projections.py ]; then+ echo "hogli build:projections not present on this branch yet — skipping (rebase to pick it up)"+ exit 0+ fi+ ./bin/hogli build:projections --check# Warn-only while the pre-existing violation backlog settles: findings annotate# the diff and land in the shared CI report comment, never a job failure.diff --git a/AGENTS.md b/AGENTS.mdindex 1904bd57fbdb..0cb10ba65fa6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -185,7 +185,7 @@ Each rule is tagged with what catches a violation.### 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.+- **Django serializers are the source of truth for frontend API types.** `[lint: build:openapi CI gate, prefer-codegen-api, test_generated_files_are_registered.py]` `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. A value list the frontend needs comes from a typed serializer field, not from a side script; other checked-in projections are entries in `tools/hogli-commands/hogli_commands/projections.py`. [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 callsdiff --git a/bin/build-dashboard-widget-types.py b/bin/build-dashboard-widget-types.pyindex d90e74493acb..fbb51685d2ff 100755--- a/bin/build-dashboard-widget-types.py+++ b/bin/build-dashboard-widget-types.py@@ -1,8 +1,8 @@#!/usr/bin/env python3"""Preflight dashboard widget OpenAPI codegen from the backend registry.-Same pattern as ``bin/build-mcp-oauth-scopes.py``: a ``bin/*`` codegen script-invoked from ``hogli build:*``, reading backend SSOT and writing frontend JSON.+A ``bin/*`` codegen step inside ``hogli build:openapi``, reading backend SSOT and+writing frontend JSON next to the generated OpenAPI types.Checks every ``WIDGET_SPECS`` type has an ``ENUM_NAME_OVERRIDES`` entry (Orval /``build:openapi-schema`` fails otherwise) and emits frontend SSOT JSON for datediff --git a/bin/build-taxonomy-json.py b/bin/build-taxonomy-json.pydeleted file mode 100755index af7d977641ba..000000000000--- a/bin/build-taxonomy-json.py+++ /dev/null@@ -1,111 +0,0 @@-#!/usr/bin/env python-"""Make CORE_FILTER_DEFINITIONS_BY_GROUP accessible outside Python.--Emits the whole taxonomy for the frontend, and the `$ai_*` event property names-for the MCP server, which allowlists them in trace responses.--Run via hogli: `hogli build:taxonomy-json`. `--check` is what ci-python.yml and-`hogli ci:preflight` call to fail on drift without writing.-"""-# ruff: noqa: T201--import sys-import json-import argparse-from pathlib import Path--REPO_ROOT = Path(__file__).resolve().parent.parent-# Ahead of site-packages, so the repo's posthog wins over an installed one of the-# same name and the check cannot compare against a different taxonomy.-sys.path.insert(0, str(REPO_ROOT))--from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP # noqa: E402 — needs the sys.path line above--OUTPUT = REPO_ROOT / "frontend/src/taxonomy/core-filter-definitions-by-group.json"-MCP_ALLOWLIST_OUTPUT = REPO_ROOT / "services/mcp/src/lib/trace-property-allowlist.generated.ts"---def render() -> str:- """The exact contents the generated file must hold.-- The write path and --check both go through this, so the two cannot disagree- about the output.- """- with_comment = {- "//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: pnpm run taxonomy:build",- **CORE_FILTER_DEFINITIONS_BY_GROUP, # Unpack the dictionary to include its contents- }- return json.dumps(with_comment, indent=4, sort_keys=True)---def render_mcp_allowlist() -> str:- """The `$ai_*` event properties an MCP trace response may carry.-- `query-llm-trace` and `query-llm-traces-list` withhold every property the- taxonomy does not define, so an application cannot hand a credential back to- an agent through the event property bag. The rule cannot be a `$ai_` prefix- test, because capture does not reserve the namespace.- """- names = sorted(name for name in CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"] if name.startswith("$ai_"))- # oxfmt wants single quotes, so format by hand rather than with json.dumps and- # keep the output byte-stable. A taxonomy name never needs escaping; assert it- # so one that does fails the build instead of the TypeScript parse.- for name in names:- if "'" in name or "\\" in name:- raise RuntimeError(f"unexpected character in property name: {name!r}")- body = ",\n".join(f" '{name}'" for name in names)- return (- "// THIS FILE IS AUTOGENERATED from posthog/taxonomy/taxonomy.py. DO NOT EDIT\n"- "// MANUALLY. To update: pnpm run taxonomy:build\n"- "//\n"- "// Every other property of a trace event is withheld from MCP responses — see\n"- "// services/mcp/src/lib/trace-redaction.ts.\n"- "\n"- "export const AI_TAXONOMY_EVENT_PROPERTIES = [\n"- f"{body},\n"- "] as const\n"- )---def outputs() -> list[tuple[Path, str]]:- return [(OUTPUT, render()), (MCP_ALLOWLIST_OUTPUT, render_mcp_allowlist())]---def read_bytes(path: Path) -> bytes:- # Bytes, not text, so no newline translation can hide or invent a difference.- return path.read_bytes() if path.exists() else b""---def check() -> int:- stale = [path for path, contents in outputs() if read_bytes(path) != contents.encode()]- if not stale:- return 0- for path in stale:- # stdout, because ci:preflight reports `result.stdout or result.stderr`.- print(f"{path.relative_to(REPO_ROOT)} is out of date with posthog/taxonomy/taxonomy.py.")- print("Run `hogli build:taxonomy-json` and commit the result.")- return 1---def main() -> int:- parser = argparse.ArgumentParser(description="Generate the frontend-side taxonomy JSON.")- parser.add_argument(- "--check",- action="store_true",- help="Exit 1 if the file on disk differs from the taxonomy, without writing anything.",- )- args = parser.parse_args()- if args.check:- return check()- # Do not add a formatter pass here. Nothing reformats render()'s output before it- # reaches the file, so the output stays byte-stable and the taxonomy drift check in- # ci-python.yml cannot flap. The other half of that guarantee is the ignorePatterns- # entry in .oxfmtrc.json, which keeps lint-staged's `bin/hogli format:yaml` (oxfmt)- # off this file. Keep both.- for path, contents in outputs():- path.write_bytes(contents.encode())- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/docs/published/handbook/engineering/type-system.md b/docs/published/handbook/engineering/type-system.mdindex 3ecab3a6abc9..1181e9bfd173 100644--- a/docs/published/handbook/engineering/type-system.md+++ b/docs/published/handbook/engineering/type-system.md@@ -108,13 +108,36 @@ def my_action(self, request, **kwargs):This validates inputs AND documents the endpoint for OpenAPI. Use `request.validated_query_data`, not manual `request.query_params` parsing.+### Side generators++A side generator is a script that reads a Python module and writes TypeScript next to the OpenAPI flow, usually as a `*.generated.ts` file outside a `generated/` directory.+Each one needs its own hogli step, CI path filters, formatter exclusions and drift check.+New ones tend to copy the nearest existing one, so the count grows.++When the frontend or the MCP server needs the values that an API accepts or returns, use the OpenAPI flow instead:++1. Type the serializer field that carries the values, for example as a `ChoiceField`.+2. Run `hogli build:openapi`. Orval emits the values as a `*EnumApi` const next to the other generated types.+3. Read the list at runtime with `Object.values(SomethingEnumApi)` and use `SomethingEnumApi` as the type.++The field must be on an endpoint that is in the schema. A viewset action marked `@extend_schema(exclude=True)` does not reach the generated types.++Data rows that no endpoint serves, such as the task model catalog, go through the projection registry instead of a script of their own:++1. Write a renderer module next to the data. Its `render()` function returns the full text of each output, keyed by repo-relative path.+2. Add an entry to `PROJECTIONS` in `tools/hogli-commands/hogli_commands/projections.py` with the renderer, its inputs and its outputs.+3. Run `hogli build:projections` and commit the outputs. CI runs `hogli build:projections --check` and fails when one is out of date.++The `test_generated_files_are_registered.py` repo invariant fails a PR that adds a `*.generated.*` file, or a new `generated/` directory, that no registered projection and no known pipeline produces.+Ask #team-devex before you add a projection.+### Troubleshooting**Types not generating?** Ensure your ViewSet is in `products/your_product/backend/` and the `products/your_product/frontend/` directory exists. Auto-tagging happens based on module path.**Wrong type shapes?** The serializer is the source of truth. Use `@extend_schema_field` for custom `SerializerMethodField` types.-**CI failing?** Run `hogli build:openapi` locally and commit the regenerated files.+**CI failing?** Run `hogli build:openapi` locally and commit the regenerated files. For a drifted projection output, run `hogli build:projections`.### Design decisionsdiff --git a/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts b/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.tsindex 1520c1447c6a..c2843d936fb4 100644--- a/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts+++ b/frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts@@ -1,6 +1,6 @@-// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.+// THIS FILE IS AUTOGENERATED by posthog/object_tags/projection.py. DO NOT EDIT.// Source of truth: posthog/object_tags/kinds.py — after editing it,-// run `hogli build:object-tags` and commit the result.+// run `hogli build:projections` and commit the result.export interface ObjectKindData {/** Human name of the kind, e.g. "Insight". */diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex f517e0d6240f..44dd71c6b061 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -1,5 +1,5 @@{- "//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: pnpm run taxonomy:build",+ "//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: hogli build:projections","elements": {"href": {"description": "Filter on the `href` attribute of the element.",diff --git a/frontend/src/taxonomy/coreFilterDefinitions.test.ts b/frontend/src/taxonomy/coreFilterDefinitions.test.tsindex 3be32bdca203..bbc3d7ba84f1 100644--- a/frontend/src/taxonomy/coreFilterDefinitions.test.ts+++ b/frontend/src/taxonomy/coreFilterDefinitions.test.ts@@ -14,7 +14,7 @@ describe('core filter definitions JSON', () => {: `${GENERATED_JSON} is missing from ignorePatterns in .oxfmtrc.json. lint-staged pipes staged JSON ` +'through `bin/hogli format:yaml` (oxfmt), and that entry is the only thing keeping oxfmt off ' +'this file. Without it the committed bytes stop matching the json.dump output of ' +- 'bin/build-taxonomy-json.py, so the taxonomy drift check in ci-python.yml fails for whoever ' ++ 'posthog/taxonomy/projection.py, so the projections drift check in ci-python.yml fails for whoever ' +'next edits posthog/taxonomy/taxonomy.py. Restore the entry rather than reformatting the JSON.'expect(missingEntryHint).toBeUndefined()diff --git a/hogli.yaml b/hogli.yamlindex 152cdd615e6a..48ac2ed79ada 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -485,12 +485,11 @@ build:build:schema-latest-versions:bin_script: build-schema-latest-versions.pydescription: Extract latest schema versions and generate frontend JSON config- build:taxonomy-json:- bin_script: build-taxonomy-json.py- description: Generate core filter definitions taxonomy JSON for frontend- build:object-tags:- bin_script: build-object-tags-registry.py- description: Generate the agent object-tag kind registry for TypeScript consumers+ build:projections:+ click: hogli_commands.projections:cmd_build_projections+ description: 'Regenerate the checked-in projections of Python modules that the+ OpenAPI flow does not carry, as registered in hogli_commands/projections.py.+ --check verifies without writing, --only NAME picks one. Needs no dev stack'build:bot-definitions:cmd: python livestream/bot/generate_definitions.pydescription: Generate livestream bot definitions JSON from bot_definitions.py@@ -534,15 +533,6 @@ build:build:openapi-mcp-tools:cmd: pnpm --filter=@posthog/mcp run generate-toolsdescription: Generate MCP tool handlers from YAML definitions + Orval schemas- build:openapi-mcp-scopes:- bin_script: build-mcp-oauth-scopes.py- description: Generate OAUTH_SCOPES_SUPPORTED for the MCP protected-resource- metadata from posthog/scopes.py- build:task-model-catalog:- cmd: python products/tasks/scripts/build_model_catalog.py- description: Generate the web and desktop views of the task run model catalog- (runtime adapter, model, reasoning effort) from- products/tasks/backend/model_catalog.pybuild:openapi-cli-agent-scopes:cmd: pnpm --filter=@posthog/mcp run generate-cli-agent-scopesdescription: Generate the CLI `agent` login use-case scope list from the MCP@@ -557,7 +547,7 @@ build:- build:widget-types- cmd: |log_dir=$(mktemp -d)- generator_names=(frontend_types mcp_types mcp_tools task_catalog exec_docs)+ generator_names=(frontend_types mcp_types mcp_tools exec_docs)generator_pids=()generator_statuses=()setsid hogli build:openapi-types >"$log_dir/frontend_types.log" 2>&1 &@@ -566,8 +556,6 @@ build:generator_pids+=("$!")setsid sh -c 'hogli build:openapi-mcp && exec hogli build:openapi-mcp-tools' >"$log_dir/mcp_tools.log" 2>&1 &generator_pids+=("$!")- setsid hogli build:task-model-catalog >"$log_dir/task_catalog.log" 2>&1 &- generator_pids+=("$!")setsid hogli build:openapi-exec-docs >"$log_dir/exec_docs.log" 2>&1 &generator_pids+=("$!")pids="${generator_pids[*]}"@@ -599,7 +587,6 @@ build:rm -rf "$log_dir"trap - INT TERMexit "$generation_status"- - build:openapi-mcp-scopes- build:openapi-cli-agent-scopesdescription: 'Generate OpenAPI schema and TypeScript types from the backend.Needs the dev stack running (Postgres and ClickHouse): Django startsdiff --git a/package.json b/package.jsonindex 9f915390842d..6c3a72791b6f 100644--- a/package.json+++ b/package.json@@ -20,8 +20,6 @@"schema:build": "bin/hogli build:schema","openapi:build": "bin/hogli build:openapi","schema:build:python": "bash bin/build-schema-python.sh",- "taxonomy:build": "pnpm run taxonomy:build:json",- "taxonomy:build:json": "python bin/build-taxonomy-json.py","grammar:build": "pnpm grammar:build:cpp","grammar:build:cpp": "cd posthog/hogql/grammar && cat HogQLLexer.cpp.g4 > HogQLLexer.g4 && tail -n +2 HogQLLexer.common.g4 >> HogQLLexer.g4 && antlr -o ../../../common/hogql_parser -Dlanguage=Cpp HogQLLexer.g4 && rm HogQLLexer.g4 && antlr -o ../../../common/hogql_parser -visitor -no-listener -Dlanguage=Cpp HogQLParser.g4","build:products": "pnpm --filter=@posthog/frontend run build:products",diff --git a/posthog/object_tags/kinds.py b/posthog/object_tags/kinds.pyindex 3f84bdeb02d3..d2de02d5f0ab 100644--- a/posthog/object_tags/kinds.py+++ b/posthog/object_tags/kinds.py@@ -7,8 +7,8 @@ markdown links — but they all share one vocabulary: the kinds, aliases, labelsand web paths defined here.Every entry is declarative (path templates and regex strings, never code) so-``bin/build-object-tags-registry.py`` can emit the same registry for the-TypeScript consumers. After editing, run ``hogli build:object-tags`` and commit+``posthog/object_tags/projection.py`` can emit the same registry for the+TypeScript consumers. After editing, run ``hogli build:projections`` and committhe regenerated files:- ``products/desktop/packages/core/src/inbox/objectKinds.generated.ts``diff --git a/bin/build-object-tags-registry.py b/posthog/object_tags/projection.pysimilarity index 51%rename from bin/build-object-tags-registry.pyrename to posthog/object_tags/projection.pyindex a75af98122c5..8f21ef7d95d7 100755--- a/bin/build-object-tags-registry.py+++ b/posthog/object_tags/projection.py@@ -1,38 +1,22 @@-#!/usr/bin/env python"""Emit the agent object-tag kind registry for its TypeScript consumers.The source of truth is ``posthog/object_tags/kinds.py``; Python-consumers import it directly. This generator carries the same registry to the+consumers import it directly. This renderer carries the same registry to thedesktop packages and the web frontend, plus the kind list the rich-outputprompt teaches agents, so none of them can drift.-Run via hogli: `hogli build:object-tags`. `--check` is what ci-python.yml and-`hogli ci:preflight` call to fail on drift without writing.+Registered in ``tools/hogli-commands/hogli_commands/projections.py``; run+``hogli build:projections``."""-# ruff: noqa: T201-import sysimport json-import argparse-from collections.abc import Callable-from pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent-# Ahead of site-packages, so the repo's posthog wins over an installed one of the-# same name and the check cannot compare against a different registry.-sys.path.insert(0, str(REPO_ROOT))--from posthog.object_tags.kinds import ( # noqa: E402 — needs the sys.path line above- FALLBACK_OBJECT_KIND,- OBJECT_KIND_ALIASES,- OBJECT_KINDS,- ObjectKindSpec,-)+from posthog.object_tags.kinds import FALLBACK_OBJECT_KIND, OBJECT_KIND_ALIASES, OBJECT_KINDS, ObjectKindSpecHEADER = """\-// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.+// THIS FILE IS AUTOGENERATED by posthog/object_tags/projection.py. DO NOT EDIT.// Source of truth: posthog/object_tags/kinds.py — after editing it,-// run `hogli build:object-tags` and commit the result.+// run `hogli build:projections` and commit the result."""DATA_INTERFACE = """\@@ -107,49 +91,13 @@ def render_prompt_kinds_ts() -> str:)-OUTPUTS: dict[Path, Callable[[], str]] = {- REPO_ROOT / "products/desktop/packages/core/src/inbox/objectKinds.generated.ts": render_registry_ts,- REPO_ROOT / "products/desktop/packages/shared/src/objectTagKinds.generated.ts": render_prompt_kinds_ts,- REPO_ROOT / "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts": render_registry_ts,-}---def check() -> int:- stale = []- for path, render in OUTPUTS.items():- # Bytes, not text, so no newline translation can hide or invent a difference.- on_disk = path.read_bytes() if path.exists() else b""- if on_disk != render().encode():- stale.append(path)- if not stale:- return 0- # stdout, because ci:preflight reports `result.stdout or result.stderr`.- for path in stale:- print(f"{path.relative_to(REPO_ROOT)} is out of date with posthog/object_tags/kinds.py.")- print("Run `hogli build:object-tags` and commit the result.")- return 1---def main() -> int:- parser = argparse.ArgumentParser(description="Generate the object-tag kind registry for TS consumers.")- parser.add_argument(- "--check",- action="store_true",- help="Exit 1 if any generated file differs from the registry, without writing anything.",- )- args = parser.parse_args()- if args.check:- return check()- # Do not add a formatter pass here. Nothing reformats render()'s output before it- # reaches the files, so the output stays byte-stable and the drift check cannot- # flap. The other halves of that guarantee are the ignorePatterns entries in- # .oxfmtrc.json (frontend copy) and the generated-files override in- # products/desktop/biome.jsonc (desktop copies). Keep all of them.- for path, render in OUTPUTS.items():- path.parent.mkdir(parents=True, exist_ok=True)- path.write_bytes(render().encode())- return 0---if __name__ == "__main__":- raise SystemExit(main())+def render() -> dict[str, str]:+ # Nothing reformats these outputs before they reach the files. The other halves of+ # that guarantee are the ignorePatterns entry in .oxfmtrc.json (frontend copy) and+ # the generated-files override in products/desktop/biome.jsonc (desktop copies).+ registry = render_registry_ts()+ return {+ "products/desktop/packages/core/src/inbox/objectKinds.generated.ts": registry,+ "products/desktop/packages/shared/src/objectTagKinds.generated.ts": render_prompt_kinds_ts(),+ "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts": registry,+ }diff --git a/posthog/scopes.py b/posthog/scopes.pyindex 7ccd0bc6b712..fea3bcc87451 100644--- a/posthog/scopes.py+++ b/posthog/scopes.py@@ -12,8 +12,8 @@ from typing import Literal, get_args## The MCP `OAUTH_SCOPES_SUPPORTED` list at# `services/mcp/src/lib/oauth-scopes.generated.ts` is generated from-# `get_scope_descriptions()` below via `bin/build-mcp-oauth-scopes.py`. Run-# `hogli build:openapi` to regenerate after editing this file.+# `get_scope_descriptions()` below via `posthog/scopes_projection.py`. Run+# `hogli build:projections` to regenerate after editing this file.APIScopeObject = Literal["action","access_control",@@ -333,7 +333,7 @@ def downgrade_scopes_to_read_only(scope_str: str) -> str:# These match what django-oauth-toolkit's OIDC layer accepts at the /authorize# endpoint. Duplicating the list as plain tuple (rather than importing from# oauth_toolkit) keeps `posthog.scopes` importable without Django setup, which-# the MCP codegen relies on (see `bin/build-mcp-oauth-scopes.py`).+# the MCP projection relies on (see `posthog/scopes_projection.py`).OIDC_SCOPES: tuple[str, ...] = ("openid", "profile", "email")@@ -616,7 +616,7 @@ def get_oauth_scopes_supported() -> list[str]:Used by the authorization server's `/.well-known/oauth-authorization-server`endpoint and by the MCP server's `/.well-known/oauth-protected-resource`- (the latter generated at build time via `bin/build-mcp-oauth-scopes.py` so+ (the latter generated at build time via `posthog/scopes_projection.py` sothe protected resource cannot drift out of subset of the AS).Resource scopes are built from `UNPRIVILEGED_SCOPES`, so the list excludesdiff --git a/bin/build-mcp-oauth-scopes.py b/posthog/scopes_projection.pysimilarity index 76%rename from bin/build-mcp-oauth-scopes.pyrename to posthog/scopes_projection.pyindex 595c086b7302..83265c14bc9f 100755--- a/bin/build-mcp-oauth-scopes.py+++ b/posthog/scopes_projection.py@@ -1,5 +1,4 @@-#!/usr/bin/env python3-"""Generate the MCP server's view of the OAuth scope universe from posthog/scopes.py.+"""Project the MCP server's view of the OAuth scope universe from posthog/scopes.py.Emits two constants into `services/mcp/src/lib/oauth-scopes.generated.ts`:@@ -18,23 +17,20 @@ Emits two constants into `services/mcp/src/lib/oauth-scopes.generated.ts`:Generating both from `posthog/scopes.py` keeps that module the singleauthority for scope classification; the TS side is a projection of it.-Run via hogli: `hogli build:openapi-mcp-scopes` (also runs as part of-`build:openapi`). See `common/hogli/manifest.yaml`.+Registered in `tools/hogli-commands/hogli_commands/projections.py`; run+`hogli build:projections`."""-# ruff: noqa: T201from __future__ import annotations-import sysimport runpyfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent-SCOPES_PY = REPO_ROOT / "posthog" / "scopes.py"-OUTPUT_TS = REPO_ROOT / "services" / "mcp" / "src" / "lib" / "oauth-scopes.generated.ts"+SCOPES_PY = Path(__file__).resolve().parent / "scopes.py"+OUTPUT = "services/mcp/src/lib/oauth-scopes.generated.ts"-def main() -> int:+def render_oauth_scopes() -> str:# runpy.run_path loads the file by filesystem path, bypassing the normal# import machinery and therefore posthog/__init__.py (which pulls in# Celery and Django settings). Any import that scopes.py doesn't satisfy@@ -53,8 +49,8 @@ def main() -> int:body = ",\n".join(f" '{s}'" for s in all_scopes)hidden_body = ",\n".join(f" '{s}'" for s in hidden_scopes)output = (- "// AUTO-GENERATED by bin/build-mcp-oauth-scopes.py from posthog/scopes.py.\n"- "// Regenerate with `hogli build:openapi`. Do not edit.\n"+ "// AUTO-GENERATED by posthog/scopes_projection.py from posthog/scopes.py.\n"+ "// Regenerate with `hogli build:projections`. Do not edit.\n""//\n""// Published as `scopes_supported` in MCP protected-resource metadata\n""// (RFC 9728). The OAuth authorization server publishes the same list\n"@@ -76,16 +72,8 @@ def main() -> int:f"{hidden_body},\n""] as const\n")+ return output- OUTPUT_TS.parent.mkdir(parents=True, exist_ok=True)- existing = OUTPUT_TS.read_text() if OUTPUT_TS.exists() else None- if existing != output:- OUTPUT_TS.write_text(output)- print(f"wrote {OUTPUT_TS} ({len(all_scopes)} scopes)")- else:- print(f"{OUTPUT_TS} already up to date ({len(all_scopes)} scopes)")- return 0--if __name__ == "__main__":- sys.exit(main())+def render() -> dict[str, str]:+ return {OUTPUT: render_oauth_scopes()}diff --git a/posthog/taxonomy/projection.py b/posthog/taxonomy/projection.pynew file mode 100755index 000000000000..411e54a37401--- /dev/null+++ b/posthog/taxonomy/projection.py@@ -0,0 +1,58 @@+"""Make CORE_FILTER_DEFINITIONS_BY_GROUP accessible outside Python.++Emits the whole taxonomy for the frontend, and the `$ai_*` event property names+for the MCP server, which allowlists them in trace responses.++Registered in `tools/hogli-commands/hogli_commands/projections.py`; run+`hogli build:projections`.+"""++import json++from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP++OUTPUT = "frontend/src/taxonomy/core-filter-definitions-by-group.json"+MCP_ALLOWLIST_OUTPUT = "services/mcp/src/lib/trace-property-allowlist.generated.ts"+++def render_core_filter_definitions() -> str:+ with_comment = {+ "//": "THIS FILE IS AUTOGENERATED. DO NOT EDIT MANUALLY. To update: hogli build:projections",+ **CORE_FILTER_DEFINITIONS_BY_GROUP, # Unpack the dictionary to include its contents+ }+ return json.dumps(with_comment, indent=4, sort_keys=True)+++def render_mcp_allowlist() -> str:+ """The `$ai_*` event properties an MCP trace response may carry.++ `query-llm-trace` and `query-llm-traces-list` withhold every property the+ taxonomy does not define, so an application cannot hand a credential back to+ an agent through the event property bag. The rule cannot be a `$ai_` prefix+ test, because capture does not reserve the namespace.+ """+ names = sorted(name for name in CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"] if name.startswith("$ai_"))+ # oxfmt wants single quotes, so format by hand rather than with json.dumps and+ # keep the output byte-stable. A taxonomy name never needs escaping; assert it+ # so one that does fails the build instead of the TypeScript parse.+ for name in names:+ if "'" in name or "\\" in name:+ raise RuntimeError(f"unexpected character in property name: {name!r}")+ body = ",\n".join(f" '{name}'" for name in names)+ return (+ "// THIS FILE IS AUTOGENERATED from posthog/taxonomy/taxonomy.py. DO NOT EDIT\n"+ "// MANUALLY. To update: hogli build:projections\n"+ "//\n"+ "// Every other property of a trace event is withheld from MCP responses — see\n"+ "// services/mcp/src/lib/trace-redaction.ts.\n"+ "\n"+ "export const AI_TAXONOMY_EVENT_PROPERTIES = [\n"+ f"{body},\n"+ "] as const\n"+ )+++def render() -> dict[str, str]:+ # The JSON stays in the .oxfmtrc.json ignorePatterns: lint-staged pipes staged JSON+ # through oxfmt, and a reformat would stop the bytes matching this output.+ return {OUTPUT: render_core_filter_definitions(), MCP_ALLOWLIST_OUTPUT: render_mcp_allowlist()}diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex 3f167cb6f28b..70d3911fadf7 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -131,7 +131,7 @@ SESSION_PROPERTIES_ALSO_INCLUDED_IN_EVENTS = {*SESSION_INITIAL_PROPERTIES_ADAPTED_FROM_EVENTS,}-# IF UPDATING THIS, ALSO RUN `pnpm run taxonomy:build` to update core-filter-definitions-by-group.json+# IF UPDATING THIS, ALSO RUN `hogli build:projections` to update core-filter-definitions-by-group.jsonCORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"events": {# in front end this key is the empty stringdiff --git a/posthog/taxonomy/test/test_build_taxonomy_json.py b/posthog/taxonomy/test/test_build_taxonomy_json.pydeleted file mode 100644index 42e418d8f232..000000000000--- a/posthog/taxonomy/test/test_build_taxonomy_json.py+++ /dev/null@@ -1,57 +0,0 @@-from __future__ import annotations--import importlib.util-from pathlib import Path-from types import ModuleType--import pytest--GENERATOR = Path(__file__).resolve().parents[3] / "bin" / "build-taxonomy-json.py"---def _load_generator() -> ModuleType:- # Loaded by path because the dash in the filename rules out a plain import.- spec = importlib.util.spec_from_file_location("build_taxonomy_json", GENERATOR)- assert spec is not None and spec.loader is not None- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- return module---def _retarget(module: ModuleType, monkeypatch: pytest.MonkeyPatch, target: Path) -> None:- # REPO_ROOT moves with the outputs because the drift branch prints- # path.relative_to(REPO_ROOT), which raises for a path outside the repo.- monkeypatch.setattr(module, "REPO_ROOT", target.parent)- monkeypatch.setattr(module, "OUTPUT", target)- monkeypatch.setattr(module, "MCP_ALLOWLIST_OUTPUT", target.parent / "trace-property-allowlist.generated.ts")---class TestTaxonomyDriftDetection:- @pytest.mark.parametrize("on_disk", [None, b"{}"])- def test_check_reports_drift(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, on_disk: bytes | None) -> None:- module = _load_generator()- target = tmp_path / "core-filter-definitions-by-group.json"- if on_disk is not None:- target.write_bytes(on_disk)- _retarget(module, monkeypatch, target)-- assert module.check() == 1-- def test_check_accepts_the_rendered_bytes(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- module = _load_generator()- target = tmp_path / "core-filter-definitions-by-group.json"- _retarget(module, monkeypatch, target)- for path, contents in module.outputs():- path.write_bytes(contents.encode())-- assert module.check() == 0-- def test_check_reports_drift_in_the_mcp_allowlist_alone(- self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch- ) -> None:- module = _load_generator()- target = tmp_path / "core-filter-definitions-by-group.json"- _retarget(module, monkeypatch, target)- target.write_bytes(module.render().encode())-- assert module.check() == 1diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.pyindex b2a4e7eb034d..87e28b167686 100644--- a/posthog/temporal/oauth.py+++ b/posthog/temporal/oauth.py@@ -263,7 +263,7 @@ SCOUT_GRANTABLE_WRITE_SCOPES: frozenset[str] = frozenset(# Derived from posthog.scopes so the token issued to a sandboxed agent cannot# drift out of subset of what the MCP server advertises in# `services/mcp/src/lib/oauth-scopes.generated.ts` (itself generated from-# `get_oauth_scopes_supported()` via `bin/build-mcp-oauth-scopes.py`). Scopes+# `get_oauth_scopes_supported()` via `posthog/scopes_projection.py`). Scopes# already covered by INTERNAL_SCOPES are excluded so resolve_scopes() doesn't# emit duplicates.def _build_mcp_scopes(action: Literal["read", "write"]) -> list[str]:diff --git a/posthog/test/repo_invariants/test_generated_files_are_registered.py b/posthog/test/repo_invariants/test_generated_files_are_registered.pynew file mode 100644index 000000000000..a42a7f3be3d8--- /dev/null+++ b/posthog/test/repo_invariants/test_generated_files_are_registered.py@@ -0,0 +1,94 @@+import subprocess+from pathlib import Path++import yaml+from hogli_commands.change_detection import matches_globs+from hogli_commands.projections import PROJECTIONS++REPO_ROOT = Path(__file__).resolve().parents[3]++# Directories a code generation pipeline owns in full: drf-spectacular and Orval output,+# schema codegen, and the MCP tool and UI-app pipelines. `*` spans `/` in fnmatch.+PIPELINE_ROOTS = (+ "frontend/src/generated/*",+ "products/*/frontend/generated/*",+ "nodejs/src/common/generated/*",+ "posthog/usage_ingestion/generated/*",+ "services/mcp/src/generated/*",+ "services/mcp/src/tools/generated/*",+ "services/mcp/src/ui-apps/generated/*",+ "services/mcp/src/ui-apps/apps/generated/*",+)++# Generated files that a Node or Rust pipeline writes, with that producer. A Python+# projection never goes here: it is an entry in PROJECTIONS.+EXTERNAL_PRODUCERS = {+ "frontend/src/lib/agentScopes.generated.ts": "services/mcp/scripts/build-cli-agent-scopes.ts",+ "services/mcp/src/resources/ui-apps.generated.ts": "services/mcp/scripts/generate-ui-apps.ts",+ "rust/common/ingestion_warnings/warning_types.generated.json": (+ "nodejs/src/ingestion/common/scripts/generate-ingestion-warning-types.ts"+ ),+}++HOW_TO_FIX = (+ "A generated file needs a known producer, so no side generator grows next to the OpenAPI flow.\n"+ "- The frontend or the MCP server needs the values an API accepts or returns: type the serializer\n"+ " field and use the generated *EnumApi from `hogli build:openapi`.\n"+ "- The data is rows no endpoint serves: add a renderer and an entry to PROJECTIONS in\n"+ " tools/hogli-commands/hogli_commands/projections.py, then run `hogli build:projections`.\n"+ "See docs/published/handbook/engineering/type-system.md, 'Side generators'."+)+++def _tracked_files() -> list[str]:+ result = subprocess.run(["git", "ls-files", "-z"], cwd=REPO_ROOT, capture_output=True, check=True)+ return [path for path in result.stdout.decode().split("\0") if path]+++def _looks_generated(path: str) -> bool:+ return ".generated." in Path(path).name or "/generated/" in f"/{path}"+++def test_every_generated_file_has_a_known_producer() -> None:+ registered = {output for projection in PROJECTIONS for output in projection.outputs}+ unknown = [+ path+ for path in _tracked_files()+ if _looks_generated(path)+ and path not in registered+ and path not in EXTERNAL_PRODUCERS+ and not matches_globs(path, PIPELINE_ROOTS)+ ]++ assert unknown == [], f"Generated files with no known producer: {unknown}\n{HOW_TO_FIX}"+++def test_the_registry_matches_the_tree() -> None:+ outputs = [output for projection in PROJECTIONS for output in projection.outputs]+ known = set(outputs) | set(EXTERNAL_PRODUCERS)++ assert [p.renderer for p in PROJECTIONS if not (REPO_ROOT / p.renderer).is_file()] == []+ assert [path for path in known if not (REPO_ROOT / path).is_file()] == []+ assert sorted(output for output in set(outputs) if outputs.count(output) > 1) == []+ assert sorted(set(outputs) & set(EXTERNAL_PRODUCERS)) == []+++def _ci_python_filter(name: str) -> list[str]:+ workflow = yaml.safe_load((REPO_ROOT / ".github/workflows/ci-python.yml").read_text())+ [step] = [step for step in workflow["jobs"]["changes"]["steps"] if step.get("id") == "filter"]+ return yaml.safe_load(step["with"]["filters"])[name]+++def test_every_output_reaches_the_drift_check() -> None:+ python_filter = _ci_python_filter("python")+ missing = [+ output+ for projection in PROJECTIONS+ for output in projection.outputs+ if not matches_globs(output, python_filter)+ ]++ assert missing == [], (+ f"Projection outputs missing from the `python` paths filter in ci-python.yml: {missing}. "+ "Add them, so a hand-edit still runs `hogli build:projections --check`."+ )diff --git a/posthog/test/test_scopes.py b/posthog/test/test_scopes.pyindex cd7a7149c117..8255de5921ac 100644--- a/posthog/test/test_scopes.py+++ b/posthog/test/test_scopes.py@@ -119,7 +119,7 @@ class TestScopeSets(SimpleTestCase):self.assertIn(scope, UNPRIVILEGED_SCOPES)def test_scopes_module_loadable_via_runpy_like_mcp_codegen(self) -> None:- # MCP scope codegen at bin/build-mcp-oauth-scopes.py loads this module via+ # The MCP scope projection at posthog/scopes_projection.py loads this module via# runpy.run_path (bypassing posthog/__init__.py which pulls in Django).# Mirror that mechanism here so the test actually catches a regression# where someone adds a Django-requiring import to posthog/scopes.py.diff --git a/products/desktop/biome.jsonc b/products/desktop/biome.jsoncindex 9767959c5953..0be06e4bf375 100644--- a/products/desktop/biome.jsonc+++ b/products/desktop/biome.jsonc@@ -124,7 +124,7 @@},{// Object-tag kind registry generated from posthog/object_tags/kinds.py; the- // generator's byte-stable output is what `hogli build:object-tags --check`+ // renderer's byte-stable output is what `hogli build:projections --check`// compares against, so no formatter may touch it."includes": ["packages/core/src/inbox/objectKinds.generated.ts",diff --git a/products/desktop/packages/core/src/inbox/objectKinds.generated.ts b/products/desktop/packages/core/src/inbox/objectKinds.generated.tsindex 1520c1447c6a..c2843d936fb4 100644--- a/products/desktop/packages/core/src/inbox/objectKinds.generated.ts+++ b/products/desktop/packages/core/src/inbox/objectKinds.generated.ts@@ -1,6 +1,6 @@-// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.+// THIS FILE IS AUTOGENERATED by posthog/object_tags/projection.py. DO NOT EDIT.// Source of truth: posthog/object_tags/kinds.py — after editing it,-// run `hogli build:object-tags` and commit the result.+// run `hogli build:projections` and commit the result.export interface ObjectKindData {/** Human name of the kind, e.g. "Insight". */diff --git a/products/desktop/packages/shared/src/model-catalog.generated.ts b/products/desktop/packages/shared/src/model-catalog.generated.tsindex 577b03a52c43..a2fea8251938 100644--- a/products/desktop/packages/shared/src/model-catalog.generated.ts+++ b/products/desktop/packages/shared/src/model-catalog.generated.ts@@ -1,6 +1,6 @@-// AUTO-GENERATED by products/tasks/scripts/build_model_catalog.py from+// AUTO-GENERATED by products/tasks/scripts/model_catalog_projection.py from// products/tasks/backend/model_catalog.py.-// Regenerate with `hogli build:task-model-catalog`. Do not edit.+// Regenerate with `hogli build:projections`. Do not edit.//// The single definition of how a task agent run is configured: harness,// runtime adapter, model, and reasoning effort, plus what each modeldiff --git a/products/desktop/packages/shared/src/objectTagKinds.generated.ts b/products/desktop/packages/shared/src/objectTagKinds.generated.tsindex 2ceeeabbb462..6ee8254492f0 100644--- a/products/desktop/packages/shared/src/objectTagKinds.generated.ts+++ b/products/desktop/packages/shared/src/objectTagKinds.generated.ts@@ -1,6 +1,6 @@-// THIS FILE IS AUTOGENERATED by bin/build-object-tags-registry.py. DO NOT EDIT.+// THIS FILE IS AUTOGENERATED by posthog/object_tags/projection.py. DO NOT EDIT.// Source of truth: posthog/object_tags/kinds.py — after editing it,-// run `hogli build:object-tags` and commit the result.+// run `hogli build:projections` and commit the result./** The kind list the rich-output prompt teaches agents. */export const OBJECT_TAG_PROMPT_KIND_LIST = "insight, dashboard, error, replay, flag, experiment, survey, ticket, report, trace, eval, event, cohort, action, person";diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 6bcf6fb42b97..7c875c6f7c92 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -523,7 +523,7 @@ an agent-side fix reaches reviews only once it is published and the image rebuil**Recipe — testing e.g. Sonnet.** Set `runtime_adapter = "claude"`, `model` to a catalog id, and an effort that modelsupports; provider auto-derives to `anthropic`. The same applies to a Codex model with `runtime_adapter = "codex"`.-Every id and its efforts live in `model_catalog.py`; run `hogli build:task-model-catalog` after editing it, which+Every id and its efforts live in `model_catalog.py`; run `hogli build:projections` after editing it, whichupdates the TypeScript projections the desktop app and the web composer read.---diff --git a/products/tasks/backend/model_catalog.py b/products/tasks/backend/model_catalog.pyindex f7a94ea005e0..c6e756d2e7a1 100644--- a/products/tasks/backend/model_catalog.py+++ b/products/tasks/backend/model_catalog.py@@ -9,9 +9,9 @@ surface that offers or validates a selection derives from here:- the web composer and settings, through ``products/tasks/frontend/modelCatalog.generated.ts``;- the desktop app and its agent, through ``@posthog/shared/model-catalog``.-Both TypeScript projections are emitted by ``products/tasks/scripts/build_model_catalog.py`` and are-checked for drift by the same CI job that guards the generated OpenAPI types, so a model-ships by editing this file and nothing else.+Both TypeScript projections are emitted by ``products/tasks/scripts/model_catalog_projection.py`` and are+checked for drift by `hogli build:projections --check` in CI. After editing this file, run+`hogli build:projections` and commit the result.Keep this module free of Django and of anything outside the standard library. Thegenerator loads it by filesystem path with ``runpy``, which bypasses ``posthog``'s packagediff --git a/products/tasks/backend/tests/test_model_catalog.py b/products/tasks/backend/tests/test_model_catalog.pyindex fa64cded8940..195bb840e7f9 100644--- a/products/tasks/backend/tests/test_model_catalog.py+++ b/products/tasks/backend/tests/test_model_catalog.py@@ -1,6 +1,3 @@-import sys-import importlib.util-from pathlib import Pathfrom typing import Anyimport pytest@@ -14,21 +11,6 @@ from products.tasks.backend.facade.model_catalogue import GatewayModel, availablfrom products.tasks.backend.models import Taskfrom products.tasks.backend.temporal.process_task.utils import ReasoningEffort, RuntimeAdapter-REPO_ROOT = Path(__file__).resolve().parents[4]-GENERATOR = REPO_ROOT / "products" / "tasks" / "scripts" / "build_model_catalog.py"---def _load_generator():- name = "build_task_model_catalog"- spec = importlib.util.spec_from_file_location(name, GENERATOR)- assert spec is not None and spec.loader is not None- module = importlib.util.module_from_spec(spec)- # Registered before execution because @dataclass resolves annotations through- # sys.modules[cls.__module__], which is unset for a module loaded by path alone.- sys.modules[name] = module- spec.loader.exec_module(module)- return module-def _resolved_catalog() -> dict[str, Any]:"""The catalog as data, read back through the public resolver rather than the tables.@@ -82,19 +64,6 @@ def test_every_model_resolves_to_the_recorded_triple(snapshot) -> None:assert _resolved_catalog() == snapshot(extension_class=JSONSnapshotExtension)[email protected]("output,style", [("WEB_OUTPUT", "OXFMT"), ("DESKTOP_OUTPUT", "BIOME")], ids=["web", "desktop"])-def test_checked_in_projection_is_what_the_generator_emits(output: str, style: str) -> None:- generator = _load_generator()- expected = generator.render(vars(model_catalog), getattr(generator, style))-- path: Path = getattr(generator, output)- assert path.exists(), f"{path} is missing — run `hogli build:task-model-catalog`"- assert path.read_text() == expected, (- f"{path.relative_to(REPO_ROOT)} is stale. The catalog changed without regenerating, so this "- f"surface would offer a selection the backend rejects. Run `hogli build:task-model-catalog`."- )--def test_every_runtime_adapter_has_catalog_models() -> None:for adapter in RuntimeAdapter:assert model_catalog.models_for_runtime_adapter(adapter.value), (diff --git a/products/tasks/frontend/modelCatalog.generated.ts b/products/tasks/frontend/modelCatalog.generated.tsindex 098fd96fcef5..c6277afb3a48 100644--- a/products/tasks/frontend/modelCatalog.generated.ts+++ b/products/tasks/frontend/modelCatalog.generated.ts@@ -1,6 +1,6 @@-// AUTO-GENERATED by products/tasks/scripts/build_model_catalog.py from+// AUTO-GENERATED by products/tasks/scripts/model_catalog_projection.py from// products/tasks/backend/model_catalog.py.-// Regenerate with `hogli build:task-model-catalog`. Do not edit.+// Regenerate with `hogli build:projections`. Do not edit.//// The single definition of how a task agent run is configured: harness,// runtime adapter, model, and reasoning effort, plus what each modeldiff --git a/products/tasks/scripts/build_model_catalog.py b/products/tasks/scripts/model_catalog_projection.pysimilarity index 88%rename from products/tasks/scripts/build_model_catalog.pyrename to products/tasks/scripts/model_catalog_projection.pyindex 1e015cfe050a..df7cd42ead2a 100755--- a/products/tasks/scripts/build_model_catalog.py+++ b/products/tasks/scripts/model_catalog_projection.py@@ -1,11 +1,9 @@-#!/usr/bin/env python3"""Project the task run model catalog into TypeScript for the web app and the desktop app.-Same pattern as ``bin/build-mcp-oauth-scopes.py``: a codegen script that reads a pure-data-Python module and writes a checked-in ``*.generated.ts``, so the Python module stays the-single authority and the TypeScript sides are projections of it. It lives beside the-catalog it projects rather than in ``bin/``, since only this product reads or writes it —-the same placement as ``products/posthog_ai/scripts/build_skills/``.+A renderer in the projection registry: it reads a pure-data Python module and returns the+checked-in ``*.generated.ts`` files, so the Python module stays the single authority and+the TypeScript sides are projections of it. It lives beside the catalog it projects,+since only this product reads it.Two files come out of one template because the two workspaces run different formatters —the web app runs oxfmt (four spaces, single quotes, no semicolons, 120 columns) and the@@ -26,27 +24,24 @@ Only data is generated. The lookup built on it lives inmodule itself — behavior stays hand-written and tested, while the table that actuallychanges has one home.-Run via hogli: `hogli build:task-model-catalog` (also runs as part of `build:openapi`).-See `hogli.yaml`.+Registered in `tools/hogli-commands/hogli_commands/projections.py`; run+`hogli build:projections`."""-# ruff: noqa: T201from __future__ import annotations-import sysimport runpyfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-REPO_ROOT = Path(__file__).resolve().parents[3]-CATALOG_PY = REPO_ROOT / "products" / "tasks" / "backend" / "model_catalog.py"-WEB_OUTPUT = REPO_ROOT / "products" / "tasks" / "frontend" / "modelCatalog.generated.ts"-DESKTOP_OUTPUT = REPO_ROOT / "products" / "desktop" / "packages" / "shared" / "src" / "model-catalog.generated.ts"+CATALOG_PY = Path(__file__).resolve().parents[1] / "backend" / "model_catalog.py"+WEB_OUTPUT = "products/tasks/frontend/modelCatalog.generated.ts"+DESKTOP_OUTPUT = "products/desktop/packages/shared/src/model-catalog.generated.ts"-HEADER = """// AUTO-GENERATED by products/tasks/scripts/build_model_catalog.py from+HEADER = """// AUTO-GENERATED by products/tasks/scripts/model_catalog_projection.py from// products/tasks/backend/model_catalog.py.-// Regenerate with `hogli build:task-model-catalog`. Do not edit.+// Regenerate with `hogli build:projections`. Do not edit.//// The single definition of how a task agent run is configured: harness,// runtime adapter, model, and reasoning effort, plus what each model@@ -98,7 +93,7 @@ OXFMT = Style(indent=" " * 4, quote="'", semi="", width=120)BIOME = Style(indent=" " * 2, quote='"', semi=";", width=80)-def render(catalog: dict[str, Any], style: Style) -> str:+def render_catalog(catalog: dict[str, Any], style: Style) -> str:i, semi = style.indent, style.semiadapters: tuple[str, ...] = catalog["RUNTIME_ADAPTERS"]providers: dict[str, str] = catalog["PROVIDER_BY_RUNTIME_ADAPTER"]@@ -333,7 +328,7 @@ export const FALLBACK_REASONING_EFFORTS: FallbackEfforts = {{"""-def check_fits(rendered: str, style: Style, output: Path) -> None:+def check_fits(rendered: str, style: Style, output: str) -> None:"""Fail on a line the target formatter would rewrap.Every line here is already in the shape its formatter produces, which is what keeps a@@ -344,29 +339,19 @@ def check_fits(rendered: str, style: Style, output: Path) -> None:too_long = [line for line in rendered.splitlines() if len(line) > style.width]if too_long:raise RuntimeError(- f"{output.name}: {len(too_long)} line(s) exceed {style.width} columns and would be "+ f"{output}: {len(too_long)} line(s) exceed {style.width} columns and would be "f"rewrapped by the formatter, e.g.\n {too_long[0]}")-def main() -> int:+def render() -> dict[str, str]:# runpy.run_path loads the module by filesystem path, bypassing the import machinery and# therefore products/__init__.py and the Django settings behind it. Anything# model_catalog.py cannot satisfy from the standard library raises here, failing loudly.catalog = runpy.run_path(str(CATALOG_PY))- model_count = len(catalog["MODELS"])-+ rendered = {}for output, style in ((WEB_OUTPUT, OXFMT), (DESKTOP_OUTPUT, BIOME)):- rendered = render(catalog, style)- check_fits(rendered, style, output)- output.parent.mkdir(parents=True, exist_ok=True)- if output.exists() and output.read_text() == rendered:- print(f"{output.relative_to(REPO_ROOT)} already up to date ({model_count} models)")- continue- output.write_text(rendered)- print(f"wrote {output.relative_to(REPO_ROOT)} ({model_count} models)")- return 0---if __name__ == "__main__":- sys.exit(main())+ text = render_catalog(catalog, style)+ check_fits(text, style, output)+ rendered[output] = text+ return rendereddiff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.tsindex c86789aa42bc..85eb08f24f15 100644--- a/services/mcp/src/lib/oauth-scopes.generated.ts+++ b/services/mcp/src/lib/oauth-scopes.generated.ts@@ -1,5 +1,5 @@-// AUTO-GENERATED by bin/build-mcp-oauth-scopes.py from posthog/scopes.py.-// Regenerate with `hogli build:openapi`. Do not edit.+// AUTO-GENERATED by posthog/scopes_projection.py from posthog/scopes.py.+// Regenerate with `hogli build:projections`. Do not edit.//// Published as `scopes_supported` in MCP protected-resource metadata// (RFC 9728). The OAuth authorization server publishes the same listdiff --git a/services/mcp/src/lib/trace-property-allowlist.generated.ts b/services/mcp/src/lib/trace-property-allowlist.generated.tsindex ef9503aabab8..781a60c4db1f 100644--- a/services/mcp/src/lib/trace-property-allowlist.generated.ts+++ b/services/mcp/src/lib/trace-property-allowlist.generated.ts@@ -1,5 +1,5 @@// THIS FILE IS AUTOGENERATED from posthog/taxonomy/taxonomy.py. DO NOT EDIT-// MANUALLY. To update: pnpm run taxonomy:build+// MANUALLY. To update: hogli build:projections//// Every other property of a trace event is withheld from MCP responses — see// services/mcp/src/lib/trace-redaction.ts.diff --git a/tools/hogli-commands/hogli_commands/build.py b/tools/hogli-commands/hogli_commands/build.pyindex 4767e2849705..ddb143053d7c 100644--- a/tools/hogli-commands/hogli_commands/build.py+++ b/tools/hogli-commands/hogli_commands/build.py@@ -9,6 +9,7 @@ import clickfrom hogli.manifest import REPO_ROOTfrom hogli_commands.change_detection import changed_files, matches_globs+from hogli_commands.projections import all_triggers# command -> file globs that should trigger itTRIGGERS: dict[str, tuple[str, ...]] = {@@ -37,8 +38,7 @@ TRIGGERS: dict[str, tuple[str, ...]] = {".oxlintrc.json",),"build:grammar": ("posthog/hogql/grammar/*",),- "build:taxonomy-json": ("posthog/taxonomy/*",),- "build:object-tags": ("posthog/object_tags/*",),+ "build:projections": all_triggers(),"build:products": ("products/*/frontend/*",),"build:skills": ("products/*/skills/*",),"build:schema-mcp": ("services/mcp/src/*",),diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 5a59fc6e2051..de197b6e9990 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -50,6 +50,7 @@ from hogli_commands.complexity_lint import PYTHON_SCOPE, TEST_WARN_AT, TYPESCRIPfrom hogli_commands.depot_mirrors import mirror_violationsfrom hogli_commands.devenv.generator import TRACKED_MPROCS_FILESfrom hogli_commands.lockfile_merge import LOCKFILE_GLOBS, missing_resolutions+from hogli_commands.projections import all_outputs as projection_outputsfrom hogli_commands.size_lint import SCOPE as SIZE_SCOPERequirement = Literal["node", "desktop-node", "stack", "clickhouse", "python-env"]@@ -276,36 +277,17 @@ DIFF_CHECKS: list[DiffCheck] = [requires=("stack",),),DiffCheck(- key="taxonomy",- label="taxonomy JSON out of sync with posthog/taxonomy/taxonomy.py",- # From build.py so preflight and build:taxonomy-json can't drift on which diffs- # need a regen, plus the generator and its output, so an edit to any side of the- # relation is caught.+ key="projections",+ label="generated projections out of sync with their Python sources",+ # From the projection registry, so preflight, build:projections and the registry+ # cannot drift on which diffs need a regen. The outputs count too, so a hand-edit+ # to one is caught.triggers=[- *BUILD_TRIGGERS["build:taxonomy-json"],- "bin/build-taxonomy-json.py",- "frontend/src/taxonomy/core-filter-definitions-by-group.json",- "services/mcp/src/lib/trace-property-allowlist.generated.ts",+ *BUILD_TRIGGERS["build:projections"],+ *projection_outputs(),],- verify=["hogli", "build:taxonomy-json", "--check"],- fix=["hogli", "build:taxonomy-json"],- requires=("python-env",),- ),- DiffCheck(- key="object-tags",- label="generated object-tag registries out of sync with posthog/object_tags/kinds.py",- # From build.py so preflight and build:object-tags can't drift on which diffs- # need a regen, plus the generator and its outputs, so an edit to any side of- # the relation is caught.- triggers=[- *BUILD_TRIGGERS["build:object-tags"],- "bin/build-object-tags-registry.py",- "products/desktop/packages/core/src/inbox/objectKinds.generated.ts",- "products/desktop/packages/shared/src/objectTagKinds.generated.ts",- "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts",- ],- verify=["hogli", "build:object-tags", "--check"],- fix=["hogli", "build:object-tags"],+ verify=["hogli", "build:projections", "--check"],+ fix=["hogli", "build:projections"],requires=("python-env",),),DiffCheck(diff --git a/tools/hogli-commands/hogli_commands/projections.py b/tools/hogli-commands/hogli_commands/projections.pynew file mode 100644index 000000000000..fcc4577fda43--- /dev/null+++ b/tools/hogli-commands/hogli_commands/projections.py@@ -0,0 +1,163 @@+"""Checked-in projections of Python modules into files other languages read.++A projection carries data that no API endpoint serves, such as the task model catalog,+from the Python module that owns it to TypeScript or JSON the web app, the desktop app or+the MCP server imports. When the frontend needs the values an API accepts or returns, a+typed serializer field and the generated ``*EnumApi`` do that job instead.++Every projection is an entry in ``PROJECTIONS``. Do not add a script for a new one:+write a renderer module next to the data, register it here, and run+``hogli build:projections``. ``posthog/test/repo_invariants/test_generated_files_are_registered.py``+fails on a ``*.generated.*`` file that no entry and no known pipeline produces.++A renderer is a Python file with a ``render()`` function that returns the full text of+each output, keyed by its repo-relative path. It never writes files and never parses+arguments; this module does both, so ``--check`` and the write path cannot disagree.+"""++from __future__ import annotations++import sys+import runpy+from collections.abc import Callable, Iterable+from dataclasses import dataclass+from pathlib import Path++import click+from hogli.manifest import REPO_ROOT++REGISTRY = "tools/hogli-commands/hogli_commands/projections.py"+++@dataclass(frozen=True)+class Projection:+ name: str+ # Repo-relative path of the renderer module. It is loaded by path, so a renderer+ # inside `posthog/` or `products/` does not import that package's `__init__`.+ renderer: str+ # Repo-relative globs whose change needs a regeneration. The renderer always counts.+ inputs: tuple[str, ...]+ # Repo-relative paths of every file the renderer returns.+ outputs: tuple[str, ...]++ @property+ def triggers(self) -> tuple[str, ...]:+ return (self.renderer, *self.inputs)+++PROJECTIONS: tuple[Projection, ...] = (+ Projection(+ name="taxonomy",+ renderer="posthog/taxonomy/projection.py",+ inputs=("posthog/taxonomy/*",),+ outputs=(+ "frontend/src/taxonomy/core-filter-definitions-by-group.json",+ "services/mcp/src/lib/trace-property-allowlist.generated.ts",+ ),+ ),+ Projection(+ name="object-tags",+ renderer="posthog/object_tags/projection.py",+ inputs=("posthog/object_tags/*",),+ outputs=(+ "products/desktop/packages/core/src/inbox/objectKinds.generated.ts",+ "products/desktop/packages/shared/src/objectTagKinds.generated.ts",+ "frontend/src/lib/components/AgentObjectTags/objectKinds.generated.ts",+ ),+ ),+ Projection(+ name="task-model-catalog",+ renderer="products/tasks/scripts/model_catalog_projection.py",+ inputs=("products/tasks/backend/model_catalog.py",),+ outputs=(+ "products/tasks/frontend/modelCatalog.generated.ts",+ "products/desktop/packages/shared/src/model-catalog.generated.ts",+ ),+ ),+ Projection(+ name="mcp-oauth-scopes",+ renderer="posthog/scopes_projection.py",+ inputs=("posthog/scopes.py",),+ outputs=("services/mcp/src/lib/oauth-scopes.generated.ts",),+ ),+)+++def all_triggers() -> tuple[str, ...]:+ # The registry counts too: a changed entry can change what a projection writes.+ return (REGISTRY, *(trigger for projection in PROJECTIONS for trigger in projection.triggers))+++def all_outputs() -> tuple[str, ...]:+ return tuple(output for projection in PROJECTIONS for output in projection.outputs)+++class ProjectionRunner:+ def __init__(self, repo_root: Path, projections: Iterable[Projection]) -> None:+ self.repo_root = repo_root+ self.projections = tuple(projections)++ def render(self, projection: Projection) -> dict[str, str]:+ # Ahead of site-packages, so a renderer that imports `posthog` reads this+ # checkout and not an installed copy of the same name.+ if str(self.repo_root) not in sys.path:+ sys.path.insert(0, str(self.repo_root))+ render: Callable[[], dict[str, str]] = runpy.run_path(str(self.repo_root / projection.renderer))["render"]+ rendered = render()+ if set(rendered) != set(projection.outputs):+ raise click.ClickException(+ f"{projection.renderer} rendered {sorted(rendered)}, but the registry declares "+ f"{sorted(projection.outputs)} for '{projection.name}'. Keep the two in step."+ )+ return rendered++ def stale(self, projection: Projection) -> list[str]:+ # Bytes, not text, so no newline translation can hide or invent a difference.+ return [path for path, contents in self.render(projection).items() if self._read(path) != contents.encode()]++ def write(self, projection: Projection) -> list[str]:+ written: list[str] = []+ for path, contents in self.render(projection).items():+ target = self.repo_root / path+ if self._read(path) == contents.encode():+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ # Nothing reformats these bytes. A renderer emits the shape its workspace+ # formatter keeps, or the output sits in that formatter's ignore list, so the+ # drift check cannot flap.+ target.write_bytes(contents.encode())+ written.append(path)+ return written++ def _read(self, path: str) -> bytes | None:+ # None, not b"", so a missing file never matches an empty rendered output.+ target = self.repo_root / path+ return target.read_bytes() if target.exists() else None+++def _select(only: tuple[str, ...]) -> tuple[Projection, ...]:+ names = {projection.name for projection in PROJECTIONS}+ unknown = sorted(set(only) - names)+ if unknown:+ raise click.BadParameter(f"unknown projection(s) {unknown}; known: {sorted(names)}", param_hint="--only")+ return tuple(projection for projection in PROJECTIONS if not only or projection.name in only)++[email protected](name="build:projections")[email protected]("--check", is_flag=True, help="Exit 1 if a checked-in output is out of date, without writing anything.")[email protected]("--only", multiple=True, metavar="NAME", help="Run only this projection. Repeat for several.")+def cmd_build_projections(check: bool, only: tuple[str, ...]) -> None:+ """Regenerate the checked-in projections of Python modules (no dev stack needed)."""+ runner = ProjectionRunner(REPO_ROOT, _select(only))+ if check:+ stale = [(projection, path) for projection in runner.projections for path in runner.stale(projection)]+ if not stale:+ return+ # stdout, because ci:preflight reports `result.stdout or result.stderr`.+ for projection, path in stale:+ click.echo(f"{path} is out of date with {', '.join(projection.inputs)}.")+ click.echo("Run `hogli build:projections` and commit the result.")+ raise SystemExit(1)+ for projection in runner.projections:+ written = runner.write(projection)+ click.echo(f"{projection.name}: {'wrote ' + ', '.join(written) if written else 'already up to date'}")diff --git a/tools/hogli-commands/hogli_commands/tests/test_build.py b/tools/hogli-commands/hogli_commands/tests/test_build.pyindex 0025941085bd..9c32e54c1afa 100644--- a/tools/hogli-commands/hogli_commands/tests/test_build.py+++ b/tools/hogli-commands/hogli_commands/tests/test_build.py@@ -30,7 +30,8 @@ class TestTriggerMatching:(".oxfmtrc.json", "build:openapi"),(".oxlintrc.json", "build:openapi"),("posthog/hogql/grammar/HogQLParser.g4", "build:grammar"),- ("posthog/taxonomy/taxonomy.py", "build:taxonomy-json"),+ ("posthog/taxonomy/taxonomy.py", "build:projections"),+ ("products/tasks/backend/model_catalog.py", "build:projections"),("products/surveys/frontend/src/Survey.tsx", "build:products"),("products/posthog_ai/skills/foo/SKILL.md", "build:skills"),("services/mcp/src/handlers/foo.ts", "build:schema-mcp"),@@ -89,7 +90,7 @@ class TestBuildCommand:"changed_file,expected_command",[("frontend/src/queries/schema/index.ts", "build:schema"),- ("posthog/taxonomy/foo.py", "build:taxonomy-json"),+ ("posthog/taxonomy/foo.py", "build:projections"),],)@patch("hogli_commands.build.subprocess.run")diff --git a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.pyindex 909ade7d5545..960168f2326b 100644--- a/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/tests/test_ci_preflight.py@@ -122,21 +122,25 @@ class TestStrictAndFixContracts:assert "mypy" not in ran-class TestTaxonomyDriftCheck:+class TestProjectionsDriftCheck:@pytest.mark.parametrize("changed",["posthog/taxonomy/taxonomy.py",- "bin/build-taxonomy-json.py",+ "products/tasks/scripts/model_catalog_projection.py",+ "tools/hogli-commands/hogli_commands/projections.py","frontend/src/taxonomy/core-filter-definitions-by-group.json",+ "products/tasks/backend/model_catalog.py",+ "posthog/scopes.py",+ "services/mcp/src/lib/oauth-scopes.generated.ts",],)def test_every_side_of_the_drift_relation_triggers(self, changed: str) -> None:- check = next(chk for chk in DIFF_CHECKS if chk.key == "taxonomy")+ check = next(chk for chk in DIFF_CHECKS if chk.key == "projections")assert matches_globs(changed, check.triggers)def test_concrete_triggers_still_point_at_real_files(self) -> None:- check = next(chk for chk in DIFF_CHECKS if chk.key == "taxonomy")+ check = next(chk for chk in DIFF_CHECKS if chk.key == "projections")# Renaming the generator or its output leaves these triggers matching nothing,# and preflight stops catching a hand-edit with nothing else to notice.concrete = [trigger for trigger in check.triggers if "*" not in trigger]@@ -177,7 +181,7 @@ class TestTaxonomyDriftCheck:assert result.exit_code == 0assert "needs python-env" in result.outputran = [arg for call in mock_run.call_args_list for arg in call.args[0]]- assert "build:taxonomy-json" not in ran+ assert "build:projections" not in ran@patch("hogli_commands.ci_preflight._emit_telemetry")@patch("hogli_commands.ci_preflight._staleness", return_value=("pass", "even with master", {}))@@ -203,11 +207,11 @@ class TestTaxonomyDriftCheck:result = runner.invoke(cli, ["ci:preflight", "--strict"])- # Without --check the verify command is the write path, which rewrites the JSON- # and exits 0, so a drifted push would report pass instead of blocking.+ # If the verify command were the write path, it would rewrite the outputs and+ # exit 0, so a drifted push would report pass instead of blocking.assert result.exit_code == 1dispatched = [call.args[0] for call in mock_run.call_args_list]- assert ["hogli", "build:taxonomy-json", "--check"] in dispatched+ assert ["hogli", "build:projections", "--check"] in dispatchedclass TestStalenessRisks:diff --git a/tools/hogli-commands/hogli_commands/tests/test_projections.py b/tools/hogli-commands/hogli_commands/tests/test_projections.pynew file mode 100644index 000000000000..79211adffbc6--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_projections.py@@ -0,0 +1,64 @@+from __future__ import annotations++from pathlib import Path++import pytest++import click+from hogli_commands.projections import Projection, ProjectionRunner++RENDERER = """+def render():+ return {"out/first.generated.ts": "first\\n", "out/second.json": "{}"}+"""++PROJECTION = Projection(+ name="fake",+ renderer="fake_projection.py",+ inputs=("fake/*",),+ outputs=("out/first.generated.ts", "out/second.json"),+)+++def _runner(tmp_path: Path, renderer: str = RENDERER, projection: Projection = PROJECTION) -> ProjectionRunner:+ (tmp_path / projection.renderer).write_text(renderer)+ return ProjectionRunner(tmp_path, [projection])+++class TestProjectionRunner:+ @pytest.mark.parametrize(+ "on_disk,expected_stale",+ [+ ({}, ["out/first.generated.ts", "out/second.json"]),+ ({"out/first.generated.ts": "first\n", "out/second.json": "{ }"}, ["out/second.json"]),+ ({"out/first.generated.ts": "first\r\n", "out/second.json": "{}"}, ["out/first.generated.ts"]),+ ({"out/first.generated.ts": "first\n", "out/second.json": "{}"}, []),+ ],+ ids=["missing", "one-output-drifted", "newline-translated", "in-sync"],+ )+ def test_stale_compares_every_output_byte_for_byte(+ self, tmp_path: Path, on_disk: dict[str, str], expected_stale: list[str]+ ) -> None:+ runner = _runner(tmp_path)+ for path, contents in on_disk.items():+ (tmp_path / path).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / path).write_bytes(contents.encode())++ assert runner.stale(PROJECTION) == expected_stale++ def test_stale_writes_nothing_and_write_clears_it(self, tmp_path: Path) -> None:+ runner = _runner(tmp_path)++ assert runner.stale(PROJECTION) != []+ assert not (tmp_path / "out").exists()++ assert runner.write(PROJECTION) == ["out/first.generated.ts", "out/second.json"]+ assert runner.stale(PROJECTION) == []+ assert runner.write(PROJECTION) == []++ def test_renderer_outputs_must_match_the_registry(self, tmp_path: Path) -> None:+ undeclared = RENDERER.replace('"out/second.json": "{}"', '"out/other.json": "{}"')+ runner = _runner(tmp_path, renderer=undeclared)++ with pytest.raises(click.ClickException, match="Keep the two in step"):+ runner.stale(PROJECTION)