Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

54.7 KB
Raw Blame
"""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.

A pull request that only adds OpenAPI schema for an endpoint makes an existing,
untouched path method redundant for the first time. The route did not change,
only whether a generated client now covers it. Telling that author to "use the
generated client instead" blames the schema work for debt it did not add, and the
cheapest way out would be dropping the schema annotation. Setting the
``API_RATCHET_BASE`` environment variable to a git ref (CI passes ``HEAD^1``, the
pull request's base commit) separates the two cases. A redundant method that is
not in the baseline but already built the same route on that ref is "exposed": the
check still fails, so the baseline and the semgrep rules stay exact, but it names
the one command that records it (``--update-baseline --write-semgrep``) and tells
the author to keep the schema change. Unset, or when the ref cannot be read
(shallow clone, bad ref), every new entry gets the ordinary message.

    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 and their products
    hogli lint:api-ratchet --write-semgrep    # regenerate the per-product semgrep rules
    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 os
import re
import json
import subprocess
from collections.abc import Iterable
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Final

import click
from hogli.manifest import REPO_ROOT

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")

# CI passes this as `HEAD^1`, the pull request's base commit.
API_RATCHET_BASE_ENV: Final = "API_RATCHET_BASE"

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 ---"

# Shared by both templates below, so they can't drift apart on what they exclude.
SEMGREP_EXCLUDE_PATHS: Final[tuple[str, ...]] = (
    "/frontend/src/lib/api.ts",
    "**/generated/**",
    "**/*.test.ts",
    "**/*.test.tsx",
    "**/*.stories.tsx",
    "**/__mocks__/**",
    "**/mocks/**",
)

# 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.
# Each rule also covers core frontend code, so a scene that moves from frontend/src into
# its product keeps the same rule id and the baseline diff does not count it as new.
# A namespace more than one product owns is left out - see SEMGREP_SHARED_RULE_TEMPLATE.
SEMGREP_RULE_TEMPLATE: Final = """\
    - id: prefer-codegen-api-namespaced-{product}
      message: >-
          Manual `api.<namespace>.<method>(...)` call on a {product} namespace. 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:
{include}
          exclude:
{exclude}
"""

# One rule for a namespace more than one product owns, replacing a copy in each
# owner's SEMGREP_RULE_TEMPLATE rule, scoped over every owner's tree plus core.
SEMGREP_SHARED_RULE_TEMPLATE: Final = """\
    - id: prefer-codegen-api-namespaced-shared-{namespace}
      message: >-
          Manual `api.{namespace}.<method>(...)` call on a namespace several products build
          routes on: {products}.

          The namespace builds its URL in `frontend/src/lib/api.ts`. Use the generated
          client of whichever product's route this call reaches, from
          `products/<product>/frontend/generated/api.ts`.

          Informational while the backlog is worked down, but a call this pull request adds
          fails the job.

          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-shared-{namespace}`
          above this line - the maturity tooling continues to track tagged sites.
      severity: WARNING
      languages: [typescript, javascript]
      pattern-either:
{patterns}
      paths:
          include:
{include}
          exclude:
{exclude}
"""

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+): \{")
# 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"\$\{[^}]*\}")


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)


@dataclass(frozen=True, kw_only=True, slots=True)
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())


@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)


def _method_route_entries(source: str) -> frozenset[str]:
    """Every (method, normalized route) pair ``source`` builds, in baseline-entry form.

    Parsed with the same ``ApiRequestResolver`` used for the current api.ts. This
    reads a *different* version of the file (the base ref's), so it does not care
    whether a route was redundant there - only whether the method already built it,
    to compare against ``RedundantMethod.entry`` on the current side.
    """
    resolver = ApiRequestResolver(source)
    entries: set[str] = set()
    for name in resolver.method_names():
        for template in resolver.templates(name):
            normalized = normalize_template(template)
            entries.add(f"{name} {'/'.join(normalized)}")
    return frozenset(entries)


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 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.

        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}")


# 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 shared_namespaces(ratchet: Ratchet) -> dict[str, list[str]]:
    """Namespaces more than one product owns, each with its owning products, sorted.

    ``ratchet.namespaces()`` already drops CORE_OWNER, so every product left in a
    namespace's set names a real product directory. More than one such product is
    the case a single product-scoped rule can't cover without also firing on the
    other owners' legitimate calls.
    """
    return {namespace: sorted(products) for namespace, products in ratchet.namespaces().items() if len(products) > 1}


def owned_namespaces_by_product(ratchet: Ratchet) -> dict[str, list[str]]:
    """Product -> the ``api`` namespaces its own generated client covers, sorted.

    A namespace ``shared_namespaces`` claims is left out here - it gets one shared
    rule instead of a copy in every owner's rule.
    """
    shared = shared_namespaces(ratchet)
    owned: dict[str, list[str]] = {}
    for namespace, products in ratchet.namespaces().items():
        if namespace in shared:
            continue
        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_patterns(namespaces: list[str]) -> str:
    """The pattern-either lines matching a call on any of the given namespaces.

    Nested members (api.signalScout.runs.list) are a different AST shape, so each
    namespace needs the one-level and the two-level pattern.
    """
    return "\n".join(
        f"          - pattern: api.{namespace}.$METHOD(...)\n          - pattern: api.{namespace}.$MEMBER.$METHOD(...)"
        for namespace in namespaces
    )


def _render_path_bullets(paths: Iterable[str]) -> str:
    """One YAML bullet per path, at the indentation ``paths.include``/``exclude`` use."""
    return "\n".join(f"              - '{path}'" for path in paths)


def render_semgrep_rules(ratchet: Ratchet) -> str:
    """The generated rule block: one rule per product, plus one per shared namespace.

    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. A namespace more than one product owns gets its own
    rule instead of a copy in each owner's: covering it there would report one call
    once per owner, each naming a different product's client.
    """
    exclude = _render_path_bullets(SEMGREP_EXCLUDE_PATHS)
    blocks: list[str] = []
    for product, namespaces in owned_namespaces_by_product(ratchet).items():
        include = _render_path_bullets([f"/products/{product}/frontend/", "/frontend/src/"])
        blocks.append(
            SEMGREP_RULE_TEMPLATE.format(
                product=product, patterns=_render_patterns(namespaces), include=include, exclude=exclude
            )
        )
    for namespace, products in sorted(shared_namespaces(ratchet).items()):
        include = _render_path_bullets([f"/products/{product}/frontend/" for product in products] + ["/frontend/src/"])
        blocks.append(
            SEMGREP_SHARED_RULE_TEMPLATE.format(
                namespace=namespace,
                products=", ".join(products),
                patterns=_render_patterns([namespace]),
                include=include,
                exclude=exclude,
            )
        )
    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 total 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)) + len(shared_namespaces(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], exposed: 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),
            "exposed": sorted(exposed),
        },
        indent=2,
    )


def _exposed_message(ratchet: Ratchet, exposed: set[str]) -> str:
    """The failure for builders a schema change exposed, with the one command that records them."""
    lines = [f"\n❌ {len(exposed)} builder(s) already existed and only gained a generated twin in this change."]
    lines.append("   Not your debt, so keep the schema change:")
    for entry in sorted(ratchet.redundant, key=lambda item: item.entry):
        if entry.entry in exposed:
            lines.append(f"    {entry.name}  ->  /api/{'/'.join(entry.template)}")
    lines.append("   Run: hogli lint:api-ratchet --update-baseline --write-semgrep, then commit the result.")
    return "\n".join(lines)


def _read_base_api_ts(repo_root: Path, ref: str) -> str | None:
    """The base ref's api.ts contents, or ``None`` if git can't produce them.

    Covers a shallow checkout that never fetched the ref, a bad ref name, and a repo
    where the file didn't exist yet at that commit — each comes back as a failed
    ``git show`` rather than a partial read.
    """
    result = subprocess.run(
        ["git", "show", f"{ref}:{API_TS.as_posix()}"], cwd=repo_root, capture_output=True, text=True
    )
    return result.stdout if result.returncode == 0 else None


def _base_entries(repo_root: Path) -> frozenset[str] | None:
    """The method and route entries the ``API_RATCHET_BASE_ENV`` ref builds, or ``None``.

    ``None`` when the variable is unset, or with a warning when git cannot read the ref;
    either way every new entry then gets the ordinary message.
    """
    ref = os.environ.get(API_RATCHET_BASE_ENV)
    if not ref:
        return None
    base_source = _read_base_api_ts(repo_root, ref)
    if base_source is None:
        click.echo(f"⚠️  {API_RATCHET_BASE_ENV}={ref} could not be read (shallow clone or unknown ref).", err=True)
        return None
    return _method_route_entries(base_source)


@click.command(
    name="lint:api-ratchet",
    help="Block new frontend/src/lib/api.ts path methods that a generated client already covers.",
)
@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.")
@click.option(
    "--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, 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)
    redundant = {entry.entry for entry in ratchet.redundant}

    if write_semgrep:
        count = write_semgrep_rules(repo_root, ratchet)
        click.echo(f"{SEMGREP_RULE}: {count} 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))}")
        return

    baseline = read_baseline(repo_root)
    new = redundant - baseline
    stale = baseline - redundant

    if 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.")
        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.\n"
                "    If this change added them, migrate the call sites instead, or say in the pull request why\n"
                "    they have to stay. If they existed before and a schema change only exposed them, that is expected."
            )
        return

    base_entries = _base_entries(repo_root)
    exposed = {entry for entry in new if base_entries is not None and entry in base_entries}
    added = new - exposed

    if as_json:
        click.echo(_report_json(ratchet, new, stale, exposed))
        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:")
        for stale_entry in sorted(stale):
            click.echo(f"    {stale_entry}")
        click.echo("    Run: hogli lint:api-ratchet --prune-baseline")
    if exposed:
        click.echo(_exposed_message(ratchet, exposed))
    if added:
        click.echo(f"\n❌ {len(added)} 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 added:
                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."
        )
    if new:
        raise SystemExit(1)
    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.")