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.

fix(devex): adjust product:maturity scoring to use percentage-based detail message (#57479)

Julian Bez6b1e3e81265d
diff --git a/tools/hogli-commands/hogli_commands/product/cli.py b/tools/hogli-commands/hogli_commands/product/cli.py
index bf1038768147..fa1336c5a1cc 100644
--- a/tools/hogli-commands/hogli_commands/product/cli.py
+++ b/tools/hogli-commands/hogli_commands/product/cli.py
@@ -6,7 +6,7 @@ import click
from hogli.cli import cli
from .lint import lint_all_products, lint_product
-from .maturity import generate_detail, generate_report, score_all_products, score_product
+from .maturity import generate_codegen_report, generate_detail, generate_report, score_all_products, score_product
from .scaffold import bootstrap_product
@@ -46,7 +46,13 @@ def cmd_lint(name: str | None, lint_all: bool) -> None:
@cli.command(name="product:maturity", help="Score product maturity across isolation dimensions")
@click.argument("name", required=False)
@click.option("--all", "score_all", is_flag=True, help="Score all products and generate ranked report")
-def cmd_maturity(name: str | None, score_all: bool) -> None:
[email protected]("--codegen", "codegen_detail", is_flag=True, help="Show detailed codegen call-site analysis")
+def cmd_maturity(name: str | None, score_all: bool, codegen_detail: bool) -> None:
+ if codegen_detail:
+ products = None if score_all or not name else [name]
+ click.echo(generate_codegen_report(products))
+ return
+
if score_all:
scores = score_all_products()
click.echo(generate_report(scores))
diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.py
index a4ace73a521c..4fd611561371 100644
--- a/tools/hogli-commands/hogli_commands/product/maturity.py
+++ b/tools/hogli-commands/hogli_commands/product/maturity.py
@@ -35,7 +35,7 @@ from .ast_helpers import (
)
from .paths import PRODUCTS_DIR, REPO_ROOT, TACH_TOML, find_views_path, get_tach_block
from .product_yaml import load_all_product_yamls, load_product_yaml
-from .ts_helpers import codegen_adoption
+from .ts_helpers import codegen_adoption, codegen_call_sites
# ---------------------------------------------------------------------------
# Config loading (best-effort from migration_config.json)
@@ -498,10 +498,8 @@ def score_codegen(product_dir: Path) -> DimensionScore:
manual api.* calls. Having generated/api.ts is free (hogli build:openapi
creates it for everyone) — what matters is actual usage.
- Points breakdown (100 total):
- frontend imports any generated function: 40
- no manual api.* HTTP calls: 60 (proportional —
- loses points as manual/(manual+generated_used) increases)
+ Score = percentage of API calls using generated client:
+ 100 * generated_used / (generated_used + manual_calls)
"""
frontend_dir = product_dir / "frontend"
if not frontend_dir.exists():
@@ -516,23 +514,16 @@ def score_codegen(product_dir: Path) -> DimensionScore:
if available == 0 and manual == 0:
return DimensionScore("codegen", 0, "no API usage")
- score = 0
- parts = []
-
- if used > 0:
- score += 40
- parts.append(f"{used} generated endpoints used")
- else:
- parts.append("0 generated used")
-
total_calls = used + manual
- if total_calls > 0:
- score += round(60 * used / total_calls)
- if manual > 0:
- parts.append(f"{manual} manual")
+ if total_calls > 0:
+ score = round(100 * used / total_calls)
+ detail = f"{score}% codegen ({used} generated, {manual} manual)"
+ else:
+ score = 0
+ detail = "no API usage"
- return DimensionScore("codegen", score, ", ".join(parts))
+ return DimensionScore("codegen", score, detail)
# ---------------------------------------------------------------------------
@@ -609,11 +600,11 @@ _DIM_SHORT = {
"facade": "facade",
"presentation": "presnt",
"boundaries": "bounds",
- "codegen": "codegn",
+ "codegen": "codgen",
}
_BAR_WIDTH = 15
-_MINI_WIDTH = 5
+_MINI_WIDTH = 6
def _bar(score: int, width: int = _BAR_WIDTH) -> str:
@@ -710,4 +701,71 @@ def generate_detail(ps: ProductScore) -> str:
lines.append("")
lines.append(f" {'overall':>17s} {overall:3d} {_bar(overall)}")
+ # Append codegen call-site details if there are manual calls
+ frontend_dir = PRODUCTS_DIR / ps.product / "frontend"
+ if frontend_dir.exists():
+ sites = codegen_call_sites(frontend_dir)
+ if sites:
+ lines.append("")
+ lines.append(" codegen call sites:")
+ for site in sites:
+ arrow = f"\u2192 {site.generated_equivalent}" if site.generated_equivalent else "(no match)"
+ lines.append(f" {site.file}:{site.line} {site.verb} {arrow}")
+
return "\n".join(lines)
+
+
+# ---------------------------------------------------------------------------
+# Codegen detail report
+# ---------------------------------------------------------------------------
+
+
+def generate_codegen_report(products: list[str] | None = None) -> str:
+ """Generate a detailed codegen adoption report showing call sites and matches.
+
+ If products is None, reports on all products with manual API calls.
+ """
+
+ if products is None:
+ products = sorted(
+ d.name
+ for d in PRODUCTS_DIR.iterdir()
+ if d.is_dir()
+ and not d.name.startswith((".", "_"))
+ and d.name != "__pycache__"
+ and (d / "__init__.py").exists()
+ )
+
+ lines: list[str] = []
+ total_manual = 0
+ total_matched = 0
+
+ for name in products:
+ frontend_dir = PRODUCTS_DIR / name / "frontend"
+ if not frontend_dir.exists():
+ continue
+
+ sites = codegen_call_sites(frontend_dir)
+ if not sites:
+ continue
+
+ matched = sum(1 for s in sites if s.generated_equivalent)
+ total_manual += len(sites)
+ total_matched += matched
+
+ pct = round(100 * matched / len(sites)) if sites else 0
+ lines.append(f"{name} {matched}/{len(sites)} matched ({pct}%)")
+
+ for site in sites:
+ arrow = f"→ {site.generated_equivalent}" if site.generated_equivalent else " (no match)"
+ lines.append(f" {site.file}:{site.line} {site.verb}({site.url[:50]}) {arrow}")
+
+ lines.append("")
+
+ if total_manual > 0:
+ overall_pct = round(100 * total_matched / total_manual)
+ header = f"Codegen adoption: {total_matched}/{total_manual} manual calls have generated equivalents ({overall_pct}%)\n"
+ else:
+ header = "No manual API calls found.\n"
+
+ return header + "\n" + "\n".join(lines)
diff --git a/tools/hogli-commands/hogli_commands/product/ts_helpers.py b/tools/hogli-commands/hogli_commands/product/ts_helpers.py
index d681474eb0fc..c28df9f5539e 100644
--- a/tools/hogli-commands/hogli_commands/product/ts_helpers.py
+++ b/tools/hogli-commands/hogli_commands/product/ts_helpers.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import re
+from dataclasses import dataclass
from pathlib import Path
_EXPORTED_ASYNC_RE = re.compile(r"^export\s+const\s+(\w+)\s*=\s*async\s*\(", re.MULTILINE)
@@ -52,7 +53,21 @@ def get_generated_imports_in_frontend(frontend_dir: Path) -> set[str]:
return imported
-_HTTP_VERBS = re.compile(r"\bapi\.(?:get|post|put|patch|delete|create|update)\s*\(", re.IGNORECASE)
+_HTTP_VERBS = re.compile(r"\bapi\.(?:get|post|put|patch|delete|create|update)\s*(?:<[^>]*>)?\s*\(", re.IGNORECASE)
+_HTTP_VERBS_WITH_URL = re.compile(
+ r"\bapi\.(get|post|put|patch|delete|create|update)\s*(?:<[^>]*>)?\s*\(\s*[`'\"](.*?)[`'\"]",
+ re.IGNORECASE,
+)
+
+_VERB_TO_METHOD = {
+ "get": "GET",
+ "post": "POST",
+ "put": "PUT",
+ "patch": "PATCH",
+ "delete": "DELETE",
+ "create": "POST",
+ "update": "PUT",
+}
def count_manual_api_calls(frontend_dir: Path) -> int:
@@ -115,6 +130,126 @@ def codegen_adoption(frontend_dir: Path) -> dict:
}
+# ---------------------------------------------------------------------------
+# Detailed call-site analysis with generated equivalent matching
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class ManualCallSite:
+ file: str
+ line: int
+ verb: str
+ url: str
+ method: str
+ generated_equivalent: str | None
+
+
+def _normalize_url(url: str) -> str:
+ """Normalize a URL for comparison: replace template vars, strip query params."""
+ url = re.sub(r"\$\{[^}]+\}", "{p}", url)
+ url = re.sub(r"@current", "{p}", url)
+ url = re.sub(r"\?.*", "", url)
+ url = url.rstrip("/")
+ if not url.startswith("/"):
+ url = "/" + url
+ return url
+
+
+def _parse_generated_url_map(api_ts: Path) -> dict[tuple[str, str], str]:
+ """Parse generated/api.ts and return {(normalized_url, METHOD): function_name}."""
+ if not api_ts.exists():
+ return {}
+ content = api_ts.read_text()
+
+ # Extract URL helpers — handle both simple return and ternary (query param variants)
+ url_helpers: dict[str, str] = {}
+ for m in re.finditer(
+ r"export const (get\w+Url)\s*=\s*\([^)]*\)\s*(?::\s*\w+\s*)?=>\s*\{(.*?)\n\}",
+ content,
+ re.DOTALL,
+ ):
+ name = m.group(1)
+ body = m.group(2)
+ urls = re.findall(r"[`]([^`]+)[`]", body)
+ if urls:
+ # Prefer the URL without query params (cleaner for matching)
+ clean = [u for u in urls if "?" not in u] or urls
+ url_helpers[name] = clean[0]
+
+ # Map async functions to their URL + method
+ generated: dict[tuple[str, str], str] = {}
+ for m in re.finditer(
+ r"export const (\w+)\s*=\s*async\s*\(.*?method:\s*['\"](\w+)['\"]",
+ content,
+ re.DOTALL,
+ ):
+ fn_name = m.group(1)
+ method = m.group(2)
+ fn_text = content[m.start() : m.start() + 500]
+ url_call = re.search(r"(get\w+Url)\(", fn_text)
+ if url_call and url_call.group(1) in url_helpers:
+ raw_url = url_helpers[url_call.group(1)]
+ url = _normalize_url(raw_url)
+ generated[(url, method)] = fn_name
+
+ return generated
+
+
+def codegen_call_sites(frontend_dir: Path) -> list[ManualCallSite]:
+ """Find all manual API call sites and match them to generated equivalents.
+
+ Returns a list of ManualCallSite objects with file, line, verb, url,
+ and the matched generated function name (or None if no match).
+ """
+ api_ts = frontend_dir / "generated" / "api.ts"
+ generated_map = _parse_generated_url_map(api_ts)
+ generated_dir = frontend_dir / "generated"
+
+ sites: list[ManualCallSite] = []
+
+ for ts_file in _collect_ts_files(frontend_dir):
+ if _is_inside(ts_file, generated_dir):
+ continue
+ content = ts_file.read_text()
+ has_api_import = (
+ "from 'lib/api'" in content
+ or 'from "lib/api"' in content
+ or "from '~/lib/api'" in content
+ or 'from "~/lib/api"' in content
+ )
+ if not has_api_import:
+ continue
+
+ rel_path = str(ts_file.relative_to(frontend_dir))
+
+ # Match verb + URL across lines (URL may be on the next line)
+ multi_line_re = re.compile(
+ r"\bapi\.(get|post|put|patch|delete|create|update)\s*(?:<[^>]*>)?\s*\(\s*[`'\"](.*?)[`'\"]",
+ re.IGNORECASE | re.DOTALL,
+ )
+ for m in multi_line_re.finditer(content):
+ verb = m.group(1).lower()
+ raw_url = m.group(2)
+ # Compute line number from offset
+ line_no = content[: m.start()].count("\n") + 1
+ method = _VERB_TO_METHOD[verb]
+ url = _normalize_url(raw_url)
+ equivalent = generated_map.get((url, method))
+ sites.append(
+ ManualCallSite(
+ file=rel_path,
+ line=line_no,
+ verb=verb,
+ url=raw_url,
+ method=method,
+ generated_equivalent=equivalent,
+ )
+ )
+
+ return sites
+
+
def _collect_ts_files(directory: Path) -> list[Path]:
"""Collect .ts and .tsx files, skipping node_modules and __pycache__."""
if not directory.exists():