#!/usr/bin/env python3 """Inventory and ratchet frontend quality and first-paint cost red flags.""" import argparse import re import sys from collections import Counter, namedtuple from pathlib import Path from typing import Dict, List REPO = Path(__file__).resolve().parents[2] FRONTEND_ROOTS = ("web/src/agentteam",) SOURCE_SUFFIXES = {".ts", ".tsx", ".js", ".jsx"} EXCLUDED_PARTS = {".git", "node_modules", "dist", "coverage", ".data"} UI_PRIMITIVE_PREFIXES = ( "web/src/agentteam/components/ui/", ) API_CLIENT_FILES = { "web/src/agentteam/api/core.ts", } DIRECT_FETCH_OWNER_FILES = API_CLIENT_FILES PATTERNS = { "direct_fetch_outside_api_client": re.compile(r"\bfetch\s*\("), "polling_intervals": re.compile(r"\b(setInterval|window\.setInterval)\s*\("), "direct_button_outside_ui": re.compile(r" str: return path.relative_to(REPO).as_posix() def is_excluded(path: Path) -> bool: return bool(EXCLUDED_PARTS.intersection(path.parts)) def is_test_file(path: Path) -> bool: name = path.name return ".test." in name or ".spec." in name def source_files() -> List[Path]: files: List[Path] = [] for root_name in FRONTEND_ROOTS: root = REPO / root_name if not root.exists(): continue for path in root.rglob("*"): if not path.is_file() or is_excluded(path) or is_test_file(path): continue if path.suffix in SOURCE_SUFFIXES: files.append(path) return sorted(files) def is_comment_or_blank(raw: str) -> bool: stripped = raw.strip() return not stripped or stripped.startswith("//") def is_string_literal_line(raw: str) -> bool: stripped = raw.strip() return stripped.startswith('"') or stripped.startswith("'") or stripped.startswith("`") def strip_js_comments(text: str) -> str: """Remove line and block comments while preserving strings and line numbers.""" output: List[str] = [] quote = "" escaped = False in_line_comment = False in_block_comment = False cursor = 0 while cursor < len(text): char = text[cursor] following = text[cursor + 1] if cursor + 1 < len(text) else "" if in_line_comment: if char == "\n": output.append(char) in_line_comment = False else: output.append(" ") cursor += 1 continue if in_block_comment: if char == "*" and following == "/": output.extend((" ", " ")) in_block_comment = False cursor += 2 else: output.append(char if char == "\n" else " ") cursor += 1 continue if quote: output.append(char) if escaped: escaped = False elif char == "\\": escaped = True elif char == quote: quote = "" cursor += 1 continue if char in {'"', "'", "`"}: quote = char output.append(char) cursor += 1 continue if char == "/" and following == "/": output.extend((" ", " ")) in_line_comment = True cursor += 2 continue if char == "/" and following == "*": output.extend((" ", " ")) in_block_comment = True cursor += 2 continue output.append(char) cursor += 1 return "".join(output) def include_hit(metric: str, path_rel: str, raw: str) -> bool: if is_comment_or_blank(raw): return False if metric == "direct_fetch_outside_api_client": return path_rel not in DIRECT_FETCH_OWNER_FILES and not is_string_literal_line(raw) if metric in {"direct_button_outside_ui", "direct_input_outside_ui"}: return not path_rel.startswith(UI_PRIMITIVE_PREFIXES) return True def array_literal_is_statically_bounded(text: str, array_start_offset: int) -> bool: depth = 0 cursor = array_start_offset while cursor < len(text): char = text[cursor] if char == "[": depth += 1 elif char == "]": depth -= 1 if depth == 0: source = text[array_start_offset : cursor + 1] return ( "..." not in source and ".map(" not in source and ".flatMap(" not in source ) cursor += 1 return False def promise_all_uses_static_array_literal(text: str, open_paren_offset: int) -> bool: cursor = open_paren_offset + 1 while cursor < len(text) and text[cursor].isspace(): cursor += 1 return ( cursor < len(text) and text[cursor] == "[" and array_literal_is_statically_bounded(text, cursor) ) def scan_uncapped_promise_all(path: Path, text: str, lines: List[str]) -> List[Hit]: hits: List[Hit] = [] path_rel = rel(path) for match in PROMISE_ALL_RE.finditer(text): lineno = text.count("\n", 0, match.start()) + 1 raw = lines[lineno - 1] if 0 <= lineno - 1 < len(lines) else "" if is_comment_or_blank(raw) or is_string_literal_line(raw): continue if promise_all_uses_static_array_literal(text, match.end() - 1): continue hits.append(Hit(path_rel, lineno, raw.strip())) return hits def scan() -> Dict[str, List[Hit]]: hits = {name: [] for name in PATTERNS} hits["uncapped_promise_all"] = [] for path in source_files(): path_rel = rel(path) text = path.read_text(errors="ignore") lines = text.splitlines() uncommented_lines = strip_js_comments(text).splitlines() hits["uncapped_promise_all"].extend( scan_uncapped_promise_all(path, text, lines) ) for lineno, raw in enumerate(lines, 1): for name, pattern in PATTERNS.items(): candidate = ( uncommented_lines[lineno - 1] if name == "cjk_literals" else raw ) if not pattern.search(candidate): continue if include_hit(name, path_rel, candidate): hits[name].append(Hit(path_rel, lineno, raw.strip())) return hits def print_inventory(name: str, hits: List[Hit], *, max_examples: int = 8) -> None: print(f"{name}: {len(hits)}") if not hits: return by_file = Counter(hit.file for hit in hits) for file, count in by_file.most_common(max_examples): print(f" {count:4d} {file}") def fail_if_over(name: str, actual: int, maximum: int, failures: List[str]) -> None: print(f"{name}: {actual} (max {maximum})") if actual > maximum: failures.append(f"{name} grew above baseline: {actual} > {maximum}") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--max-direct-fetch-outside-api-client", type=int, required=True) parser.add_argument("--max-polling-intervals", type=int, required=True) parser.add_argument("--max-uncapped-promise-all", type=int, required=True) parser.add_argument("--max-direct-button-outside-ui", type=int, required=True) parser.add_argument("--max-direct-input-outside-ui", type=int, required=True) parser.add_argument("--max-cjk-literals", type=int, required=True) args = parser.parse_args() hits = scan() print("== Frontend quality and first-paint risk inventory ==") for name in ( "direct_fetch_outside_api_client", "polling_intervals", "uncapped_promise_all", "direct_button_outside_ui", "direct_input_outside_ui", "cjk_literals", ): print_inventory(name, hits[name]) failures: List[str] = [] print("\n== Ratchet baselines ==") fail_if_over("direct_fetch_outside_api_client", len(hits["direct_fetch_outside_api_client"]), args.max_direct_fetch_outside_api_client, failures) fail_if_over("polling_intervals", len(hits["polling_intervals"]), args.max_polling_intervals, failures) fail_if_over("uncapped_promise_all", len(hits["uncapped_promise_all"]), args.max_uncapped_promise_all, failures) fail_if_over("direct_button_outside_ui", len(hits["direct_button_outside_ui"]), args.max_direct_button_outside_ui, failures) fail_if_over("direct_input_outside_ui", len(hits["direct_input_outside_ui"]), args.max_direct_input_outside_ui, failures) fail_if_over("cjk_literals", len(hits["cjk_literals"]), args.max_cjk_literals, failures) if failures: for failure in failures: print(f"FAIL: {failure}", file=sys.stderr) print(f"\nFrontend quality guardrail failed with {len(failures)} issue(s).", file=sys.stderr) return 1 print("\nFrontend quality guardrail passed.") return 0 if __name__ == "__main__": raise SystemExit(main())