: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): ratchet product paths in lib/api.ts against the generated clients (#104241)
Julian Bez91ea7181693b
diff --git a/.github/workflows/ci-python.yml b/.github/workflows/ci-python.ymlindex 721389d0bd1a..006878361dce 100644--- a/.github/workflows/ci-python.yml+++ b/.github/workflows/ci-python.yml@@ -65,6 +65,7 @@ jobs:query_perf: ${{ steps.filter.outputs.query_perf || 'true' }}stamphog: ${{ steps.filter.outputs.stamphog || 'true' }}bin_scripts: ${{ steps.filter.outputs.bin_scripts || 'true' }}+ api_ratchet: ${{ steps.filter.outputs.api_ratchet || 'true' }}steps:# For pull requests it's not necessary to checkout the code, but we# also want this to run on master so we need to checkout@@ -187,6 +188,16 @@ jobs:- 'pyproject.toml'- 'uv.lock'- .github/workflows/ci-python.yml+ # The lib/api.ts ratchet compares the hand-rolled URL builder with+ # the generated clients, so either side moving can create new debt.+ api_ratchet:+ - 'frontend/src/lib/api.ts'+ - 'frontend/src/lib/api-ratchet-baseline.txt'+ - 'frontend/src/generated/core/api.ts'+ - 'products/*/frontend/generated/api.ts'+ - 'tools/hogli-commands/hogli_commands/api_ratchet.py'+ - 'hogli.yaml'+ - .github/workflows/ci-python.ymlcode-quality:needs: changes@@ -481,11 +492,44 @@ jobs:if-no-files-found: ignorepath: junit-granian-shared-socket.xml+ api-ratchet:+ needs: changes+ # Its own filter output, so an api.ts-only pull request pays for this job+ # instead of the repo-wide code-quality one.+ if: needs.changes.outputs.api_ratchet == 'true' && github.event_name != 'push'+ name: lib/api.ts codegen ratchet+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0+ with:+ python-version-file: 'pyproject.toml'++ - name: Install uv+ uses: ./.github/actions/setup-uv++ - name: Install python dependencies+ run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev++ # Skip on unrebased branches: the command may not be registered yet.+ - name: Ratchet product paths in lib/api.ts+ run: |+ if [ ! -f tools/hogli-commands/hogli_commands/api_ratchet.py ]; then+ echo "hogli lint:api-ratchet not present on this branch yet — skipping (rebase to pick it up)"+ exit 0+ fi+ ./bin/hogli lint:api-ratchet+# Collate job - single required status check for branch protection.# The code-quality job skips when no Python changes, but this job always# runs and reports success, allowing PRs to merge.python_tests:- needs: [changes, code-quality]+ needs: [changes, code-quality, api-ratchet]name: Python code quality checksruns-on: ubuntu-24.04timeout-minutes: 5@@ -499,6 +543,13 @@ jobs:exit 1fi+ # Checked before the no-Python-changes exit below: the ratchet has its+ # own filter, so it can run on a pull request that touches no Python.+ if [[ "${{ needs.api-ratchet.result }}" != "success" && "${{ needs.api-ratchet.result }}" != "skipped" ]]; then+ echo "lib/api.ts codegen ratchet did not succeed (result: ${{ needs.api-ratchet.result }})."+ exit 1+ fi+# Pass if no Python changes detected (jobs were skipped)if [[ "${{ needs.changes.outputs.python }}" != "true" ]]; thenecho "Python checks were skipped (no relevant changes)"diff --git a/frontend/src/lib/api-ratchet-baseline.txt b/frontend/src/lib/api-ratchet-baseline.txtnew file mode 100644index 000000000000..5443d8edc068--- /dev/null+++ b/frontend/src/lib/api-ratchet-baseline.txt@@ -0,0 +1,256 @@+# ApiRequest path methods in frontend/src/lib/api.ts that a generated client+# already covers, each with the route it duplicates. Grandfathered debt: the+# ratchet fails on a redundant method and route pair that is NOT listed here.+#+# DO NOT EDIT BY HAND. Mechanical output of `hogli lint:api-ratchet+# --update-baseline`. Hand-added entries turn it back into an allowlist.+#+# To drop an entry: migrate the call sites onto the product's generated client+# (see .agents/skills/adopting-generated-api-types/SKILL.md), delete the path+# method and the namespace block, then regenerate this file.++accountsTableQuery projects/{}/accounts_table_query+actions projects/{}/actions+actionsDetail projects/{}/actions/{}+activityLog projects/{}/activity_log+aiObservabilityTranslate projects/{}/llm_analytics/translate+alert projects/{}/alerts/{}+alerts projects/{}/alerts+alerts projects/{}/alerts/{}+annotation projects/{}/annotations/{}+annotations projects/{}/annotations+batchExport projects/{}/batch_exports/{}+batchExportBackfill projects/{}/batch_exports/{}/backfills/{}+batchExportBackfills projects/{}/batch_exports/{}/backfills+batchExportRun projects/{}/batch_exports/{}/runs/{}+batchExportRuns projects/{}/batch_exports/{}/runs+batchExports projects/{}/batch_exports+cohorts projects/{}/cohorts+cohortsAddPersonsToStatic projects/{}/cohorts/{}/add_persons_to_static_cohort+cohortsCalculationHistory projects/{}/cohorts/{}/calculation_history+cohortsDetail projects/{}/cohorts/{}+cohortsDetailPersons projects/{}/cohorts/{}/persons+cohortsRemovePersonFromStatic projects/{}/cohorts/{}/remove_person_from_static_cohort+columnConfigurationDetail projects/{}/column_configurations/{}+columnConfigurations projects/{}/column_configurations+comment projects/{}/comments/{}+comments projects/{}/comments+conversation projects/{}/conversations/{}+conversations projects/{}/conversations+conversationsTicket projects/{}/conversations/tickets/{}+conversationsTickets projects/{}/conversations/tickets+copyOrganizationFeatureFlags organizations/{}/feature_flags/copy_flags+coreMemory projects/{}/core_memory+coreMemoryDetail projects/{}/core_memory/{}+customerJourneys projects/{}/customer_journeys+customerJourneysDetail projects/{}/customer_journeys/{}+customerProfileConfigs projects/{}/customer_profile_configs+customerProfileConfigsDetail projects/{}/customer_profile_configs/{}+dashboardCollaborators projects/{}/dashboards/{}/collaborators+dashboardCollaboratorsDetail projects/{}/dashboards/{}/collaborators/{}+dashboardSharing projects/{}/dashboards/{}/sharing+dashboardSharingPassword projects/{}/dashboards/{}/sharing/passwords/{}+dashboardSharingPasswords projects/{}/dashboards/{}/sharing/passwords+dashboardTemplateSchema projects/{}/dashboard_templates/json_schema+dashboardTemplates projects/{}/dashboard_templates+dashboardTemplatesCopyBetweenProjects projects/{}/dashboard_templates/copy_between_projects+dashboardTemplatesDetail projects/{}/dashboard_templates/{}+dashboards projects/{}/dashboards+dashboardsDetail projects/{}/dashboards/{}+dataColorTheme projects/{}/data_color_themes/{}+dataColorThemes projects/{}/data_color_themes+dataModelingEdges projects/{}/data_modeling_edges+dataModelingJobsRecent projects/{}/data_modeling_jobs/recent+dataModelingJobsRunning projects/{}/data_modeling_jobs/running+dataModelingNode projects/{}/data_modeling_nodes/{}+dataModelingNodes projects/{}/data_modeling_nodes+dataWarehouseDataModelingJobs projects/{}/data_modeling_jobs+dataWarehouseManagedViewset projects/{}/managed_viewsets/{}+dataWarehouseSavedQueries projects/{}/warehouse_saved_queries+dataWarehouseSavedQuery projects/{}/warehouse_saved_queries/{}+dataWarehouseSavedQueryActivity projects/{}/warehouse_saved_queries/{}/activity+dataWarehouseSavedQueryDraft projects/{}/warehouse_saved_query_drafts/{}+dataWarehouseSavedQueryDrafts projects/{}/warehouse_saved_query_drafts+dataWarehouseSavedQueryFolder projects/{}/warehouse_saved_query_folders/{}+dataWarehouseSavedQueryFolders projects/{}/warehouse_saved_query_folders+dataWarehouseTable projects/{}/warehouse_tables/{}+dataWarehouseTables projects/{}/warehouse_tables+dataWarehouseViewLink projects/{}/warehouse_view_link/{}+dataWarehouseViewLinks projects/{}/warehouse_view_link+earlyAccessFeature projects/{}/early_access_feature/{}+earlyAccessFeatures projects/{}/early_access_feature+endpoint projects/{}/endpoints+endpointDetail projects/{}/endpoints/{}+errorTrackingAssignIssue projects/{}/error_tracking/issues/{}/assign+errorTrackingExternalReference projects/{}/error_tracking/external_references+errorTrackingIssue projects/{}/error_tracking/issues/{}+errorTrackingIssueBulk projects/{}/error_tracking/issues/bulk+errorTrackingIssueCohort projects/{}/error_tracking/issues/{}/cohort+errorTrackingIssueFingerprints projects/{}/error_tracking/fingerprints+errorTrackingIssueMerge projects/{}/error_tracking/issues/{}/merge+errorTrackingIssueSplit projects/{}/error_tracking/issues/{}/split+errorTrackingIssues projects/{}/error_tracking/issues+errorTrackingIssuesExists projects/{}/error_tracking/issues/exists+errorTrackingRecommendations projects/{}/error_tracking/recommendations+errorTrackingRelease projects/{}/error_tracking/releases/{}+errorTrackingReleases projects/{}/error_tracking/releases+errorTrackingSpikeDetectionConfig projects/{}/error_tracking/spike_detection_config+errorTrackingSpikeEvents projects/{}/error_tracking/spike_events+errorTrackingStackFrames projects/{}/error_tracking/stack_frames/batch_get+errorTrackingSymbolSet projects/{}/error_tracking/symbol_sets/{}+errorTrackingSymbolSets projects/{}/error_tracking/symbol_sets+evaluationRuns projects/{}/evaluation_runs+eventDefinitionDetail projects/{}/event_definitions/{}+eventDefinitions projects/{}/event_definitions+experimentCreateExposureCohort projects/{}/experiments/{}/create_exposure_cohort_for_experiment+experiments projects/{}/experiments+experimentsDetail projects/{}/experiments/{}+export projects/{}/exports/{}+exports projects/{}/exports+externalDataSchemas projects/{}/external_data_schemas+externalDataSource projects/{}/external_data_sources/{}+externalDataSourceRevenueAnalyticsConfig projects/{}/external_data_sources/{}/revenue_analytics_config+externalDataSourceSchema projects/{}/external_data_schemas/{}+externalDataSources projects/{}/external_data_sources+featureFlag projects/{}/feature_flags/{}+featureFlagCreateScheduledChange projects/{}/scheduled_changes+featureFlagCreateStaticCohort projects/{}/feature_flags/{}/create_static_cohort_for_flag+featureFlagDeleteScheduledChange projects/{}/scheduled_changes/{}+featureFlagScheduledChange projects/{}/scheduled_changes/{}+featureFlagScheduledChanges projects/{}/scheduled_changes+featureFlags projects/{}/feature_flags+featureFlagsActivity projects/{}/feature_flags/activity+featureFlagsActivity projects/{}/feature_flags/{}/activity+fileSystem projects/{}/file_system+fileSystemCount projects/{}/file_system/{}/count+fileSystemDetail projects/{}/file_system/{}+fileSystemLink projects/{}/file_system/{}/link+fileSystemLogView projects/{}/file_system/log_view+fileSystemMove projects/{}/file_system/{}/move+fileSystemShortcut projects/{}/file_system_shortcut+fileSystemShortcutDetail projects/{}/file_system_shortcut/{}+fileSystemShortcutReorder projects/{}/file_system_shortcut/reorder+fileSystemUndoDelete projects/{}/file_system/undo_delete+fileSystemUnfiled projects/{}/file_system/unfiled+fixHogQLErrors projects/{}/fix_hogql+group projects/{}/groups+groupActivity projects/{}/groups/activity+groups projects/{}/groups+heatmapScreenshotSaved projects/{}/saved/{}+heatmapScreenshotsSaved projects/{}/saved+hogFlow projects/{}/hog_flows/{}+hogFlowTemplate projects/{}/hog_flow_templates/{}+hogFlowTemplates projects/{}/hog_flow_templates+hogFlows projects/{}/hog_flows+hogFunction projects/{}/hog_functions/{}+hogFunctionTemplate projects/{}/hog_function_templates/{}+hogFunctionTemplates projects/{}/hog_function_templates+hogFunctions projects/{}/hog_functions+insight projects/{}/insights/{}+insightSharing projects/{}/insights/{}/sharing+insightSharingPassword projects/{}/insights/{}/sharing/passwords/{}+insightSharingPasswords projects/{}/insights/{}/sharing/passwords+insightVariable projects/{}/insight_variables/{}+insightVariables projects/{}/insight_variables+insights projects/{}/insights+insightsActivity projects/{}/insights/activity+insightsCancel projects/{}/insights/cancel+integration projects/{}/integrations/{}+integrationClickUpLists projects/{}/integrations/{}/clickup_lists+integrationClickUpSpaces projects/{}/integrations/{}/clickup_spaces+integrationClickUpWorkspaces projects/{}/integrations/{}/clickup_workspaces+integrationEmail projects/{}/integrations/{}/email+integrationEmailVerify projects/{}/integrations/{}/email/verify+integrationGitHubBranches projects/{}/integrations/{}/github_branches+integrationGitHubRepositories projects/{}/integrations/{}/github_repos+integrationGoogleAdsAccounts projects/{}/integrations/{}/google_accessible_accounts+integrationGoogleAdsConversionActions projects/{}/integrations/{}/google_conversion_actions+integrationJiraProjects projects/{}/integrations/{}/jira_projects+integrationLinearTeams projects/{}/integrations/{}/linear_teams+integrationLinkedInAdsAccounts projects/{}/integrations/{}/linkedin_ads_accounts+integrationLinkedInAdsConversionRules projects/{}/integrations/{}/linkedin_ads_conversion_rules+integrationSlackChannels projects/{}/integrations/{}/channels+integrationSlackChannelsById projects/{}/integrations/{}/channels+integrationTwilioPhoneNumbers projects/{}/integrations/{}/twilio_phone_numbers+integrations projects/{}/integrations+integrationsDomainConnectApplyUrl projects/{}/integrations/domain-connect/apply-url+integrationsDomainConnectCheck projects/{}/integrations/domain-connect/check+link projects/{}/links/{}+links projects/{}/links+logsExplainWithAI projects/{}/logs/explainLogWithAI+logsExport projects/{}/logs/export+logsHasLogs projects/{}/logs/has_logs+logsQuery projects/{}/logs/query+logsSparkline projects/{}/logs/sparkline+media projects/{}/uploaded_media+messagingCategories projects/{}/messaging_categories+messagingCategoriesImportFromCustomerIO projects/{}/messaging_categories/import_from_customerio+messagingCategoriesOptOutSyncConfig projects/{}/messaging_categories/optout_sync_config+messagingCategoriesRemoveCustomerIOAppConfig projects/{}/messaging_categories/remove_customerio_app_config+messagingCategoriesRemoveTrackConfig projects/{}/messaging_categories/remove_track_config+messagingCategoriesRemoveWebhookConfig projects/{}/messaging_categories/remove_webhook_config+messagingCategoriesSaveTrackConfig projects/{}/messaging_categories/save_track_config+messagingCategoriesSaveWebhookConfig projects/{}/messaging_categories/save_webhook_config+messagingCategory projects/{}/messaging_categories/{}+messagingPreferencesBulkAddOptOuts projects/{}/messaging_preferences/bulk_add_opt_outs+messagingPreferencesExportOptOutsCsv projects/{}/messaging_preferences/export_opt_outs_csv+messagingPreferencesLink projects/{}/messaging_preferences/generate_link+messagingTemplate projects/{}/messaging_templates/{}+messagingTemplates projects/{}/messaging_templates+notebook projects/{}/notebooks/{}+notebookSharing projects/{}/notebooks/{}/sharing+notebookSharingPassword projects/{}/notebooks/{}/sharing/passwords/{}+notebookSharingPasswords projects/{}/notebooks/{}/sharing/passwords+notebooks projects/{}/notebooks+organizationFeatureFlagKeys organizations/{}/feature_flags/keys+organizationFeatureFlags organizations/{}/feature_flags/{}+organizationMember organizations/{}/members/{}+organizationMemberScopedApiKeys organizations/{}/members/{}/scoped_api_keys+organizationMembers organizations/{}/members+organizationOAuthApplications organizations/{}/oauth_applications+person projects/{}/persons/{}+personActivity projects/{}/persons/activity+personActivity projects/{}/persons/{}/activity+persons projects/{}/persons+productTour projects/{}/product_tours/{}+productTours projects/{}/product_tours+projectSecretApiKey projects/{}/project_secret_api_keys/{}+projectSecretApiKeys projects/{}/project_secret_api_keys+propertyDefinitionDetail projects/{}/property_definitions/{}+propertyDefinitionSeenTogether projects/{}/property_definitions/seen_together+propertyDefinitions projects/{}/property_definitions+queryTabState projects/{}/query_tab_state+queryTabStateDetail projects/{}/query_tab_state/{}+queryTabStateUser projects/{}/query_tab_state/user+recording projects/{}/session_recordings/{}+recordingPlaylist projects/{}/session_recording_playlists/{}+recordingPlaylists projects/{}/session_recording_playlists+recordingSharing projects/{}/session_recordings/{}/sharing+recordingSharingPassword projects/{}/session_recordings/{}/sharing/passwords/{}+recordingSharingPasswords projects/{}/session_recordings/{}/sharing/passwords+recordings projects/{}/session_recordings+revenueAnalyticsJoins projects/{}/revenue_analytics/joins+roleMemberships organizations/{}/roles/{}/role_memberships+roleMembershipsDetail organizations/{}/roles/{}/role_memberships/{}+roles organizations/{}/roles+rolesDetail organizations/{}/roles/{}+signalReport projects/{}/signals/reports/{}+signalReports projects/{}/signals/reports+signalSourceConfig projects/{}/signals/source_configs/{}+signalSourceConfigs projects/{}/signals/source_configs+subscription projects/{}/subscriptions/{}+subscriptions projects/{}/subscriptions+survey projects/{}/surveys/{}+surveyActivity projects/{}/surveys/activity+surveyActivity projects/{}/surveys/{}/activity+surveys projects/{}/surveys+surveysResponsesCount projects/{}/surveys/responses_count+task projects/{}/tasks/{}+taskRun projects/{}/tasks/{}/runs/{}+taskRuns projects/{}/tasks/{}/runs+tasks projects/{}/tasks+userInterview projects/{}/user_interviews/{}+userInterviews projects/{}/user_interviews+users users+webAnalyticsFilterPreset projects/{}/web_analytics_filter_presets/{}+webAnalyticsFilterPresets projects/{}/web_analytics_filter_presetsdiff --git a/hogli.yaml b/hogli.yamlindex 5a927224e7b3..9b1f8494e9de 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -898,6 +898,9 @@ quality:lint:size:click: hogli_commands.size_lint:cmd_lint_sizedescription: Check the size of changed Python/TypeScript files (warn-only, crossing 1000 lines)+ lint:api-ratchet:+ click: hogli_commands.api_ratchet:cmd_lint_api_ratchet+ description: Block new frontend/src/lib/api.ts path methods that a generated client already coverslint:workflows:click: hogli_commands.workflow_lint.cli:cmd_lint_workflowsdescription: Lint .github/workflows/** for repo conventionsdiff --git a/tools/hogli-commands/hogli_commands/api_ratchet.py b/tools/hogli-commands/hogli_commands/api_ratchet.pynew file mode 100644index 000000000000..5b785c9cfc1b--- /dev/null+++ b/tools/hogli-commands/hogli_commands/api_ratchet.py@@ -0,0 +1,779 @@+"""Ratchet on the product-specific path methods in ``frontend/src/lib/api.ts``.++``ApiRequest`` is one class holding every URL in the app, so adding an endpoint+means editing a core file, and the namespace on the ``api`` singleton is one line+further. Products keep doing that even when their Orval client already has the+same endpoint, which puts a single product's URLs and response types in core.++The check is mechanical: resolve the URL each ``ApiRequest`` path method builds,+and compare it with every template the generated clients emit. A match means a+generated twin already exists, so the hand-rolled method is redundant. No+ownership judgment and no allowlist - the generated output decides.++The unit is the path, not the operation. A path method carries no HTTP verb, since+the verb lives on the ``api`` namespace that calls it, so a match says the route is+generated and not that every operation on it is. The namespace side of that is+resolved per member in ``product/ts_helpers.py``, which checks the verb too.++Existing redundancy is grandfathered in a baseline file. The command fails only+on a redundant method that is not in the baseline, which is the case that would+add new debt. A shrinking baseline is the migration's progress metric.++ hogli lint:api-ratchet # check against the baseline+ hogli lint:api-ratchet --prune-baseline # drop stale entries, never add one+ hogli 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 --json # full report as JSON++``ApiRequest`` builds ``/api/environments/{team_id}/...``, Orval emits+``/api/projects/{project_id}/...``. Those are the same Django routes - the+environments path is a backward-compat alias that codegen skips - so both sides+are normalized onto ``projects`` before comparison.+"""++from __future__ import annotations++import re+import json+from dataclasses import dataclass+from pathlib import Path+from typing import Final++import click+from hogli.manifest import REPO_ROOT++from posthog.dataclasses import frozen++API_TS: Final = Path("frontend/src/lib/api.ts")+CORE_GENERATED: Final = Path("frontend/src/generated/core/api.ts")+PRODUCT_GENERATED_GLOB: Final = "products/*/frontend/generated/api.ts"++# Stands in for a product in the owner set of a template only the core client emits.+# A core twin is coverage: frontend/src/generated/core/api.ts exists for the endpoints+# no single product owns, so a hand-rolled path method beside one is still redundant.+# It never matches a product directory name, so no product owns such a namespace.+CORE_OWNER: Final = "core"++# The scoping prefixes a path method starts from. They are plumbing, not endpoints, so a+# method that resolves to one of them is not a duplicate of anything. Every other short+# template is fair game: the generated clients really do emit /api/billing/activate/.+PLUMBING_TEMPLATES: Final = frozenset({("projects",), ("projects", "{}"), ("organizations",), ("organizations", "{}")})++# 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")++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+# ratchet fails on a redundant method and route pair that is NOT listed here.+#+# DO NOT EDIT BY HAND. Mechanical output of `hogli lint:api-ratchet+# --update-baseline`. Hand-added entries turn it back into an allowlist.+#+# To drop an entry: migrate the call sites onto the product's generated client+# (see .agents/skills/adopting-generated-api-types/SKILL.md), delete the path+# method and the namespace block, then regenerate this file.+"""++# The chain builders a path method composes its URL from.+_COMPONENT_CALLS: Final = frozenset({"addPathComponent", "addEncodedPathComponent", "withAction"})++# Chain roots that resolve to a literal prefix rather than to another method.+_ROOT_PREFIXES: Final[dict[str, tuple[str, ...]]] = {+ "projects": ("projects",),+ "projectsDetail": ("projects", "{}"),+ "environments": ("environments",),+ "environmentsDetail": ("environments", "{}"),+ "organizations": ("organizations",),+ "organizationsDetail": ("organizations", "{}"),+}++# TypeScript class members are public by default, so a method needs an explicit+# `private`/`protected`/`static` modifier to be unreachable from the `api` singleton.+_METHOD_START: Final = re.compile(r"^ (?!private |protected |static )(?:public )?(\w+)\(")+_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+): \{")+_MEMBER_CALL: Final = re.compile(r"\.(\w+)\(")+_GENERATED_URL: Final = re.compile(r"`(/api/[^`]*)`")+_TEMPLATE_HOLE: Final = re.compile(r"\$\{[^}]*\}")+++def _read_call_argument(text: str, open_paren: int) -> str:+ """Return the argument text of the call whose ``(`` sits at ``open_paren``."""+ depth = 0+ for index in range(open_paren, len(text)):+ char = text[index]+ if char == "(":+ depth += 1+ elif char == ")":+ depth -= 1+ if depth == 0:+ return text[open_paren + 1 : index]+ return text[open_paren + 1 :]+++def _split_top_level_args(text: str) -> list[str]:+ """Split a call's argument text on its top-level commas."""+ if not text.strip():+ return []+ args: list[str] = []+ depth = 0+ quote = ""+ start = 0+ for index, char in enumerate(text):+ if quote:+ quote = "" if char == quote else quote+ continue+ if char in "\"'`":+ quote = char+ elif char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ elif char == "," and depth == 0:+ args.append(text[start:index])+ start = index + 1+ args.append(text[start:])+ return args+++def _signature_params(signature: str) -> list[tuple[str, bool]]:+ """A method signature's parameters, in order, each with whether it is optional."""+ match = re.search(r"\((.*)\)\s*:\s*ApiRequest\s*\{", signature, re.S)+ if match is None:+ return []+ params = []+ for arg in _split_top_level_args(match.group(1)):+ name = arg.strip().split(":", 1)[0].strip()+ if not name:+ continue+ optional = name.endswith("?")+ params.append((name.rstrip("?").strip(), optional))+ return params+++def _argument_segments(argument: str) -> tuple[str, ...]:+ """Path segments an argument contributes.++ A quoted string can pack several segments, and a template literal can mix them+ with interpolations: ``addPathComponent(`${issueId}/similar_issues`)`` is the+ detail route plus a literal action, not one opaque hole.+ """+ stripped = argument.strip()+ quoted = re.fullmatch(r"""(['"`])(.*)\1""", stripped, re.S)+ if quoted is None:+ return ("{}",)+ return tuple("{}" if "${" in part else part for part in quoted.group(2).split("/") if part)+++@dataclass(frozen=True)+class RedundantMethod:+ """A path method and one generated route it duplicates."""++ name: str+ template: tuple[str, ...]+ products: frozenset[str]++ @property+ def entry(self) -> str:+ """The baseline line for this pair."""+ return f"{self.name} {'/'.join(self.template)}"+++@dataclass(frozen=True)+class ReturnStatement:+ """One ``return`` of a path method, with the statements that run before it.++ ``guard`` is the single-variable ``if`` this return sits inside, or falls through+ from - ``(param, True)`` when the branch runs while ``param`` is truthy, ``(param,+ False)`` while it is falsy. ``None`` covers everything else: an unconditional+ return, an ``else``, a compound condition - anywhere a delegating call can't prove+ which branch runs, so every branch stays reachable.+ """++ setup: str+ statement: str+ guard: tuple[str, bool] | None = None+++# A plain `if (x) {` or `if (!x) {` on its own line - anything more, an `else` or a+# compound condition, is left unrecognized and leaves the branch's guard as None.+_IF_GUARD: Final = re.compile(r"^\s*if \((!?)(\w+)\)\s*\{\s*$")+++def _block_paths(lines: list[str]) -> tuple[list[tuple[int, ...]], dict[int, int]]:+ """For each line, the ids of the brace blocks open at it, outermost first,+ plus the line that opened each block id."""+ paths: list[tuple[int, ...]] = []+ opened_at: dict[int, int] = {}+ stack: list[int] = []+ opened = 0+ for line_index, line in enumerate(lines):+ paths.append(tuple(stack))+ for char in line:+ if char == "{":+ opened += 1+ stack.append(opened)+ opened_at[opened] = line_index+ elif char == "}" and stack:+ stack.pop()+ return paths, opened_at+++def _blocks_with_return(lines: list[str], paths: list[tuple[int, ...]]) -> frozenset[int]:+ """Block ids that contain a ``return``, directly or in a block nested inside them."""+ has_return: set[int] = set()+ for index, line in enumerate(lines):+ if _RETURN_LINE.match(line):+ has_return.update(paths[index])+ return frozenset(has_return)+++@frozen+class SameLevelIfGuard:+ """A same-level if-block found before a return, and the variable it guards on."""++ block_id: int+ name: str+ negated: bool+++def _nearest_same_level_if(+ lines: list[str], paths: list[tuple[int, ...]], opened_at: dict[int, int], index: int+) -> SameLevelIfGuard | None:+ """The nearest same-level closed if-block before ``index``."""+ level = paths[index]+ for position in range(index - 1, -1, -1):+ if paths[position] != level:+ continue+ if not lines[position].strip():+ continue # a blank line between the closed block and here proves nothing+ match = _IF_GUARD.match(lines[position])+ if match is None:+ return None+ negated, name = match.groups()+ block_id = next((bid for bid, opened_line in opened_at.items() if opened_line == position), None)+ if block_id is None:+ return None+ return SameLevelIfGuard(block_id=block_id, name=name, negated=bool(negated))+ return None+++def _fallthrough_guard(+ lines: list[str], paths: list[tuple[int, ...]], opened_at: dict[int, int], index: int, has_return: frozenset[int]+) -> tuple[str, bool] | None:+ """The guard on the nearest same-level if this return falls through from.++ Only applies when that if returns on its own: reaching past it then proves the+ condition was false. An if that only mutates and falls through leaves this return+ reachable either way, so it carries no guard here - ``_optional_mutation`` covers it.+ """+ found = _nearest_same_level_if(lines, paths, opened_at, index)+ if found is None:+ return None+ if found.block_id not in has_return:+ return None+ return (found.name, found.negated)+++def _return_guard(+ lines: list[str], paths: list[tuple[int, ...]], opened_at: dict[int, int], index: int, has_return: frozenset[int]+) -> tuple[str, bool] | None:+ """The single-variable ``if`` this return runs inside, or falls through from."""+ if paths[index]:+ header = lines[opened_at[paths[index][-1]]]+ match = _IF_GUARD.match(header)+ if match is None:+ return None+ negated, name = match.groups()+ return (name, not bool(negated))+ return _fallthrough_guard(lines, paths, opened_at, index, has_return)+++def _optional_mutation(+ lines: list[str], paths: list[tuple[int, ...]], opened_at: dict[int, int], index: int, has_return: frozenset[int]+) -> tuple[tuple[str, bool], list[str]] | None:+ """The mutation-only if-block this return might have fallen through, if any.++ An if that never returns on its own leaves the return after it reachable whether+ or not the block ran, so its mutation belongs in an extra, guarded copy of that+ return - dropping it entirely resolves the method to the untouched route only,+ and applying it unconditionally resolves it to the mutated route only.+ """+ found = _nearest_same_level_if(lines, paths, opened_at, index)+ if found is None:+ return None+ if found.block_id in has_return:+ return None+ block_lines = [line for position, line in enumerate(lines) if found.block_id in paths[position]]+ return (found.name, not found.negated), block_lines+++def _split_returns(body: str) -> list[ReturnStatement]:+ """Split a method body into one ReturnStatement per ``return``.++ A return's setup is the statements it actually runs after: those in its own block+ and in the blocks enclosing it, never those in a branch it never entered. A+ conditional that mutates the chain before returning inside the `if` must not reach+ the return below the block, or the method resolves to the conditional route only.+ A conditional that mutates and falls through - no return of its own - reaches the+ return below either way, so that return gets two copies here: one with the+ mutation, one without, each guarded on whether the block ran.+ """+ lines = body.splitlines()+ paths, opened_at = _block_paths(lines)+ has_return = _blocks_with_return(lines, paths)+ returns: list[ReturnStatement] = []+ for index, line in enumerate(lines):+ if not _RETURN_LINE.match(line):+ continue+ setup = [+ earlier+ for position, earlier in enumerate(lines[:index])+ if paths[position] == paths[index][: len(paths[position])] and not _RETURN_LINE.match(earlier)+ ]+ statement = _return_expression("\n".join(lines[index:]))+ guard = _return_guard(lines, paths, opened_at, index, has_return)+ optional = _optional_mutation(lines, paths, opened_at, index, has_return) if guard is None else None+ if optional is None:+ returns.append(ReturnStatement(setup="\n".join(setup), statement=statement, guard=guard))+ continue+ mutated_guard, block_lines = optional+ name, mutated = mutated_guard+ returns.append(ReturnStatement(setup="\n".join(setup), statement=statement, guard=(name, not mutated)))+ returns.append(ReturnStatement(setup="\n".join(setup + block_lines), statement=statement, guard=mutated_guard))+ return returns or [ReturnStatement(setup="", statement=body)]+++def _ternary_branches(expression: str) -> list[str]:+ """The branches of a ternary, or the expression itself when there is no ternary.++ A ternary return builds two different URLs, and reading the calls of both branches+ as one chain produces a template that neither branch builds.+ """+ depth = 0+ quote = ""+ question = -1+ for index, char in enumerate(expression):+ if quote:+ quote = "" if char == quote else quote+ continue+ if char in "\"'`":+ quote = char+ elif char in "([{":+ depth += 1+ elif char in ")]}":+ depth -= 1+ elif depth != 0:+ continue+ elif char == "?" and question < 0 and expression[index + 1 : index + 2] not in {".", "?"}:+ question = index+ elif char == ":" and question >= 0:+ return [expression[question + 1 : index], expression[index + 1 :]]+ return [expression]+++def _return_expression(chunk: str) -> str:+ """The returned expression alone, without the statements that follow it.++ A chain or a ternary can span lines, so a continuation line is one that opens the+ expression further, starts with the next call in the chain, or starts with a+ ternary arm.+ """+ lines = chunk.splitlines(keepends=True)+ taken = [lines[0]]+ for line in lines[1:]:+ text = "".join(taken)+ if text.count("(") > text.count(")") or line.lstrip().startswith((".", "?", ":")):+ taken.append(line)+ continue+ break+ return "".join(taken)+++def _after_base(text: str, base: re.Match[str]) -> str:+ """The chain text after its root call.++ A root that is itself a component builder, `this.addPathComponent('projects')`,+ keeps its own argument, so the scan starts before it rather than after it.+ """+ return text if base.group(1) in _COMPONENT_CALLS else text[base.end() :]+++def normalize_template(segments: tuple[str, ...]) -> tuple[str, ...]:+ """Drop the query string, put the environments alias on projects, @current on a hole."""+ kept = tuple("{}" if segment == "@current" else segment for segment in segments if not segment.startswith("?"))+ if kept[:1] == ("environments",):+ return ("projects", *kept[1:])+ return kept+++class ApiRequestResolver:+ """Resolves each ``ApiRequest`` path method to the URL templates it builds.++ A method can build more than one URL - ``alerts()`` branches on whether an+ alert id was passed - so each ``return`` statement is resolved on its own,+ against everything the body built before it. Resolving the return statement+ alone loses the chain root of the methods that assign it to a local first+ (``const apiRequest = this.environmentsDetail(teamId)...``).+ """++ def __init__(self, source: str) -> None:+ self._returns: dict[str, list[ReturnStatement]] = {}+ self._signatures: dict[str, str] = {}+ self._cache: dict[str, tuple[tuple[str, ...], ...]] = {}+ self._parse(source)++ def _parse(self, source: str) -> None:+ """Collect the return-statement chunks of every method returning an ApiRequest."""+ lines = source.splitlines()+ index = 0+ while index < len(lines):+ match = _METHOD_START.match(lines[index])+ if match is None:+ index += 1+ continue+ signature: list[str] = []+ while index < len(lines) and not lines[index].rstrip().endswith("{"):+ signature.append(lines[index])+ index += 1+ if index < len(lines):+ signature.append(lines[index])+ index += 1+ body: list[str] = []+ while index < len(lines) and lines[index] != " }":+ body.append(lines[index])+ index += 1+ signature_text = " ".join(signature)+ if "): ApiRequest {" not in signature_text:+ continue # a verb (get/create/...), not a path method+ text = "\n".join(body)+ self._returns[match.group(1)] = _split_returns(text)+ self._signatures[match.group(1)] = signature_text++ def method_names(self) -> frozenset[str]:+ return frozenset(self._returns)++ def templates(self, name: str) -> tuple[tuple[str, ...], ...]:+ """Every URL template ``name`` can build, as segment tuples, empty if unresolvable."""+ if name in self._cache:+ return self._cache[name]+ self._cache[name] = () # cycle guard for the recursive resolve below+ resolved: list[tuple[str, ...]] = []+ for statement in self._returns.get(name, []):+ resolved.extend(self._resolve_return(statement, name))+ self._cache[name] = tuple(dict.fromkeys(resolved))+ return self._cache[name]++ def _resolve_return(self, statement: ReturnStatement, owner: str) -> list[tuple[str, ...]]:+ """Every template one return can build, across its ternary and base branches."""+ branches = _ternary_branches(statement.statement)+ if len(branches) > 1:+ resolved: list[tuple[str, ...]] = []+ for branch in branches:+ resolved.extend(self._resolve_return(ReturnStatement(setup=statement.setup, statement=branch), owner))+ return resolved+ return self._resolve_chain(statement, owner)++ def _resolve_chain(self, statement: ReturnStatement, owner: str) -> list[tuple[str, ...]]:+ base = _CHAIN_BASE.search(statement.statement)+ if base is not None:+ args = _split_top_level_args(_read_call_argument(statement.statement, base.end() - 1))+ prefixes = self._base_prefixes(base.group(1), args, owner)+ tail = self._appended_segments(_after_base(statement.statement, base))+ return [(*prefix, *tail) for prefix in prefixes]+ # The return continues a chain the setup built into a local, so the root and+ # the components before the return both come from the setup.+ base = _CHAIN_BASE.search(statement.setup)+ if base is None:+ return []+ args = _split_top_level_args(_read_call_argument(statement.setup, base.end() - 1))+ prefixes = self._base_prefixes(base.group(1), args, owner)+ tail = self._appended_segments(_after_base(statement.setup, base)) + self._appended_segments(+ statement.statement+ )+ return [(*prefix, *tail) for prefix in prefixes]++ def _base_prefixes(self, name: str, args: list[str], owner: str) -> list[tuple[str, ...]]:+ """Every prefix the chain root can stand for. A branching root has several.++ ``args`` are the arguments this particular call site passed to ``name``, and+ ``owner`` is the method making the call. Together they can rule out a branch+ the caller's own arguments can never reach - see ``_reachable_returns``.+ """+ if name in _COMPONENT_CALLS:+ return [()] # the chain starts on `this` itself, e.g. this.addPathComponent('projects')+ if name in _ROOT_PREFIXES:+ return [_ROOT_PREFIXES[name]]+ statements = self._returns.get(name)+ if not statements:+ return []+ reachable = self._reachable_returns(name, statements, args, owner)+ if reachable == statements:+ return list(self.templates(name)) # no filtering applies - reuse the cached, cycle-safe result+ resolved: list[tuple[str, ...]] = []+ for statement in reachable:+ resolved.extend(self._resolve_return(statement, name))+ return list(dict.fromkeys(resolved))++ def _reachable_returns(+ self, name: str, statements: list[ReturnStatement], args: list[str], owner: str+ ) -> list[ReturnStatement]:+ """Which of ``name``'s branches this call site can reach, given its arguments.++ A branch guarded by ``if (<param>)`` is unreachable when the call passes+ nothing for that parameter, and unreachable in reverse when the call passes a+ value the caller's own signature proves is always there - one of its own+ required parameters, forwarded as-is. Anything else - an optional parameter+ forwarded, a computed expression - can't be proven either way, so every+ branch stays reachable.+ """+ guards = [statement.guard for statement in statements if statement.guard is not None]+ if not guards:+ return statements+ param_name = guards[0][0] # every guard on one method names the same parameter+ params = _signature_params(self._signatures.get(name, ""))+ index = next((i for i, (pname, _optional) in enumerate(params) if pname == param_name), None)+ if index is None:+ return statements+ if index >= len(args) or not args[index].strip():+ return [statement for statement in statements if statement.guard != (param_name, True)]+ passed = args[index].strip()+ if not passed.isidentifier():+ return statements+ owner_optional = dict(_signature_params(self._signatures.get(owner, ""))).get(passed)+ if owner_optional is False:+ return [statement for statement in statements if statement.guard != (param_name, False)]+ return statements++ def _appended_segments(self, text: str, seen: frozenset[str] = frozenset()) -> tuple[str, ...]:+ """The segments a chain appends, expanding the path helpers it calls.++ A chain can pass through another path method: `organizations().current()`+ appends `@current` through `current()`, and reading only the component+ builders drops it.+ """+ segments: list[str] = []+ for call in _CHAINED_CALL.finditer(text):+ name = call.group(1)+ if name in _COMPONENT_CALLS:+ segments.extend(_argument_segments(_read_call_argument(text, call.end() - 1)))+ elif name in self._returns and name not in seen:+ segments.extend(self._helper_appends(name, seen | {name}))+ return tuple(segments)++ def _helper_appends(self, name: str, seen: frozenset[str]) -> tuple[str, ...]:+ """What a path method appends when it is chained onto an existing request."""+ statements = self._returns.get(name, [])+ if not statements:+ return ()+ statement = statements[0]+ base = _CHAIN_BASE.search(statement.statement)+ body = _after_base(statement.statement, base) if base is not None else statement.statement+ return self._appended_segments(body, seen)+++class GeneratedTemplates:+ """Every URL template the generated clients emit, with the products emitting it.++ ``product/ts_helpers.py`` parses the same files into a different shape+ (``{p}`` holes, keyed by URL and HTTP method) because it matches a call site+ that carries a verb. Here the verb lives on the namespace, not on the path+ method, so the key is the path alone.+ """++ def __init__(self, repo_root: Path) -> None:+ self.owners: dict[tuple[str, ...], frozenset[str]] = {}+ for path in sorted(repo_root.glob(PRODUCT_GENERATED_GLOB)):+ self._collect(path, path.relative_to(repo_root).parts[1])+ core = repo_root / CORE_GENERATED+ if core.exists():+ self._collect(core, CORE_OWNER)++ def _collect(self, path: Path, owner: str) -> None:+ for url in _GENERATED_URL.findall(path.read_text()):+ raw = tuple(_TEMPLATE_HOLE.sub("{}", url).strip("/").split("/")[1:])+ template = normalize_template(raw)+ if not template:+ continue+ self.owners[template] = self.owners.get(template, frozenset()) | {owner}++ def products_covering(self, template: tuple[str, ...]) -> frozenset[str]:+ """Owners whose generated client emits exactly ``template``, CORE_OWNER included.++ Prefix matching would also fire on a shorter URL that merely sits above a+ generated route (``file_system`` above ``file_system/{}/link``), and those+ are different endpoints, so the match has to be exact.+ """+ return self.owners.get(template, frozenset())+++class Ratchet:+ """The report: which path methods are redundant, and which namespaces use them."""++ def __init__(self, repo_root: Path) -> None:+ self._source = (repo_root / API_TS).read_text()+ self._resolver = ApiRequestResolver(self._source)+ self._generated = GeneratedTemplates(repo_root)+ # Every branch of a method that matches, not only the first: a method that+ # builds both a collection and a detail route duplicates two generated routes,+ # and grandfathering one of them would leave the other unguarded.+ self.redundant: list[RedundantMethod] = []+ for name in sorted(self._resolver.method_names()):+ for template in self._resolver.templates(name):+ normalized = normalize_template(template)+ if normalized in PLUMBING_TEMPLATES:+ continue+ products = self._generated.products_covering(normalized)+ if products:+ self.redundant.append(RedundantMethod(name=name, template=normalized, products=products))++ def products_by_method(self) -> dict[str, frozenset[str]]:+ """The products covering each redundant method, across all of its routes."""+ products: dict[str, frozenset[str]] = {}+ for entry in self.redundant:+ products[entry.name] = products.get(entry.name, frozenset()) | entry.products+ return products++ def namespaces(self) -> dict[str, frozenset[str]]:+ """Namespaces on the ``api`` singleton that call a redundant path method.++ CORE_OWNER stays in ``redundant`` and ``products_by_method()`` - it is real+ route coverage - but it names no product directory, so it is dropped here.+ Callers of this method (the ``--namespaces`` output, and the per-product+ semgrep rules generated from it) need real product owners only.+ """+ owned: dict[str, frozenset[str]] = {}+ by_method = self.products_by_method()+ for namespace, block in self._namespace_blocks().items():+ products: set[str] = set()+ for call in _MEMBER_CALL.finditer(block):+ products |= by_method.get(call.group(1), frozenset()) - {CORE_OWNER}+ if products:+ owned[namespace] = frozenset(products)+ return owned++ def _namespace_blocks(self) -> dict[str, str]:+ lines = self._source.splitlines()+ start = next((i for i, line in enumerate(lines) if line.startswith("const api = {")), None)+ if start is None:+ return {}+ blocks: dict[str, str] = {}+ index = start + 1+ while index < len(lines):+ match = _NAMESPACE_START.match(lines[index])+ if match is None:+ index += 1+ continue+ depth, body = 0, []+ while index < len(lines):+ line = lines[index]+ body.append(line)+ depth += line.count("{") - line.count("}")+ index += 1+ if depth <= 0:+ break+ blocks[match.group(1)] = "\n".join(body)+ return blocks+++def read_baseline(repo_root: Path) -> set[str]:+ path = repo_root / BASELINE+ if not path.exists():+ return set()+ return {+ stripped+ for line in path.read_text().splitlines()+ if (stripped := line.strip()) and not stripped.startswith("#")+ }+++def write_baseline(repo_root: Path, methods: set[str]) -> None:+ body = "".join(f"{name}\n" for name in sorted(methods))+ (repo_root / BASELINE).write_text(f"{BASELINE_HEADER}\n{body}")+++def _report_json(ratchet: Ratchet, new: set[str], stale: set[str]) -> str:+ return json.dumps(+ {+ "redundant": [+ {"method": entry.name, "template": "/".join(entry.template), "products": sorted(entry.products)}+ for entry in sorted(ratchet.redundant, key=lambda item: item.entry)+ ],+ "namespaces": {ns: sorted(products) for ns, products in sorted(ratchet.namespaces().items())},+ "new": sorted(new),+ "stale": sorted(stale),+ },+ indent=2,+ )+++ name="lint:api-ratchet",+ help="Block new frontend/src/lib/api.ts path methods that a generated client already covers.",+)[email protected]("--update-baseline", is_flag=True, help="Rewrite the baseline from the current state (it can grow).")[email protected]("--prune-baseline", is_flag=True, help="Drop stale baseline entries. Never adds one.")[email protected]("--namespaces", is_flag=True, help="Print the product-owned api namespaces and their products.")[email protected]("--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:+ """Fail on a new ApiRequest path method that a generated client already covers."""+ repo_root = Path(REPO_ROOT)+ ratchet = Ratchet(repo_root)+ redundant = {entry.entry for entry in ratchet.redundant}++ if namespaces:+ for namespace, products in sorted(ratchet.namespaces().items()):+ click.echo(f"{namespace} {','.join(sorted(products))}")+ return++ baseline = read_baseline(repo_root)+ new = redundant - baseline+ stale = baseline - redundant++ if prune_baseline:+ write_baseline(repo_root, baseline - stale)+ 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.")+ return++ if update_baseline:+ write_baseline(repo_root, redundant)+ click.echo(f"Baseline rewritten: {len(redundant)} redundant path method(s).")+ if new:+ click.echo(+ f"⚠️ This grew the baseline by {len(new)} entry/entries, which grandfathers new debt.\n"+ " Migrate the call sites instead, or say in the pull request why the entry has to stay."+ )+ return++ if as_json:+ click.echo(_report_json(ratchet, new, stale))+ raise SystemExit(1 if new else 0)++ 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:")+ for stale_entry in sorted(stale):+ click.echo(f" {stale_entry}")+ click.echo(" Run: hogli lint:api-ratchet --prune-baseline")+ if new:+ click.echo(f"\n❌ {len(new)} path method(s) duplicate a generated client:")+ for redundant_method in sorted(ratchet.redundant, key=lambda item: item.entry):+ if redundant_method.entry not in new:+ continue+ click.echo(+ f" {redundant_method.name} -> /api/{'/'.join(redundant_method.template)}"+ f" (generated in: {', '.join(sorted(redundant_method.products))})"+ )+ click.echo(+ "\nUse the product's generated client from products/<product>/frontend/generated/api.ts instead.\n"+ "The match is on the route, so check the operation you need is generated as well:\n"+ "if it is not, annotate the viewset and run `hogli build:openapi` before migrating.\n"+ "Agents: invoke the `adopting-generated-api-types` skill."+ )+ raise SystemExit(1)+ click.echo("✅ No new path methods duplicating a generated client.")diff --git a/tools/hogli-commands/hogli_commands/ci_preflight.py b/tools/hogli-commands/hogli_commands/ci_preflight.pyindex 166d07ae0fd6..b8b6b4baf754 100644--- a/tools/hogli-commands/hogli_commands/ci_preflight.py+++ b/tools/hogli-commands/hogli_commands/ci_preflight.py@@ -226,6 +226,23 @@ DIFF_CHECKS: list[DiffCheck] = [verify=["hogli", "lint:feature-flags"],fix=["hogli", "lint:feature-flags:fix"],),+ DiffCheck(+ key="api-ratchet",+ label="new lib/api.ts path method duplicating a generated client",+ # Both sides of the comparison: a new path method, and a regenerated client+ # that gives an existing method a twin.+ triggers=[+ "frontend/src/lib/api.ts",+ "frontend/src/lib/api-ratchet-baseline.txt",+ "frontend/src/generated/core/api.ts",+ "products/*/frontend/generated/api.ts",+ ],+ 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"],+ requires=("python-env",),+ ),DiffCheck(key="workflow-lint",label="workflow-convention failure in .github/workflows",diff --git a/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py b/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.pynew file mode 100644index 000000000000..ae7873342b1c--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_api_ratchet.py@@ -0,0 +1,455 @@+from __future__ import annotations++from pathlib import Path++import pytest++from click.testing import CliRunner, Result+from hogli_commands import api_ratchet+from hogli_commands.api_ratchet import ApiRequestResolver, Ratchet, cmd_lint_api_ratchet, read_baseline+from parameterized import parameterized++runner = CliRunner()++API_TS_FIXTURE = """\+export class ApiRequest {+ private addPathComponent(component: string | number): ApiRequest {+ this.pathComponents.push(component.toString())+ return this+ }++ public organizations(): ApiRequest {+ return this.addPathComponent('organizations')+ }++ public current(): ApiRequest {+ return this.addPathComponent('@current')+ }++ public organizationMembers(): ApiRequest {+ return this.organizations().current().addPathComponent('members')+ }++ public projects(): ApiRequest {+ return this.addPathComponent('projects')+ }++ public projectsDetail(id: ProjectType['id'] = ApiConfig.getCurrentProjectId()): ApiRequest {+ return this.projects().addPathComponent(id)+ }++ public environmentsDetail(id: TeamType['id'] = ApiConfig.getCurrentTeamId()): ApiRequest {+ return this.environments().addPathComponent(id)+ }++ public signalReports(teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId).addPathComponent('signals').addPathComponent('reports')+ }++ public signalReport(id: SignalReport['id'], teamId?: TeamType['id']): ApiRequest {+ return this.signalReports(teamId).addPathComponent(id)+ }++ public propertyDefinitions(teamId?: TeamType['id']): ApiRequest {+ return this.projectsDetail(teamId).addPathComponent('property_definitions')+ }++ public signalReportSimilar(id: SignalReport['id'], teamId?: TeamType['id']): ApiRequest {+ return this.signalReports(teamId).addPathComponent(`${id}/similar`)+ }++ public signalReportChecks(id?: string, teamId?: TeamType['id']): ApiRequest {+ let request = this.signalReports(teamId).addPathComponent('checks')+ if (id) {+ request = request.addPathComponent(id)+ return request+ }+ return request+ }++ public signalScoutRuns(kind?: string, teamId?: TeamType['id']): ApiRequest {+ const request = this.projectsDetail(teamId).addPathComponent('signals')+ if (!kind) {+ return request+ }+ request.addPathComponent('scout')+ return request.addPathComponent(kind)+ }++ public hogFlows(): ApiRequest {+ return this.environmentsDetail().addPathComponent('hog_flows')+ }++ public errorTrackingStackFrames(): ApiRequest {+ return this.errorTracking().addPathComponent('stack_frames/batch_get')+ }++ public errorTracking(teamId?: TeamType['id']): ApiRequest {+ return this.environmentsDetail(teamId).addPathComponent('error_tracking')+ }++ public alerts(alertId?: AlertType['id'], teamId?: TeamType['id']): ApiRequest {+ if (alertId) {+ return this.environmentsDetail(teamId).addPathComponent('alerts').addPathComponent(alertId)+ }+ return this.environmentsDetail(teamId).addPathComponent('alerts')+ }++ public alert(alertId: AlertType['id']): ApiRequest {+ return this.alerts(alertId)+ }++ public alertsCollection(): ApiRequest {+ return this.alerts()+ }++ public query(teamId?: TeamType['id'], queryKind?: string): ApiRequest {+ const apiRequest = this.environmentsDetail(teamId).addPathComponent('query')+ if (queryKind) {+ return apiRequest.addPathComponent(queryKind)+ }+ return apiRequest+ }++ // A mutation that falls through - no return of its own inside the `if` - leaves+ // the shared return below reachable whether or not the block ran.+ public signalReportArchive(archived?: boolean, teamId?: TeamType['id']): ApiRequest {+ const request = this.signalReports(teamId).addPathComponent('archive')+ if (archived) {+ request.addPathComponent('archived')+ }+ return request+ }++ // No `public` keyword - TypeScript makes this callable from `api` regardless.+ signalReportPin(id: SignalReport['id'], teamId?: TeamType['id']): ApiRequest {+ return this.signalReport(id, teamId).addPathComponent('pin')+ }++ public async get(): Promise<any> {+ return await api.get(this.assembleFullUrl())+ }+}++const api = {+ signalReports: {+ async list(): Promise<any> {+ return await new ApiRequest().signalReports().get()+ },+ },+ hogFlows: {+ async list(): Promise<any> {+ return await new ApiRequest().hogFlows().get()+ },+ },+ comments: {+ async list(): Promise<any> {+ return await new ApiRequest().comments().get()+ },+ },+ propertyDefinitions: {+ async list(): Promise<any> {+ return await new ApiRequest().propertyDefinitions().get()+ },+ },+}+"""++GENERATED_SIGNALS = """\+export const signalsReportsList = (projectId: string) => {+ return apiMutator({ url: `/api/projects/${projectId}/signals/reports/`, method: 'GET' })+}+export const signalsReportsRetrieve = (projectId: string, id: string) => {+ return apiMutator({ url: `/api/projects/${projectId}/signals/reports/${id}/`, method: 'GET' })+}+"""++GENERATED_WORKFLOWS = """\+export const hogFlowsList = (projectId: string) => {+ return apiMutator({ url: `/api/projects/${projectId}/hog_flows/`, method: 'GET' })+}+"""++GENERATED_CORE = """\+export const propertyDefinitionsList = (projectId: string) => {+ return apiMutator({ url: `/api/projects/${projectId}/property_definitions/`, method: 'GET' })+}+export const organizationMembersList = (organizationId: string) => {+ return apiMutator({ url: `/api/organizations/${organizationId}/members/`, method: 'GET' })+}+export const remindersList = () => {+ return apiMutator({ url: `/api/reminders/`, method: 'GET' })+}+"""+++def _write_repo(+ root: Path,+ api_ts: str = API_TS_FIXTURE,+ baseline: str | None = None,+ generated_signals: str = GENERATED_SIGNALS,+) -> None:+ (root / "frontend/src/lib").mkdir(parents=True, exist_ok=True)+ (root / "frontend/src/lib/api.ts").write_text(api_ts)+ (root / "products/signals/frontend/generated").mkdir(parents=True, exist_ok=True)+ (root / "products/signals/frontend/generated/api.ts").write_text(generated_signals)+ (root / "products/workflows/frontend/generated").mkdir(parents=True, exist_ok=True)+ (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)+ if baseline is not None:+ (root / api_ratchet.BASELINE).write_text(baseline)+++# Baseline lines carry the route, so the fixtures build them from the resolver.+_FIXTURE_ROUTES = {+ "signalReports": "projects/{}/signals/reports",+ "signalReport": "projects/{}/signals/reports/{}",+ "hogFlows": "projects/{}/hog_flows",+ "propertyDefinitions": "projects/{}/property_definitions",+ "organizationMembers": "organizations/{}/members",+}+++def _baseline_lines(*names: str) -> str:+ return "".join(f"{name} {_FIXTURE_ROUTES[name]}\n" for name in names)+++class TestApiRequestResolver:+ @parameterized.expand(+ [+ ("literal chain off projectsDetail", "signalReports", ["projects/{}/signals/reports"]),+ # The prototype collapsed the whole template literal to one hole, which+ # resolved this to the detail route and called it covered.+ (+ "a template literal keeps its literal segments",+ "signalReportSimilar",+ ["projects/{}/signals/reports/{}/similar"],+ ),+ # organizations().current() passes through another path method, and reading+ # only the component builders dropped the @current segment.+ (+ "a chain through a path helper keeps its segments",+ "organizationMembers",+ ["organizations/@current/members"],+ ),+ # The mutation inside the `if` must not reach the return below the block,+ # or the collection route disappears.+ (+ "a conditional mutation stays inside its branch",+ "signalReportChecks",+ ["projects/{}/signals/reports/checks/{}", "projects/{}/signals/reports/checks"],+ ),+ # The second return reads a chain the first branch did not see.+ (+ "a mutation between two returns reaches the later one",+ "signalScoutRuns",+ ["projects/{}/signals", "projects/{}/signals/scout/{}"],+ ),+ ("dynamic component becomes a hole", "signalReport", ["projects/{}/signals/reports/{}"]),+ ("environments alias is kept until normalization", "hogFlows", ["environments/{}/hog_flows"]),+ (+ "a literal holding a slash splits into segments",+ "errorTrackingStackFrames",+ ["environments/{}/error_tracking/stack_frames/batch_get"],+ ),+ (+ "both branches of a conditional resolve",+ "alerts",+ ["environments/{}/alerts/{}", "environments/{}/alerts"],+ ),+ # `alert` always forwards a required id, so the no-id branch is unreachable.+ (+ "a required argument rules out the branch that doesn't consume it",+ "alert",+ ["environments/{}/alerts/{}"],+ ),+ # `alertsCollection` forwards nothing, so the id branch is unreachable.+ (+ "no argument rules out the branch that needs one",+ "alertsCollection",+ ["environments/{}/alerts"],+ ),+ # The chain root lives in the body, not in the return statement. Resolving+ # the return alone drops environments/{} and the URL looks like /api/query.+ (+ "a chain assigned to a local keeps its root",+ "query",+ ["environments/{}/query/{}", "environments/{}/query"],+ ),+ ("the root path method resolves to its own segment", "projects", ["projects"]),+ # `archived` only mutates and falls through - no return of its own inside+ # the `if` - so the shared return below is reachable either way.+ (+ "a mutation that falls through resolves both ways",+ "signalReportArchive",+ ["projects/{}/signals/reports/archive", "projects/{}/signals/reports/archive/archived"],+ ),+ (+ "a method without the `public` keyword still resolves",+ "signalReportPin",+ ["projects/{}/signals/reports/{}/pin"],+ ),+ ]+ )+ def test_resolves(self, _name: str, method: str, expected: list[str]) -> None:+ resolver = ApiRequestResolver(API_TS_FIXTURE)+ assert ["/".join(template) for template in resolver.templates(method)] == expected++ def test_verb_methods_are_not_path_methods(self) -> None:+ # `get` returns a Promise, so counting it would give every namespace a bare+ # /api/projects/{} template and match half the generated output.+ assert "get" not in ApiRequestResolver(API_TS_FIXTURE).method_names()++ def test_method_names_include_methods_without_public_keyword(self) -> None:+ assert "signalReportPin" in ApiRequestResolver(API_TS_FIXTURE).method_names()+++class TestRatchet:+ def test_flags_methods_with_a_generated_twin(self, tmp_path: Path) -> None:+ _write_repo(tmp_path)+ assert {entry.entry: sorted(entry.products) for entry in Ratchet(tmp_path).redundant} == {+ "signalReports projects/{}/signals/reports": ["signals"],+ "signalReport projects/{}/signals/reports/{}": ["signals"],+ "hogFlows projects/{}/hog_flows": ["workflows"],+ "propertyDefinitions projects/{}/property_definitions": ["core"],+ "organizationMembers organizations/{}/members": ["core"],+ }++ def test_namespaces_lists_only_those_calling_a_redundant_method(self, tmp_path: Path) -> None:+ _write_repo(tmp_path)+ assert {ns: sorted(products) for ns, products in Ratchet(tmp_path).namespaces().items()} == {+ "signalReports": ["signals"],+ "hogFlows": ["workflows"],+ }++ def test_namespaces_drops_the_core_sentinel(self, tmp_path: Path) -> None:+ # `propertyDefinitions` is redundant only against the core client, and CORE_OWNER+ # names no product directory - a namespace covered by it alone must not appear.+ _write_repo(tmp_path)+ assert "propertyDefinitions" not in Ratchet(tmp_path).namespaces()+++class TestEveryBranch:+ # Grandfathering the first route would leave the other branch unguarded.+ def test_a_method_on_two_generated_routes_gets_a_line_each(self, tmp_path: Path) -> None:+ api_ts = API_TS_FIXTURE.replace(+ " public hogFlows(): ApiRequest {",+ " public signalReportsActivity(id?: string, teamId?: TeamType['id']): ApiRequest {\n"+ " return id\n"+ " ? this.signalReports(teamId).addPathComponent(id).addPathComponent('activity')\n"+ " : this.signalReports(teamId).addPathComponent('activity')\n"+ " }\n\n"+ " public hogFlows(): ApiRequest {",+ )+ generated = GENERATED_SIGNALS + (+ "export const signalsReportsActivityList = (projectId: string) => {\n"+ " return apiMutator({ url: `/api/projects/${projectId}/signals/reports/activity/`, method: 'GET' })\n"+ "}\n"+ "export const signalsReportsActivityRetrieve = (projectId: string, id: string) => {\n"+ " return apiMutator({ url: `/api/projects/${projectId}/signals/reports/${id}/activity/`, method: 'GET' })\n"+ "}\n"+ )+ _write_repo(tmp_path, api_ts=api_ts, generated_signals=generated)+ entries = {entry.entry for entry in Ratchet(tmp_path).redundant if entry.name == "signalReportsActivity"}+ assert entries == {+ "signalReportsActivity projects/{}/signals/reports/activity",+ "signalReportsActivity projects/{}/signals/reports/{}/activity",+ }+++class TestBaselineIdentity:+ # Keyed on the name alone, a method that keeps its name and moves to another+ # generated route would stay grandfathered.+ def test_a_method_on_another_route_is_new_debt(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines("hogFlows", "propertyDefinitions", "organizationMembers", "signalReport")+ + "signalReports projects/{}/signals/old_reports\n",+ )+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)+ result = runner.invoke(cmd_lint_api_ratchet, [])+ assert result.exit_code == 1+ assert "signalReports" in result.output++ # A short template is not automatically plumbing: the generated clients really do+ # emit routes such as /api/reminders/.+ def test_only_the_scoping_prefixes_are_exempt(self, tmp_path: Path) -> None:+ api_ts = API_TS_FIXTURE.replace(+ " public projects(): ApiRequest {",+ " public reminders(): ApiRequest {\n"+ " return this.addPathComponent('reminders')\n"+ " }\n\n"+ " public projects(): ApiRequest {",+ )+ _write_repo(tmp_path, api_ts=api_ts)+ names = {entry.name for entry in Ratchet(tmp_path).redundant}+ assert "reminders" in names+ assert "projects" not in names+ assert "organizations" not in names+++class TestBaselineFixModes:+ # Guards the fix path: --update-baseline here would grandfather the new duplicate.+ def test_prune_drops_stale_entries_and_leaves_new_debt_failing(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _write_repo(tmp_path, baseline=_baseline_lines("hogFlows") + "longGoneMethod gone/route\n")+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)+ assert runner.invoke(cmd_lint_api_ratchet, ["--prune-baseline"]).exit_code == 0+ assert read_baseline(tmp_path) == {"hogFlows projects/{}/hog_flows"}+ assert runner.invoke(cmd_lint_api_ratchet, []).exit_code == 1++ def test_update_warns_that_it_grandfathers_new_debt(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_repo(tmp_path, baseline=_baseline_lines("hogFlows"))+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", tmp_path)+ result = runner.invoke(cmd_lint_api_ratchet, ["--update-baseline"])+ assert result.exit_code == 0+ assert "grandfathers new debt" in result.output+ assert runner.invoke(cmd_lint_api_ratchet, []).exit_code == 0+++class TestCommand:+ def _run(self, monkeypatch: pytest.MonkeyPatch, root: Path, *args: str) -> Result:+ monkeypatch.setattr(api_ratchet, "REPO_ROOT", root)+ return runner.invoke(cmd_lint_api_ratchet, list(args))++ def test_fails_on_a_method_missing_from_the_baseline(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_repo(tmp_path, baseline=_baseline_lines("signalReport", "signalReports"))+ result = self._run(monkeypatch, tmp_path)+ assert result.exit_code == 1+ assert "hogFlows" in result.output++ def test_passes_when_every_redundant_method_is_grandfathered(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines(+ "hogFlows", "propertyDefinitions", "organizationMembers", "signalReport", "signalReports"+ ),+ )+ assert self._run(monkeypatch, tmp_path).exit_code == 0++ def test_reports_a_stale_entry_without_failing(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_repo(+ tmp_path,+ baseline=_baseline_lines(+ "hogFlows", "propertyDefinitions", "organizationMembers", "signalReport", "signalReports"+ )+ + "longGoneMethod gone/route\n",+ )+ result = self._run(monkeypatch, tmp_path)+ assert result.exit_code == 0+ assert "longGoneMethod" in result.output++ def test_update_baseline_drops_stale_and_adds_new(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ _write_repo(tmp_path, baseline="longGoneMethod gone/route\n")+ assert self._run(monkeypatch, tmp_path, "--update-baseline").exit_code == 0+ assert read_baseline(tmp_path) == {+ "signalReports projects/{}/signals/reports",+ "signalReport projects/{}/signals/reports/{}",+ "hogFlows projects/{}/hog_flows",+ "propertyDefinitions projects/{}/property_definitions",+ "organizationMembers organizations/{}/members",+ }