: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): treat product namespace calls on lib/api as manual api calls (#104242)
Julian Bez30d892719c6f
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 006878361dce..d360b505f879 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -196,6 +196,9 @@ jobs:- 'frontend/src/generated/core/api.ts'- 'products/*/frontend/generated/api.ts'- 'tools/hogli-commands/hogli_commands/api_ratchet.py'+ # The generated rule block is compared against the generator, so+ # editing it by hand has to reach the drift check.+ - '.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml'- 'hogli.yaml'- .github/workflows/ci-python.ymldiff --git a/.semgrep/rules/devex/prefer-codegen-api-namespaced.test.ts b/.semgrep/rules/devex/prefer-codegen-api-namespaced.test.tsnew file mode 100644index 000000000000..535fab2be397--- /dev/null+++ b/.semgrep/rules/devex/prefer-codegen-api-namespaced.test.ts@@ -0,0 +1,43 @@+// @ts-nocheck+// Test fixture for the generated prefer-codegen-api-namespaced-<product> rules.+// `semgrep --test` ignores paths.include, so every rule runs against this file and+// each line names the product rule that has to fire on it.++import api from 'lib/api'++// ruleid: prefer-codegen-api-namespaced-signals+const a = await api.signalReports.list()++// ruleid: prefer-codegen-api-namespaced-workflows+const b = await api.hogFlows.get(id)++// ruleid: prefer-codegen-api-namespaced-error_tracking+const c = await api.errorTracking.updateIssue(id, { status: 'resolved' })++// ruleid: prefer-codegen-api-namespaced-alerts+const d = await api.alerts.create({ name })++// A nested member chain is a different AST shape than api.<ns>.<method>().+// ruleid: prefer-codegen-api-namespaced-signals+const e = await api.signalSourceConfigs.runs.list({ limit: 10 })++// ruleid: prefer-codegen-api-namespaced-error_tracking+const f = await api.errorTracking.symbolSets.bulkDelete(ids)++// A namespace no generated client covers stays allowed.+// ok: prefer-codegen-api-namespaced-signals+const g = await api.signalTeamConfig.get()++// A namespace whose routes the generated clients gained is enforced from then on.+// ruleid: prefer-codegen-api-namespaced-posthog_ai+const h = await api.coreMemory.get()++// The bare verbs are the other rule's job.+// ok: prefer-codegen-api-namespaced-signals+const i = await api.get(`api/projects/${projectId}/signals/reports/`)++// ok: prefer-codegen-api-namespaced-signals+const j = await signalsReportsList(projectId)++// nosemgrep: prefer-codegen-api-namespaced-signals+const k = await api.signalReports.availableReviewers()diff --git a/.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml b/.semgrep/rules/devex/prefer-codegen-api-namespaced.yamlnew file mode 100644index 000000000000..03cc8587687d--- /dev/null+++ b/.semgrep/rules/devex/prefer-codegen-api-namespaced.yaml@@ -0,0 +1,1362 @@+# Product-scoped guards against calling a product's own endpoints through the+# `api` singleton in frontend/src/lib/api.ts instead of the product's generated+# client.+#+# DO NOT EDIT THE GENERATED BLOCK BY HAND. It is the mechanical output of+# `hogli lint:api-ratchet --write-semgrep`, which derives each product's+# namespaces from api.ts and the generated clients. `hogli lint:api-ratchet`+# fails when the block here disagrees with that output.+#+# One rule per product, rather than one rule listing every namespace: a call on+# another product's namespace, such as conversations calling api.comments, is+# legitimate, and a global list would block it.+#+# WARNING severity, so the backlog prints without failing and the devex job's+# --baseline-commit pass blocks only the calls a pull request adds. See+# .semgrep/rules/devex/README.md.+rules:+ # --- generated by `hogli lint:api-ratchet --write-semgrep` ---+ - id: prefer-codegen-api-namespaced-actions+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/actions. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/actions/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen actions` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-actions`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.actions.$METHOD(...)+ - pattern: api.actions.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/actions/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-ai_observability+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/ai_observability. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/ai_observability/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen ai_observability` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-ai_observability`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.aiObservability.$METHOD(...)+ - pattern: api.aiObservability.$MEMBER.$METHOD(...)+ - pattern: api.evaluationRuns.$METHOD(...)+ - pattern: api.evaluationRuns.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/ai_observability/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-alerts+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/alerts. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/alerts/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen alerts` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-alerts`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.alerts.$METHOD(...)+ - pattern: api.alerts.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/alerts/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-annotations+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/annotations. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/annotations/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen annotations` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-annotations`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.annotations.$METHOD(...)+ - pattern: api.annotations.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/annotations/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-batch_exports+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/batch_exports. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/batch_exports/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen batch_exports` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-batch_exports`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.batchExports.$METHOD(...)+ - pattern: api.batchExports.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/batch_exports/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-cdp+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/cdp. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/cdp/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen cdp` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-cdp`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.hogFunctions.$METHOD(...)+ - pattern: api.hogFunctions.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/cdp/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-cohorts+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/cohorts. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/cohorts/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen cohorts` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-cohorts`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.cohorts.$METHOD(...)+ - pattern: api.cohorts.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/cohorts/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-conversations+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/conversations. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/conversations/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen conversations` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-conversations`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.conversationsTickets.$METHOD(...)+ - pattern: api.conversationsTickets.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/conversations/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-customer_analytics+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/customer_analytics. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/customer_analytics/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen customer_analytics` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-customer_analytics`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.customerJourneys.$METHOD(...)+ - pattern: api.customerJourneys.$MEMBER.$METHOD(...)+ - pattern: api.customerProfileConfigs.$METHOD(...)+ - pattern: api.customerProfileConfigs.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/customer_analytics/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-dashboards+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/dashboards. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/dashboards/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen dashboards` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-dashboards`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.dashboardTemplates.$METHOD(...)+ - pattern: api.dashboardTemplates.$MEMBER.$METHOD(...)+ - pattern: api.dashboards.$METHOD(...)+ - pattern: api.dashboards.$MEMBER.$METHOD(...)+ - pattern: api.dataColorThemes.$METHOD(...)+ - pattern: api.dataColorThemes.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/dashboards/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-data_modeling+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/data_modeling. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/data_modeling/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen data_modeling` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-data_modeling`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.dataModelingEdges.$METHOD(...)+ - pattern: api.dataModelingEdges.$MEMBER.$METHOD(...)+ - pattern: api.dataModelingNodes.$METHOD(...)+ - pattern: api.dataModelingNodes.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/data_modeling/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-data_warehouse+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/data_warehouse. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/data_warehouse/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen data_warehouse` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-data_warehouse`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.dataModelingJobs.$METHOD(...)+ - pattern: api.dataModelingJobs.$MEMBER.$METHOD(...)+ - pattern: api.dataWarehouseManagedViewsets.$METHOD(...)+ - pattern: api.dataWarehouseManagedViewsets.$MEMBER.$METHOD(...)+ - pattern: api.dataWarehouseSavedQueries.$METHOD(...)+ - pattern: api.dataWarehouseSavedQueries.$MEMBER.$METHOD(...)+ - pattern: api.dataWarehouseSavedQueryDrafts.$METHOD(...)+ - pattern: api.dataWarehouseSavedQueryDrafts.$MEMBER.$METHOD(...)+ - pattern: api.dataWarehouseSavedQueryFolders.$METHOD(...)+ - pattern: api.dataWarehouseSavedQueryFolders.$MEMBER.$METHOD(...)+ - pattern: api.dataWarehouseTables.$METHOD(...)+ - pattern: api.dataWarehouseTables.$MEMBER.$METHOD(...)+ - pattern: api.dataWarehouseViewLinks.$METHOD(...)+ - pattern: api.dataWarehouseViewLinks.$MEMBER.$METHOD(...)+ - pattern: api.fixHogQLErrors.$METHOD(...)+ - pattern: api.fixHogQLErrors.$MEMBER.$METHOD(...)+ - pattern: api.insightVariables.$METHOD(...)+ - pattern: api.insightVariables.$MEMBER.$METHOD(...)+ - pattern: api.queryTabState.$METHOD(...)+ - pattern: api.queryTabState.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/data_warehouse/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-early_access_features+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/early_access_features. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/early_access_features/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen early_access_features` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-early_access_features`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.earlyAccessFeatures.$METHOD(...)+ - pattern: api.earlyAccessFeatures.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/early_access_features/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-endpoints+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/endpoints. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/endpoints/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen endpoints` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-endpoints`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.endpoint.$METHOD(...)+ - pattern: api.endpoint.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/endpoints/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-error_tracking+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/error_tracking. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/error_tracking/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen error_tracking` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-error_tracking`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.errorTracking.$METHOD(...)+ - pattern: api.errorTracking.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/error_tracking/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-event_definitions+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/event_definitions. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/event_definitions/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen event_definitions` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-event_definitions`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.eventDefinitions.$METHOD(...)+ - pattern: api.eventDefinitions.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/event_definitions/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-experiments+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/experiments. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/experiments/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen experiments` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-experiments`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.experiments.$METHOD(...)+ - pattern: api.experiments.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/experiments/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-exports+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/exports. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/exports/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen exports` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-exports`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.exports.$METHOD(...)+ - pattern: api.exports.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/exports/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-feature_flags+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/feature_flags. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/feature_flags/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen feature_flags` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-feature_flags`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.featureFlags.$METHOD(...)+ - pattern: api.featureFlags.$MEMBER.$METHOD(...)+ - pattern: api.organizationFeatureFlags.$METHOD(...)+ - pattern: api.organizationFeatureFlags.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/feature_flags/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-groups+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/groups. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/groups/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen groups` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-groups`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.groups.$METHOD(...)+ - pattern: api.groups.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/groups/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-integrations+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/integrations. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/integrations/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen integrations` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-integrations`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.integrations.$METHOD(...)+ - pattern: api.integrations.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/integrations/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-links+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/links. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/links/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen links` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-links`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.links.$METHOD(...)+ - pattern: api.links.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/links/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-logs+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/logs. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/logs/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen logs` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-logs`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.logs.$METHOD(...)+ - pattern: api.logs.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/logs/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-messaging+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/messaging. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/messaging/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen messaging` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-messaging`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.messaging.$METHOD(...)+ - pattern: api.messaging.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/messaging/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-notebooks+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/notebooks. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/notebooks/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen notebooks` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-notebooks`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.notebooks.$METHOD(...)+ - pattern: api.notebooks.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/notebooks/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-persons+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/persons. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/persons/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen persons` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-persons`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.persons.$METHOD(...)+ - pattern: api.persons.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/persons/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-platform_features+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/platform_features. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/platform_features/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen platform_features` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-platform_features`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.comments.$METHOD(...)+ - pattern: api.comments.$MEMBER.$METHOD(...)+ - pattern: api.organizationMembers.$METHOD(...)+ - pattern: api.organizationMembers.$MEMBER.$METHOD(...)+ - pattern: api.roles.$METHOD(...)+ - pattern: api.roles.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/platform_features/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-posthog_ai+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/posthog_ai. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/posthog_ai/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen posthog_ai` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-posthog_ai`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.conversations.$METHOD(...)+ - pattern: api.conversations.$MEMBER.$METHOD(...)+ - pattern: api.coreMemory.$METHOD(...)+ - pattern: api.coreMemory.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/posthog_ai/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-product_analytics+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/product_analytics. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/product_analytics/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen product_analytics` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-product_analytics`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.columnConfigurations.$METHOD(...)+ - pattern: api.columnConfigurations.$MEMBER.$METHOD(...)+ - pattern: api.insights.$METHOD(...)+ - pattern: api.insights.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/product_analytics/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-product_tours+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/product_tours. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/product_tours/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen product_tours` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-product_tours`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.productTours.$METHOD(...)+ - pattern: api.productTours.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/product_tours/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-replay+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/replay. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/replay/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen replay` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-replay`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.recordings.$METHOD(...)+ - pattern: api.recordings.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/replay/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-revenue_analytics+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/revenue_analytics. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/revenue_analytics/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen revenue_analytics` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-revenue_analytics`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.revenueAnalyticsJoins.$METHOD(...)+ - pattern: api.revenueAnalyticsJoins.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/revenue_analytics/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-signals+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/signals. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/signals/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen signals` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-signals`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.signalReports.$METHOD(...)+ - pattern: api.signalReports.$MEMBER.$METHOD(...)+ - pattern: api.signalSourceConfigs.$METHOD(...)+ - pattern: api.signalSourceConfigs.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/signals/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-subscriptions+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/subscriptions. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/subscriptions/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen subscriptions` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-subscriptions`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.subscriptions.$METHOD(...)+ - pattern: api.subscriptions.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/subscriptions/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-surveys+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/surveys. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/surveys/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen surveys` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-surveys`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.activity.$METHOD(...)+ - pattern: api.activity.$MEMBER.$METHOD(...)+ - pattern: api.surveys.$METHOD(...)+ - pattern: api.surveys.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/surveys/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-tasks+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/tasks. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/tasks/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen tasks` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-tasks`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.tasks.$METHOD(...)+ - pattern: api.tasks.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/tasks/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-user_interviews+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/user_interviews. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/user_interviews/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen user_interviews` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-user_interviews`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.userInterviews.$METHOD(...)+ - pattern: api.userInterviews.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/user_interviews/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-warehouse_sources+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/warehouse_sources. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/warehouse_sources/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen warehouse_sources` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-warehouse_sources`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.externalDataSchemas.$METHOD(...)+ - pattern: api.externalDataSchemas.$MEMBER.$METHOD(...)+ - pattern: api.externalDataSources.$METHOD(...)+ - pattern: api.externalDataSources.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/warehouse_sources/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-web_analytics+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/web_analytics. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/web_analytics/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen web_analytics` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-web_analytics`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.savedHeatmaps.$METHOD(...)+ - pattern: api.savedHeatmaps.$MEMBER.$METHOD(...)+ - pattern: api.webAnalyticsFilterPresets.$METHOD(...)+ - pattern: api.webAnalyticsFilterPresets.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/web_analytics/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'++ - id: prefer-codegen-api-namespaced-workflows+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/workflows. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/workflows/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen workflows` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-workflows`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+ - pattern: api.hogFlowTemplates.$METHOD(...)+ - pattern: api.hogFlowTemplates.$MEMBER.$METHOD(...)+ - pattern: api.hogFlows.$METHOD(...)+ - pattern: api.hogFlows.$MEMBER.$METHOD(...)+ paths:+ include:+ - '/products/workflows/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'+ # --- end generated ---diff --git a/.semgrep/rules/security/prefer-codegen-api.yaml b/.semgrep/rules/security/prefer-codegen-api.yamlindex 39fb725c8e5e..00fc8114b536 100644--- a/.semgrep/rules/security/prefer-codegen-api.yaml+++ b/.semgrep/rules/security/prefer-codegen-api.yaml@@ -14,6 +14,10 @@ rules:the maturity tooling continues to track tagged sites.severity: ERRORlanguages: [typescript, javascript]+ # Namespaced calls (api.signalReports.list()) are a different AST shape and+ # have a backlog in the hundreds, so they live in the WARNING-severity+ # .semgrep/rules/devex/prefer-codegen-api-namespaced.yaml, where the devex+ # job's --baseline-commit pass blocks only the ones a pull request adds.pattern-either:- pattern: api.get(...)- pattern: api.post(...)diff --git a/tools/hogli-commands/hogli_commands/api_ratchet.py b/tools/hogli-commands/hogli_commands/api_ratchet.pyindex 5b785c9cfc1b..d1990948b816 100644--- a/tools/hogli-commands/hogli_commands/api_ratchet.py+++ b/tools/hogli-commands/hogli_commands/api_ratchet.py@@ -22,7 +22,8 @@ add new debt. A shrinking baseline is the migration's progress metric.hogli lint:api-ratchet # check against the baselinehogli lint:api-ratchet --prune-baseline # drop stale entries, never add onehogli lint:api-ratchet --update-baseline # rewrite the baseline, new debt included- hogli lint:api-ratchet --namespaces # product-owned namespaces, for codegen+ hogli lint:api-ratchet --namespaces # product-owned namespaces and their products+ hogli lint:api-ratchet --write-semgrep # regenerate the per-product semgrep ruleshogli lint:api-ratchet --json # full report as JSON``ApiRequest`` builds ``/api/environments/{team_id}/...``, Orval emits@@ -36,6 +37,7 @@ from __future__ import annotationsimport reimport jsonfrom dataclasses import dataclass+from functools import lru_cachefrom pathlib import Pathfrom typing import Final@@ -62,6 +64,45 @@ PLUMBING_TEMPLATES: Final = frozenset({("projects",), ("projects", "{}"), ("orga# Sits next to the file it ratchets, so the person adding a path method sees it.BASELINE: Final = Path("frontend/src/lib/api-ratchet-baseline.txt")+SEMGREP_RULE: Final = Path(".semgrep/rules/devex/prefer-codegen-api-namespaced.yaml")+SEMGREP_BEGIN: Final = " # --- generated by `hogli lint:api-ratchet --write-semgrep` ---"+SEMGREP_END: Final = " # --- end generated ---"++# One rule per product. The message names the product because the rule is scoped to it,+# and the rule id carries the product so a `nosemgrep` line stays as narrow as the rule.+SEMGREP_RULE_TEMPLATE: Final = """\+ - id: prefer-codegen-api-namespaced-{product}+ message: >-+ Manual `api.<namespace>.<method>(...)` call in products/{product}. The namespace+ builds its URL in `frontend/src/lib/api.ts`, and this product's generated client+ already covers that URL. Use `products/{product}/frontend/generated/api.ts`.++ Informational while the backlog is worked down, but a call this pull request adds+ fails the job. `hogli product:maturity --codegen {product}` lists the call sites.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration+ workflow.++ If no generated equivalent is available yet (endpoint missing OpenAPI tags,+ dynamic URL, etc.), add `// nosemgrep: prefer-codegen-api-namespaced-{product}`+ above this line - the maturity tooling continues to track tagged sites.+ severity: WARNING+ languages: [typescript, javascript]+ pattern-either:+{patterns}+ paths:+ include:+ - '/products/{product}/frontend/'+ exclude:+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.stories.tsx'+ - '**/__mocks__/**'+ - '**/mocks/**'+"""+BASELINE_HEADER: Final = """\# ApiRequest path methods in frontend/src/lib/api.ts that a generated client# already covers, each with the route it duplicates. Grandfathered debt: the@@ -95,6 +136,34 @@ _CHAIN_BASE: Final = re.compile(r"this\.(\w+)\(")_RETURN_LINE: Final = re.compile(r"\s*return\b")_CHAINED_CALL: Final = re.compile(r"\.(\w+)\(")_NAMESPACE_START: Final = re.compile(r"^ (\w+): \{")+# A method of a namespace block, at the block's own depth or one group deeper.+_NAMESPACE_MEMBER: Final = re.compile(r"^ {8,12}(?:async )?(\w+)[(<]")+# A group of methods inside a namespace, api.signalScout.runs, always one level deep.+_NAMESPACE_GROUP: Final = re.compile(r"^ {8}(\w+): \{$")+# The HTTP method each ApiRequest verb sends, from its body in api.ts, plus the+# transport wrappers on the `api` object that send one without naming it. A member+# using an unknown wrapper is reported rather than dropped, so a new wrapper shows up+# as something to add here instead of quietly removing the member from the report.+VERB_METHODS: Final[dict[str, str]] = {+ "get": "GET",+ "getResponse": "GET",+ "loadPaginatedResults": "GET",+ "create": "POST",+ "createResponse": "POST",+ "createWithUploadProgress": "POST",+ "update": "PATCH",+ "put": "PUT",+ "delete": "DELETE",+}+# api.stream carries its method as a per-call option, so it is reported as+# unrecognized rather than guessed.+_VERB_CALL: Final = re.compile(rf"\.({'|'.join(VERB_METHODS)})\(")+# api.loadPaginatedResults(url) takes the assembled URL rather than chaining off the+# request, so the wrapper appears as a bare call on the api object too.+_TRANSPORT_CALL: Final = re.compile(rf"\bapi\.({'|'.join(VERB_METHODS)})\b")+# A direct call on the api object, so `api.someWrapper(url)` but not the namespace+# delegation `api.actions.get(...)`, which sends nothing of the member's own.+_API_CALL: Final = re.compile(r"\bapi\.(\w+)\s*(?:<[^(]*>)?\(")_MEMBER_CALL: Final = re.compile(r"\.(\w+)\(")_GENERATED_URL: Final = re.compile(r"`(/api/[^`]*)`")_TEMPLATE_HOLE: Final = re.compile(r"\$\{[^}]*\}")@@ -610,6 +679,91 @@ class GeneratedTemplates:return self.owners.get(template, frozenset())+@dataclass(frozen=True)+class NamespaceMember:+ """One method on the ``api`` singleton, with the request it sends."""++ namespace: str+ member: str+ template: tuple[str, ...]+ # Empty when the member sends its request through a transport this tool does not+ # know, which is a gap in VERB_METHODS rather than a missing generated function.+ method: str+ transport: str++ @property+ def path(self) -> str:+ """What a call site names: `signalScout.runs.list`."""+ return f"{self.namespace}.{self.member}"+++@dataclass(frozen=True)+class MemberSource:+ """A namespace method as it appears in api.ts."""++ name: str+ body: str+++def _split_members(block: str) -> list[MemberSource]:+ """The methods of a namespace block.++ A method inside a group keeps its path, ``runs.list``, because that is what the+ call site names: api.signalScout.runs.list(). api.ts nests one level deep, so a+ group is a line at the block's own indentation and its methods sit one deeper.+ """+ lines = block.splitlines()+ starts: list[tuple[int, str]] = [] # line index, dotted name+ group = ""+ for index, line in enumerate(lines):+ if (opening := _NAMESPACE_GROUP.match(line)) is not None:+ group = opening.group(1)+ continue+ member = _NAMESPACE_MEMBER.match(line)+ if member is None:+ continue+ nested = line.startswith(" " * 12)+ starts.append((index, f"{group}.{member.group(1)}" if nested and group else member.group(1)))+ bounds = [index for index, _ in starts] + [len(lines)]+ return [+ MemberSource(name=name, body="\n".join(lines[index : bounds[position + 1]]))+ for position, (index, name) in enumerate(starts)+ ]+++def _member_transport(body: str) -> str:+ """What the member calls to send its request, empty when nothing looks like one."""+ verb = _VERB_CALL.search(body)+ if verb is not None:+ return verb.group(1)+ wrapper = _TRANSPORT_CALL.search(body)+ if wrapper is not None:+ return wrapper.group(1)+ unknown = _API_CALL.search(body)+ return unknown.group(1) if unknown is not None else ""+++def _first_argument(argument: str) -> str:+ """The first argument of a call, empty when it takes none."""+ depth = 0+ for index, char in enumerate(argument):+ if char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ elif char == "," and depth == 0:+ return argument[:index].strip()+ return argument.strip()+++def _argument_segments_after(text: str, offset: int) -> tuple[str, ...]:+ """The segments the `withAction` calls after ``offset`` append."""+ segments: list[str] = []+ for call in re.finditer(r"\.(withAction|addPathComponent)\(", text[offset:]):+ segments.extend(_argument_segments(_read_call_argument(text[offset:], call.end() - 1)))+ return tuple(segments)++class Ratchet:"""The report: which path methods are redundant, and which namespaces use them."""@@ -637,6 +791,49 @@ class Ratchet:products[entry.name] = products.get(entry.name, frozenset()) | entry.productsreturn products+ def namespace_members(self) -> dict[str, NamespaceMember]:+ """Every ``api.<namespace>.<member>`` with the route and HTTP method it sends.++ The route alone cannot say whether a member is covered: the signals client+ generates GET and PATCH on a report but no DELETE, so a namespace method+ needs its verb checked as well.+ """+ members: dict[str, NamespaceMember] = {}+ for namespace, block in self._namespace_blocks().items():+ for source in _split_members(block):+ route = self._member_route(source.body)+ if route is None:+ continue+ transport = _member_transport(source.body)+ if not transport:+ continue # delegates to another namespace or only builds a URL+ member = NamespaceMember(+ namespace=namespace,+ member=source.name,+ template=route,+ method=VERB_METHODS.get(transport, ""),+ transport=transport,+ )+ members[member.path] = member+ return members++ def _member_route(self, body: str) -> tuple[str, ...] | None:+ """The route a member builds: its path method plus any action it appends.++ A path method that branches on an optional id builds a collection route and a+ detail route, and which one the member gets depends on what it passes:+ `api.alerts.list()` calls `alerts()` empty and gets the collection.+ """+ for call in _MEMBER_CALL.finditer(body):+ templates = self._resolver.templates(call.group(1))+ if not templates:+ continue+ passes_id = _first_argument(_read_call_argument(body, call.end() - 1)) != ""+ chosen = max(templates, key=len) if passes_id else min(templates, key=len)+ tail = _argument_segments_after(body, call.end())+ return normalize_template((*chosen, *tail))+ return None+def namespaces(self) -> dict[str, frozenset[str]]:"""Namespaces on the ``api`` singleton that call a redundant path method.@@ -695,6 +892,99 @@ def write_baseline(repo_root: Path, methods: set[str]) -> None:(repo_root / BASELINE).write_text(f"{BASELINE_HEADER}\n{body}")+# Each build reads api.ts and every generated client, and `product:maturity --all`+# asks once per product. A caller that rewrites one of those files mid-process has+# to call cache_clear().+@lru_cache(maxsize=1)+def _ratchet(repo_root: Path) -> Ratchet:+ return Ratchet(repo_root)+++def namespace_members(repo_root: Path | None = None) -> dict[str, NamespaceMember]:+ """Every ``api.<namespace>.<member>`` with the route and HTTP method it sends."""+ return _ratchet(repo_root or Path(REPO_ROOT)).namespace_members()+++def namespaces_owned_by(product: str, repo_root: Path | None = None) -> frozenset[str]:+ """``api`` namespaces whose path methods this product's generated client covers.++ The one source the guards share, so the semgrep rule, the ratchet and+ ``product:maturity`` cannot disagree about which namespaces a product owns.+ """+ ratchet = _ratchet(repo_root or Path(REPO_ROOT))+ return frozenset(namespace for namespace, products in ratchet.namespaces().items() if product in products)+++def owned_namespaces_by_product(ratchet: Ratchet) -> dict[str, list[str]]:+ """Product -> the ``api`` namespaces its own generated client covers, sorted."""+ owned: dict[str, list[str]] = {}+ for namespace, products in ratchet.namespaces().items():+ for product in products:+ if product == CORE_OWNER:+ continue # core owns no product directory, so no rule can scope to it+ owned.setdefault(product, []).append(namespace)+ return {product: sorted(namespaces) for product, namespaces in sorted(owned.items())}+++def render_semgrep_rules(ratchet: Ratchet) -> str:+ """The generated rule block: one rule per product, scoped to that product's tree.++ One global namespace list would fire on a legitimate cross-product call, such as+ conversations calling api.comments, and the blocking new-warning pass would stop+ it. Scoping each namespace to the product that owns it matches what+ ``product:maturity`` counts.+ """+ blocks: list[str] = []+ for product, namespaces in owned_namespaces_by_product(ratchet).items():+ patterns = "\n".join(+ # Nested members (api.signalScout.runs.list) are a different AST shape, so+ # each namespace needs the one-level and the two-level pattern.+ f" - pattern: api.{namespace}.$METHOD(...)\n"+ f" - pattern: api.{namespace}.$MEMBER.$METHOD(...)"+ for namespace in namespaces+ )+ blocks.append(SEMGREP_RULE_TEMPLATE.format(product=product, patterns=patterns))+ return "\n".join(blocks)+++@dataclass(frozen=True)+class MarkedBlock:+ """A rule file split around its generated block."""++ before: str+ body: str+ after: str+++def _read_marked_block(text: str) -> MarkedBlock:+ for marker in (SEMGREP_BEGIN, SEMGREP_END):+ if marker not in text:+ raise SystemExit(f"{SEMGREP_RULE}: marker {marker.strip()!r} is gone — restore it, indentation included.")+ before, marked = text.split(SEMGREP_BEGIN, 1)+ body, after = marked.split(SEMGREP_END, 1)+ return MarkedBlock(before=before, body=body.lstrip("\n"), after=after)+++def write_semgrep_rules(repo_root: Path, ratchet: Ratchet) -> int:+ """Rewrite the generated rule block in place. Returns the rule count."""+ path = repo_root / SEMGREP_RULE+ block = _read_marked_block(path.read_text())+ path.write_text(f"{block.before}{SEMGREP_BEGIN}\n{render_semgrep_rules(ratchet)}{SEMGREP_END}{block.after}")+ return len(owned_namespaces_by_product(ratchet))+++def semgrep_drift(repo_root: Path, ratchet: Ratchet) -> str | None:+ """Why the committed rule block disagrees with the generator, or None if it agrees."""+ path = repo_root / SEMGREP_RULE+ if not path.exists():+ return "the rule file is missing"+ text = path.read_text()+ if SEMGREP_BEGIN not in text or SEMGREP_END not in text:+ return "the generated block's markers are gone"+ committed = _read_marked_block(text).body+ return None if committed == render_semgrep_rules(ratchet) else "the committed rules are out of date"++def _report_json(ratchet: Ratchet, new: set[str], stale: set[str]) -> str:return json.dumps({@@ -717,13 +1007,26 @@ def _report_json(ratchet: Ratchet, new: set[str], stale: set[str]) -> str:@click.option("--update-baseline", is_flag=True, help="Rewrite the baseline from the current state (it can grow).")@click.option("--prune-baseline", is_flag=True, help="Drop stale baseline entries. Never adds one.")@click.option("--namespaces", is_flag=True, help="Print the product-owned api namespaces and their products.")+ "--write-semgrep",+ is_flag=True,+ help="Regenerate the namespace patterns in the prefer-codegen-api-namespaced semgrep rule.",+)@click.option("--json", "as_json", is_flag=True, help="Print the full report as JSON.")-def cmd_lint_api_ratchet(update_baseline: bool, prune_baseline: bool, namespaces: bool, as_json: bool) -> None:+def cmd_lint_api_ratchet(+ update_baseline: bool, prune_baseline: bool, namespaces: bool, write_semgrep: bool, as_json: bool+) -> None:"""Fail on a new ApiRequest path method that a generated client already covers."""repo_root = Path(REPO_ROOT)- ratchet = Ratchet(repo_root)+ ratchet = _ratchet(repo_root)redundant = {entry.entry for entry in ratchet.redundant}+ if write_semgrep:+ count = write_semgrep_rules(repo_root, ratchet)+ click.echo(f"{SEMGREP_RULE}: {count} product rule(s) written.")+ if not prune_baseline and not update_baseline:+ return+if namespaces:for namespace, products in sorted(ratchet.namespaces().items()):click.echo(f"{namespace} {','.join(sorted(products))}")@@ -735,6 +1038,7 @@ def cmd_lint_api_ratchet(update_baseline: bool, prune_baseline: bool, namespacesif prune_baseline:write_baseline(repo_root, baseline - stale)+ write_semgrep_rules(repo_root, ratchet)click.echo(f"Baseline pruned: {len(stale)} stale entry/entries dropped, {len(baseline - stale)} left.")if new:click.echo(f"{len(new)} new duplicate(s) stay unlisted, so the check still fails on them.")@@ -754,6 +1058,8 @@ def cmd_lint_api_ratchet(update_baseline: bool, prune_baseline: bool, namespacesclick.echo(_report_json(ratchet, new, stale))raise SystemExit(1 if new else 0)+ drift = semgrep_drift(repo_root, ratchet)+click.echo(f"ApiRequest path methods with a generated twin: {len(redundant)} ({len(baseline)} in the baseline)")if stale:click.echo(f"\n⚠️ {len(stale)} stale baseline entry/entries — gone or no longer redundant:")@@ -776,4 +1082,7 @@ def cmd_lint_api_ratchet(update_baseline: bool, prune_baseline: bool, namespaces"Agents: invoke the `adopting-generated-api-types` skill.")raise SystemExit(1)- click.echo("✅ No new path methods duplicating a generated client.")+ if drift is not None:+ click.echo(f"\n❌ {SEMGREP_RULE} is stale: {drift}.\n Run: hogli lint:api-ratchet --write-semgrep")+ raise SystemExit(1)+ click.echo("✅ No new path methods duplicating a generated client, and the semgrep rules match.")diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex b8b6b4baf754..61f0c7cdcb76 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -236,11 +236,12 @@ DIFF_CHECKS: list[DiffCheck] = ["frontend/src/lib/api-ratchet-baseline.txt","frontend/src/generated/core/api.ts","products/*/frontend/generated/api.ts",+ ".semgrep/rules/devex/prefer-codegen-api-namespaced.yaml",],verify=["hogli", "lint:api-ratchet"],# Prune, never update: --update-baseline would grandfather the duplicate the# branch just added, which is the one thing the check exists to stop.- fix=["hogli", "lint:api-ratchet", "--prune-baseline"],+ fix=["hogli", "lint:api-ratchet", "--prune-baseline", "--write-semgrep"],requires=("python-env",),),DiffCheck(diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.pyindex b54738ab7ca7..a895ea850e29 100644--- a/tools/hogli-commands/hogli_commands/product/maturity.py+++ b/tools/hogli-commands/hogli_commands/product/maturity.py@@ -43,7 +43,7 @@ from .isolation import ()from .paths import PRODUCTS_DIR, REPO_ROOT, TACH_TOML, find_views_path, get_tach_blockfrom .product_yaml import load_all_product_yamls, load_product_yaml-from .ts_helpers import codegen_adoption, codegen_call_sites+from .ts_helpers import ManualCallSite, codegen_adoption, codegen_call_sites# ---------------------------------------------------------------------------# Config loading (best-effort from migration_config.json)@@ -744,6 +744,17 @@ def score_boundaries(# ---------------------------------------------------------------------------+def _call_site_target(site: ManualCallSite) -> str:+ """What to migrate a manual call site to, for the evidence line."""+ if site.generated_equivalent:+ return f"→ {site.generated_equivalent}"+ if site.note:+ return f"({site.note})"+ if site.namespaced:+ return "→ this product's generated client"+ return "(no match)"++def score_codegen(product_dir: Path) -> DimensionScore:"""Frontend code generation adoption.@@ -791,11 +802,7 @@ def score_codegen(product_dir: Path) -> DimensionScore:)sites = codegen_call_sites(frontend_dir)if sites:- items = [- f"{site.file}:{site.line} {site.verb} "- + (f"→ {site.generated_equivalent}" if site.generated_equivalent else "(no match)")- for site in sites- ]+ items = [f"{site.file}:{site.line} {site.verb} {_call_site_target(site)}" for site in sites]evidence.append(("call sites", items))skills.append("/adopting-generated-api-types")skills.append("/improving-drf-endpoints")@@ -1203,7 +1210,7 @@ def generate_codegen_report(products: list[str] | None = None) -> str:if not sites:continue- matched = sum(1 for s in sites if s.generated_equivalent)+ matched = sum(1 for s in sites if s.generated_equivalent or s.namespaced)total_manual += len(sites)total_matched += matched@@ -1211,8 +1218,7 @@ def generate_codegen_report(products: list[str] | None = None) -> str:lines.append(f"{name} {matched}/{len(sites)} matched ({pct}%)")for site in sites:- arrow = f"→ {site.generated_equivalent}" if site.generated_equivalent else " (no match)"- lines.append(f" {site.file}:{site.line} {site.verb}({site.url[:50]}) {arrow}")+ lines.append(f" {site.file}:{site.line} {site.verb}({site.url[:50]}) {_call_site_target(site)}")lines.append("")diff --git a/tools/hogli-commands/hogli_commands/product/ts_helpers.py b/tools/hogli-commands/hogli_commands/product/ts_helpers.pyindex 18717f3e9013..8ca0bdf42c64 100644--- a/tools/hogli-commands/hogli_commands/product/ts_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ts_helpers.py@@ -6,6 +6,8 @@ import refrom dataclasses import dataclassfrom pathlib import Path+from hogli_commands.api_ratchet import NamespaceMember, namespace_members, namespaces_owned_by+_EXPORTED_ASYNC_RE = re.compile(r"^export\s+const\s+(\w+)\s*=\s*async\s*\(", re.MULTILINE)@@ -87,18 +89,33 @@ _VERB_TO_METHOD = {}-def count_manual_api_calls(frontend_dir: Path) -> int:- """Count manual HTTP calls via the shared api object.+def owned_namespace_pattern(frontend_dir: Path) -> re.Pattern[str] | None:+ """Regex over `api.<namespace>.<method>(` for the namespaces this product owns.++ A namespace counts as owned when an `ApiRequest` path method behind it builds+ a URL this product's generated client already emits, which `lint:api-ratchet`+ decides. Returns None when the product owns none.+ """+ owned = namespaces_owned_by(frontend_dir.parent.name)+ if not owned:+ return None+ alternatives = "|".join(sorted(owned))+ # `(?:\s*\.\s*\w+)+` so a nested chain (api.signalScout.runs.list) counts once, and+ # a call the formatter broke across lines (api.endpoint\n .get(...)) counts at all.+ return re.compile(rf"\bapi\.({alternatives})((?:\s*\.\s*\w+)+)\s*(?:<[^(]*>)?\s*\(")- Only counts direct HTTP verb calls: api.get(, api.post(, api.create(,- api.update(, api.delete(, api.patch(, api.put(.- Does NOT count api.<namespace>.<method>( — those are shared platform- utilities (api.integrations.authorizeUrl, api.comments.create, etc.)- that belong to other products and aren't replaceable by this product's- generated client.+def count_manual_api_calls(frontend_dir: Path) -> int:+ """Count manual API calls via the shared api object.++ Counts direct HTTP verb calls (api.get(, api.post(, api.create(, ...) and+ `api.<namespace>.<method>(` where the namespace belongs to this product -+ the generated client already covers those URLs, so they are this product's+ debt. A namespace owned by another product, or by none, is not counted:+ api.comments.create is not this product's call to migrate."""generated_dir = frontend_dir / "generated"+ namespaced = owned_namespace_pattern(frontend_dir)total = 0for ts_file in _collect_ts_files(frontend_dir):@@ -114,6 +131,8 @@ def count_manual_api_calls(frontend_dir: Path) -> int:if not has_api_import:continuetotal += len(_HTTP_VERBS.findall(content))+ if namespaced is not None:+ total += len(namespaced.findall(content))return total@@ -160,6 +179,80 @@ class ManualCallSite:url: strmethod: strgenerated_equivalent: str | None+ # A call on a namespace this product owns whose route and verb the generated client+ # covers. False when the client has no operation for it, which is a backend gap.+ namespaced: bool = False+ # Why a site has no generated function, when the reason is not a missing endpoint.+ note: str = ""+++def _generated_key(request: NamespaceMember) -> str:+ """The member's route in the shape `_parse_generated_url_map` keys on."""+ return "/api/" + "/".join("{p}" if segment == "{}" else segment for segment in request.template)+++def _candidate_functions(request: NamespaceMember, generated_map: dict[tuple[str, str], str]) -> list[str]:+ """Generated functions whose route fits the member's route, holes as wildcards.++ A member that takes a path segment from its caller+ (api.errorTracking.createRule(ErrorTrackingRuleType.Bypass, ...)) builds a mask+ rather than one route, and the client generates a function per concrete segment.+ `_narrow_by_arguments` picks between the survivors using the call's own tokens.+ """+ mask = _generated_key(request).split("/")+ fitting: dict[str, list[str]] = {}+ for (url, method), name in generated_map.items():+ if method != request.method:+ continue+ segments = url.split("/")+ if len(segments) != len(mask):+ continue+ if all(want in {have, "{p}"} for want, have in zip(mask, segments)):+ fitting[name] = segments+ if not fitting:+ return []+ # A mask hole can be a real id or a resource-type selector - the mask alone can't+ # say which. But when some candidate does vary by id in that spot, a literal+ # action route sharing the spot (`.../reorder/`) is a different operation, not+ # this one with an id, so it drops out rather than passing as an ambiguous match.+ if mask[-1] == "{p}" and any(segments[-1] == "{p}" for segments in fitting.values()):+ fitting = {name: segments for name, segments in fitting.items() if segments[-1] == "{p}"}+ return sorted(fitting)+++def _first_call_argument(arguments: str) -> str:+ """The text of a call's first argument, up to its own top-level comma."""+ depth = 0+ for index, char in enumerate(arguments):+ if char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ elif char == "," and depth == 0:+ return arguments[:index]+ return arguments+++def _narrow_by_arguments(candidates: list[str], arguments: str) -> list[str]:+ """The candidates the call's selector argument names, or all of them.++ The route the member's own path method builds takes its dynamic segment from the+ first argument (`errorTrackingRule(ruleType, id)`) - later arguments are the+ entity id or payload, not the selector, and a token from one of those+ (`values.rule.id`) can match every candidate's shared `Rule`/`Rules` suffix and+ defeat the narrowing entirely. `ErrorTrackingRuleType.Bypass` and `'bypass_rules'`+ both name the bypass route, so the token after the last dot or inside the quotes+ picks the function.+ """+ selector = _first_call_argument(arguments)+ tokens = [+ token.lower()+ for token in re.findall(r"""['"`](\w+)['"`]|\.(\w+)|\b([A-Z]\w+)""", selector)+ for token in token+ if token+ ]+ named = [name for name in candidates if any(token in name.lower() for token in tokens)]+ return named or candidatesdef _normalize_url(url: str) -> str:@@ -203,25 +296,67 @@ def _parse_generated_url_map(api_ts: Path) -> dict[tuple[str, str], str]:):fn_name = m.group(1)method = m.group(2)- fn_text = content[m.start() : m.start() + 500]- url_call = re.search(r"(get\w+Url)\(", fn_text)- if url_call and url_call.group(1) in url_helpers:- raw_url = url_helpers[url_call.group(1)]+ # The last helper call before the method, rather than the first in a fixed+ # window: a function that builds a FormData first pushes the call past 500+ # characters, and the helper always sits on the line that sends the request.+ url_calls = re.findall(r"(get\w+Url)\(", m.group(0))+ if url_calls and url_calls[-1] in url_helpers:+ raw_url = url_helpers[url_calls[-1]]url = _normalize_url(raw_url)generated[(url, method)] = fn_namereturn generated+def _read_arguments(content: str, open_paren: int) -> str:+ """The argument text of the call whose `(` sits at ``open_paren``."""+ depth = 0+ for index in range(open_paren, len(content)):+ if content[index] == "(":+ depth += 1+ elif content[index] == ")":+ depth -= 1+ if depth == 0:+ return content[open_paren + 1 : index]+ return ""+++def _resolve_namespaced(+ request: NamespaceMember | None,+ content: str,+ open_paren: int,+ generated_map: dict[tuple[str, str], str],+) -> tuple[str | None, str]:+ """The generated function for a namespaced call site, and why there is none."""+ if request is None:+ return None, ""+ if not request.method:+ return None, f"unrecognized transport: api.{request.transport}"+ exact = generated_map.get((_generated_key(request), request.method))+ if exact is not None:+ return exact, ""+ candidates = _candidate_functions(request, generated_map)+ if not candidates:+ return None, ""+ named = _narrow_by_arguments(candidates, _read_arguments(content, open_paren))+ return (named[0] if len(named) == 1 else " | ".join(named)), ""++def codegen_call_sites(frontend_dir: Path) -> list[ManualCallSite]:"""Find all manual API call sites and match them to generated equivalents.- Returns a list of ManualCallSite objects with file, line, verb, url,- and the matched generated function name (or None if no match).+ Returns a list of ManualCallSite objects with file, line, verb, url, and the+ matched generated function name (or None if no match). A call on a namespace+ this product owns carries no URL at the call site, so it names the client that+ covers it instead of a function."""api_ts = frontend_dir / "generated" / "api.ts"generated_map = _parse_generated_url_map(api_ts)generated_dir = frontend_dir / "generated"+ namespaced = owned_namespace_pattern(frontend_dir)+ # Built once for the whole report: it parses all of lib/api.ts, and a product with+ # many files importing it would otherwise repeat that parse once per file.+ members = namespace_members() if namespaced is not None else {}sites: list[ManualCallSite] = []@@ -264,6 +399,28 @@ def codegen_call_sites(frontend_dir: Path) -> list[ManualCallSite]:))+ if namespaced is None:+ continue+ for m in namespaced.finditer(content):+ namespace = m.group(1)+ member = re.sub(r"\s+", "", m.group(2)).lstrip(".")+ # The route and verb the namespace method sends, so a member the client has+ # no operation for is reported as a gap rather than as already covered.+ request = members.get(f"{namespace}.{member}")+ equivalent, note = _resolve_namespaced(request, content, m.end() - 1, generated_map)+ sites.append(+ ManualCallSite(+ file=rel_path,+ line=content[: m.start()].count("\n") + 1,+ verb=f"{namespace}.{member}",+ url="/".join(request.template) if request is not None else "",+ method=request.method if request is not None else "",+ generated_equivalent=equivalent,+ namespaced=equivalent is not None,+ note=note,+ )+ )+return sitesdiff --git a/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py b/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.pyindex ae7873342b1c..34c09928b6c2 100644--- a/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py+++ b/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py@@ -4,6 +4,7 @@ from pathlib import Pathimport pytest+import yamlfrom click.testing import CliRunner, Resultfrom hogli_commands import api_ratchetfrom hogli_commands.api_ratchet import ApiRequestResolver, Ratchet, cmd_lint_api_ratchet, read_baseline@@ -197,6 +198,10 @@ def _write_repo((root / "products/workflows/frontend/generated/api.ts").write_text(GENERATED_WORKFLOWS)(root / api_ratchet.CORE_GENERATED).parent.mkdir(parents=True, exist_ok=True)(root / api_ratchet.CORE_GENERATED).write_text(GENERATED_CORE)+ rule = root / api_ratchet.SEMGREP_RULE+ rule.parent.mkdir(parents=True, exist_ok=True)+ rule.write_text(f"rules:\n{api_ratchet.SEMGREP_BEGIN}\n{api_ratchet.SEMGREP_END}\n")+ api_ratchet.write_semgrep_rules(root, Ratchet(root))if baseline is not None:(root / api_ratchet.BASELINE).write_text(baseline)@@ -409,6 +414,97 @@ class TestBaselineFixModes:assert runner.invoke(cmd_lint_api_ratchet, []).exit_code == 0+class TestNamespaceMembers:+ # alerts() branches on an optional id, so api.alerts.list() must get the collection+ # route and not the detail one, or the report names the wrong generated function.+ def test_a_member_gets_the_route_its_arguments_select(self, tmp_path: Path) -> None:+ api_ts = API_TS_FIXTURE.replace(+ "const api = {",+ "const api = {\n"+ " alerts: {\n"+ " async list(): Promise<any> {\n"+ " return await new ApiRequest().alerts().get()\n"+ " },\n"+ " async get(alertId: string): Promise<any> {\n"+ " return await new ApiRequest().alerts(alertId).get()\n"+ " },\n"+ " },",+ ).replace(+ " public hogFlows(): ApiRequest {",+ " public alerts(alertId?: string, teamId?: TeamType['id']): ApiRequest {\n"+ " if (alertId) {\n"+ " return this.projectsDetail(teamId).addPathComponent('alerts').addPathComponent(alertId)\n"+ " }\n"+ " return this.projectsDetail(teamId).addPathComponent('alerts')\n"+ " }\n\n"+ " public hogFlows(): ApiRequest {",+ )+ _write_repo(tmp_path, api_ts=api_ts)+ members = Ratchet(tmp_path).namespace_members()+ assert members["alerts.list"].template == ("projects", "{}", "alerts")+ assert members["alerts.get"].template == ("projects", "{}", "alerts", "{}")+++class TestMemberTransports:+ # A member that sends through a wrapper used to be dropped, which hid the call from+ # the report while the semgrep rule still flagged it.+ def test_a_wrapper_counts_as_its_verb_and_an_unknown_one_is_reported(self, tmp_path: Path) -> None:+ api_ts = API_TS_FIXTURE.replace(+ " signalReports: {",+ " signalReports: {\n"+ " async paginated(): Promise<any> {\n"+ " const url = new ApiRequest().signalReports().assembleFullUrl()\n"+ " return await api.loadPaginatedResults(url)\n"+ " },\n"+ " async streamed(): Promise<any> {\n"+ " return await api.stream(new ApiRequest().signalReports().assembleFullUrl(), {})\n"+ " },",+ )+ _write_repo(tmp_path, api_ts=api_ts)+ members = Ratchet(tmp_path).namespace_members()+ assert members["signalReports.paginated"].method == "GET"+ # api.stream takes its method as a per-call option, so it stays unrecognized.+ assert members["signalReports.streamed"].method == ""+ assert members["signalReports.streamed"].transport == "stream"+++class TestSemgrepRules:+ def test_rules_are_scoped_to_the_owning_product(self, tmp_path: Path) -> None:+ _write_repo(tmp_path)+ parsed = yaml.safe_load((tmp_path / api_ratchet.SEMGREP_RULE).read_text())+ by_id = {rule["id"]: rule for rule in parsed["rules"]}+ assert sorted(by_id) == [+ "prefer-codegen-api-namespaced-signals",+ "prefer-codegen-api-namespaced-workflows",+ ]+ signals = by_id["prefer-codegen-api-namespaced-signals"]+ assert signals["paths"]["include"] == ["/products/signals/frontend/"]+ assert signals["severity"] == "WARNING"+ # Both nesting depths, so api.signalScout.runs.list() cannot slip through.+ assert signals["pattern-either"] == [+ {"pattern": "api.signalReports.$METHOD(...)"},+ {"pattern": "api.signalReports.$MEMBER.$METHOD(...)"},+ ]+ # A namespace only the core client covers belongs to no product, so no rule.+ assert "prefer-codegen-api-namespaced-core" not in by_id++ def test_the_check_fails_when_the_committed_rules_are_stale(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines(+ "hogFlows", "propertyDefinitions", "organizationMembers", "signalReport", "signalReports"+ ),+ )+ rule = tmp_path / api_ratchet.SEMGREP_RULE+ rule.write_text(rule.read_text().replace("api.signalReports.$METHOD(...)", "api.somethingElse.$METHOD(...)"))+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)+ result = runner.invoke(cmd_lint_api_ratchet, [])+ assert result.exit_code == 1+ assert "--write-semgrep" in result.output++class TestCommand:def _run(self, monkeypatch: pytest.MonkeyPatch, root: Path, *args: str) -> Result:monkeypatch.setattr(api_ratchet, "REPO_ROOT", root)diff --git a/tools/hogli-commands/hogli_commands/tests/test_ts_helpers.py b/tools/hogli-commands/hogli_commands/tests/test_ts_helpers.pynew file mode 100644index 000000000000..fe883ed8b8d4--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_ts_helpers.py@@ -0,0 +1,225 @@+from __future__ import annotations++from pathlib import Path++import pytest++from hogli_commands import api_ratchet+from hogli_commands.product.ts_helpers import codegen_call_sites, count_manual_api_calls++API_TS = """\+export class ApiRequest {+ public projectsDetail(id: ProjectType['id'] = ApiConfig.getCurrentProjectId()): ApiRequest {+ return this.addPathComponent('projects').addPathComponent(id)+ }++ public signalReports(teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId).addPathComponent('signals').addPathComponent('reports')+ }++ public signalReport(id: string, teamId?: TeamType['id']): ApiRequest {+ return this.signalReports(teamId).addPathComponent(id)+ }++ public signalRules(ruleType: string, teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId).addPathComponent('signals').addPathComponent(ruleType)+ }++ public signalRule(ruleType: string, id: string): ApiRequest {+ return this.signalRules(ruleType).addPathComponent(id)+ }++ public signalReorderRules(ruleType: string): ApiRequest {+ return this.signalRules(ruleType).addPathComponent('reorder')+ }++ public signalScoutRuns(teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId).addPathComponent('signals').addPathComponent('scout').addPathComponent('runs')+ }++ public comments(teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId).addPathComponent('comments')+ }+}++const api = {+ signalReports: {+ async list(): Promise<any> {+ return await new ApiRequest().signalReports().get()+ },+ async setState(id: string, data: any): Promise<any> {+ return await new ApiRequest().signalReport(id).withAction('state').create({ data })+ },+ async createRule(ruleType: string, data: any): Promise<any> {+ return await new ApiRequest().signalRules(ruleType).create({ data })+ },+ async updateRule(ruleType: string, id: string, data: any): Promise<any> {+ return await new ApiRequest().signalRule(ruleType, id).update({ data })+ },+ async reorderRules(ruleType: string, orders: any): Promise<any> {+ return await new ApiRequest().signalReorderRules(ruleType).update({ data: { orders } })+ },+ async availableReviewers(): Promise<any> {+ return await new ApiRequest().signalReports().withAction('available_reviewers').get()+ },+ },+ signalScout: {+ runs: {+ async list(): Promise<any> {+ return await new ApiRequest().signalScoutRuns().get()+ },+ },+ },+ comments: {+ async list(): Promise<any> {+ return await new ApiRequest().comments().get()+ },+ },+}+"""++GENERATED_SIGNALS = """\+export const getSignalsReportsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/reports/`+}+export const signalsReportsList = async (projectId: string) => {+ return apiMutator({ url: getSignalsReportsListUrl(projectId), method: 'GET' })+}+export const signalsReportsStateCreate = async (projectId: string, id: string) => {+ return apiMutator({ url: getSignalsReportsStateCreateUrl(projectId, id), method: 'POST' })+}+export const getSignalsReportsStateCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/reports/${id}/state/`+}+export const signalsAssignmentRulesCreate = async (projectId: string) => {+ return apiMutator({ url: getSignalsAssignmentRulesCreateUrl(projectId), method: 'POST' })+}+export const getSignalsAssignmentRulesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/assignment_rules/`+}+export const signalsGroupingRulesCreate = async (projectId: string) => {+ return apiMutator({ url: getSignalsGroupingRulesCreateUrl(projectId), method: 'POST' })+}+export const getSignalsGroupingRulesCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/grouping_rules/`+}+export const signalsAssignmentRulesPartialUpdate = async (projectId: string, id: string) => {+ return apiMutator({ url: getSignalsAssignmentRulesPartialUpdateUrl(projectId, id), method: 'PATCH' })+}+export const getSignalsAssignmentRulesPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/signals/assignment_rules/${id}/`+}+export const signalsAssignmentRulesReorderPartialUpdate = async (projectId: string) => {+ return apiMutator({ url: getSignalsAssignmentRulesReorderPartialUpdateUrl(projectId), method: 'PATCH' })+}+export const getSignalsAssignmentRulesReorderPartialUpdateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/assignment_rules/reorder/`+}+export const getSignalsScoutRunsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/`+}+export const signalsScoutRunsList = async (projectId: string) => {+ return apiMutator({ url: getSignalsScoutRunsListUrl(projectId), method: 'GET' })+}+"""++GENERATED_COMMENTS = """\+export const getCommentsListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/comments/`+}+export const commentsList = async (projectId: string) => {+ return apiMutator({ url: getCommentsListUrl(projectId), method: 'GET' })+}+"""++PRODUCT_FILE = """\+import api from 'lib/api'++export const load = async (): Promise<void> => {+ await api.signalReports.list()+ await api.signalReports.setState(id, { state: 'resolved' })+ await api.signalScout.runs.list({ limit: 10 })+ await api.signalReports.availableReviewers()+ await api.signalReports+ .setState(id, { state: 'resolved' })+ await api.signalReports.createRule(SignalRuleType.Grouping, values.rule.id)+ await api.signalReports.createRule(ruleTypeFromProps, rule)+ await api.signalReports.updateRule(SignalRuleType.Assignment, id, rule)+ await api.comments.list()+ await api.get(`api/projects/${projectId}/signals/config/`)+}+"""+++def repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:+ (tmp_path / "frontend/src/lib").mkdir(parents=True)+ (tmp_path / "frontend/src/lib/api.ts").write_text(API_TS)+ for product, generated in (("signals", GENERATED_SIGNALS), ("platform_features", GENERATED_COMMENTS)):+ directory = tmp_path / "products" / product / "frontend" / "generated"+ directory.mkdir(parents=True)+ (directory / "api.ts").write_text(generated)+ (tmp_path / "products/signals/frontend/reportsLogic.ts").write_text(PRODUCT_FILE)+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)+ api_ratchet._ratchet.cache_clear()+ return tmp_path+++class TestParameterisedRoutes:+ # The route is a mask, so the call's own argument decides which generated function+ # replaces it; reporting the mask as unmatched sent the reader looking for nothing.+ def test_a_literal_argument_picks_the_generated_function(self, repo: Path) -> None:+ sites = codegen_call_sites(repo / "products/signals/frontend")+ by_line = {site.line: site for site in sites if site.verb == "signalReports.createRule"}+ picked = [site.generated_equivalent for site in by_line.values()]+ assert "signalsGroupingRulesCreate" in picked+ # A value the call site does not spell out leaves every candidate on the line.+ ambiguous = next(name for name in picked if name is not None and " | " in name)+ assert "signalsAssignmentRulesCreate" in ambiguous+ assert "signalsGroupingRulesCreate" in ambiguous++ # `values.rule.id` is not the selector - it's a plain object access - but its+ # dotted tokens ("rule", "id") match every candidate's shared "Rules" suffix and+ # used to turn a spelled-out literal selector ambiguous.+ def test_a_later_dotted_argument_does_not_dilute_the_selector(self, repo: Path) -> None:+ sites = codegen_call_sites(repo / "products/signals/frontend")+ picked = [site.generated_equivalent for site in sites if site.verb == "signalReports.createRule"]+ assert picked.count("signalsGroupingRulesCreate") == 1++ # An id hole and a rule-type hole both read as `{p}` in the mask. A static action+ # route sharing the id's position (`.../reorder/`) is a different operation, not+ # this one with an id, so it must not survive as a second candidate.+ def test_a_static_action_route_does_not_match_the_id_hole(self, repo: Path) -> None:+ sites = codegen_call_sites(repo / "products/signals/frontend")+ update = next(site for site in sites if site.verb == "signalReports.updateRule")+ assert update.generated_equivalent == "signalsAssignmentRulesPartialUpdate"+++class TestManualApiCalls:+ # Guards the blind spot: an owned namespace used to score as zero manual calls.+ def test_counts_owned_namespaces_and_skips_foreign_ones(self, repo: Path) -> None:+ # seven api.signalReports calls, one of them broken across lines, one nested+ # api.signalScout.runs.list, one api.get; api.comments belongs to platform_features+ assert count_manual_api_calls(repo / "products/signals/frontend") == 9++ def test_call_sites_mark_a_namespaced_call_as_covered(self, repo: Path) -> None:+ sites = codegen_call_sites(repo / "products/signals/frontend")+ assert sorted(site.verb for site in sites) == [+ "get",+ "signalReports.availableReviewers",+ "signalReports.createRule",+ "signalReports.createRule",+ "signalReports.list",+ "signalReports.setState",+ "signalReports.setState",+ "signalReports.updateRule",+ # A nested chain counts once, with its full member path.+ "signalScout.runs.list",+ ]+ covered = next(site for site in sites if site.verb == "signalReports.list")+ assert covered.namespaced+ assert covered.generated_equivalent == "signalsReportsList"+ # The client has no operation for this member, so it is a gap, not a twin.+ gap = next(site for site in sites if site.verb == "signalReports.availableReviewers")+ assert not gap.namespaced+ assert gap.generated_equivalent is None