CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

trysac/repo-health

Score a local repository on docs, tests, CI, security and maintenance with ten weighted offline checks and an A-F grade. Use when the user asks how healthy, complete or well maintained a repository is, or what basics it lacks.

Quality

94%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Passed

No findings from the security scan

Overview
Quality
Evals
Security
Files

repo_health.pyscripts/

"""Offline repository health scorer bundled with the repo-health agent skill.

Ten weighted checks (docs, tests, CI, security, maintenance), standard library only. The script
reads files of the checkout, never executes repository code, makes no network calls and never
runs git. Git-based checks (SEC001, MNT001) use data you pass in with ``--tracked-files`` and
``--last-commit`` and are skipped when it is missing.

Usage: python repo_health.py [PATH] [--format text|json] [--min-score N] [--now ISO8601]
       [--tracked-files FILE|-] [--last-commit ISO8601]
Exit codes: 0 success, 1 score below --min-score or a domain error, 2 usage or IO error.
"""

from __future__ import annotations

import argparse
import fnmatch
import json
import logging
import os
import posixpath
import re
import stat
import sys
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Literal, Protocol

logger = logging.getLogger(__name__)

Category = Literal["docs", "tests", "ci", "security", "maintenance"]
Status = Literal["pass", "fail", "skipped"]
ErrorCode = Literal["root_missing", "too_many_files", "naive_time"]

_DETAIL_LIMIT = 200
_MIN_README_WORDS = 100
_MAINTAINED_WINDOW = timedelta(days=365)
_WORKFLOW_DIR = ".github/workflows/"
_GITLAB_CI = ".gitlab-ci.yml"
_CI_PATTERN = r"(?<!\w)(?:pytest|npm\s+test|go\s+test|tox|nox|make\s+test)(?!\w)"
_CI_COMMAND = re.compile(_CI_PATTERN)
_README_NAMES = frozenset({"readme", "readme.md", "readme.rst", "readme.txt", "readme.markdown"})
_LICENSE_NAMES = frozenset({"license", "license.md", "license.txt", "copying"})
_CONTRIBUTING_NAMES = frozenset(
    {"contributing", "contributing.md", "contributing.rst", "contributing.txt"}
)
_SECURITY_NAMES = frozenset({"security.md"})
_TEST_PATTERNS = ("test_*.py", "*_test.py", "*_test.go", "*.test.ts", "*.spec.ts")
_UPDATE_FILES = frozenset(
    {
        ".github/dependabot.yml",
        ".github/dependabot.yaml",
        "renovate.json",
        "renovate.json5",
        ".renovaterc",
        ".renovaterc.json",
        ".github/renovate.json",
        ".github/renovate.json5",
        ".gitlab/renovate.json5",
    }
)
_SECRET_KEY_NAMES = frozenset({"id_rsa", "id_ed25519"})

_META: dict[str, tuple[Category, int]] = {
    "DOC001": ("docs", 10),
    "DOC002": ("docs", 10),
    "DOC003": ("docs", 5),
    "DOC004": ("docs", 10),
    "TST001": ("tests", 10),
    "CI001": ("ci", 10),
    "CI002": ("ci", 5),
    "SEC001": ("security", 15),
    "SEC002": ("security", 10),
    "MNT001": ("maintenance", 15),
}


def _clip(text: str, limit: int = _DETAIL_LIMIT) -> str:
    """Replace non-printable characters and cap the length of ``text``."""
    cleaned = "".join(ch if ch.isprintable() else "?" for ch in text)
    return cleaned[:limit]


class RepoHealthError(Exception):
    """Base error of the library.

    Attributes:
        code: stable machine-readable identifier, one of ``root_missing``,
            ``too_many_files`` or ``naive_time``.
    """

    def __init__(self, code: ErrorCode, message: str) -> None:
        super().__init__(_clip(message))
        self.code: ErrorCode = code


@dataclass(frozen=True)
class CheckResult:
    """Outcome of a single check."""

    id: str
    category: Category
    weight: int
    status: Status
    detail: str


class GitPort(Protocol):
    """Access to git data; ``None`` means the information is unavailable (check skipped)."""

    def last_commit_time(self) -> datetime | None:
        """Return the committer time of HEAD (timezone-aware) or ``None``."""
        ...

    def tracked_files(self) -> list[str] | None:
        """Return the tracked paths relative to the root or ``None``."""
        ...


class ProvidedGit:
    """``GitPort`` backed by data the caller supplies; this script never runs git.

    ``None`` means the data was not supplied, so the checks that need it are skipped.
    """

    def __init__(
        self, tracked: list[str] | None = None, last_commit: datetime | None = None
    ) -> None:
        self._tracked = tracked
        self._last_commit = last_commit

    def last_commit_time(self) -> datetime | None:
        """Return the supplied committer time of HEAD or ``None``."""
        return self._last_commit

    def tracked_files(self) -> list[str] | None:
        """Return the supplied tracked paths or ``None``."""
        return self._tracked


class _TooLargeError(Exception):
    """Raised internally when a file exceeds the configured size limit."""


def _read_text(path: Path, limit: int) -> str:
    """Read a regular file of at most ``limit`` bytes; never opens larger files."""
    info = os.lstat(path)
    if not stat.S_ISREG(info.st_mode):
        raise OSError("not a regular file")
    if info.st_size > limit:
        raise _TooLargeError
    with open(path, "rb") as handle:
        data = handle.read(limit)
    return data.decode("utf-8", errors="replace")


@dataclass(frozen=True)
class _Tree:
    root: Path
    files: tuple[str, ...]
    dirs: frozenset[str]
    max_file_bytes: int

    def find(self, folders: Sequence[str], names: frozenset[str]) -> str | None:
        """Return the first file in one of ``folders`` whose lower-cased name is in ``names``."""
        for rel in self.files:
            folder, _, base = rel.rpartition("/")
            if folder in folders and base.lower() in names:
                return rel
        return None

    def read(self, rel: str) -> str:
        return _read_text(self.root / rel, self.max_file_bytes)


def _scan(root: Path, max_files: int) -> tuple[tuple[str, ...], frozenset[str]]:
    """List regular files and directories below ``root`` without following symlinks."""
    files: list[str] = []
    dirs: set[str] = {""}
    pending = [""]
    while pending:
        folder = pending.pop()
        with os.scandir(root / folder if folder else root) as entries:
            for entry in entries:
                if entry.name == ".git" or entry.is_symlink():
                    continue
                rel = f"{folder}/{entry.name}" if folder else entry.name
                if entry.is_dir(follow_symlinks=False):
                    dirs.add(rel)
                    pending.append(rel)
                elif entry.is_file(follow_symlinks=False):
                    files.append(rel)
                    if len(files) > max_files:
                        raise RepoHealthError("too_many_files", "too many files in the checkout")
    return tuple(sorted(files)), frozenset(dirs)


def _result(check_id: str, ok: bool | None, detail: str) -> CheckResult:
    category, weight = _META[check_id]
    status: Status = "skipped" if ok is None else ("pass" if ok else "fail")
    return CheckResult(check_id, category, weight, status, _clip(detail))


def _require_aware(value: datetime, what: str) -> None:
    if value.tzinfo is None or value.utcoffset() is None:
        raise RepoHealthError("naive_time", f"{what} must be timezone-aware")


def _doc001(tree: _Tree) -> CheckResult:
    rel = tree.find(("",), _README_NAMES)
    if rel is None:
        return _result("DOC001", False, "missing")
    try:
        text = tree.read(rel)
    except _TooLargeError:
        return _result("DOC001", False, "too large")
    except OSError:
        return _result("DOC001", False, "unreadable")
    words = len(text.split())
    return _result("DOC001", words >= _MIN_README_WORDS, f"{words} words")


def _presence(
    tree: _Tree, check_id: str, folders: Sequence[str], names: frozenset[str]
) -> CheckResult:
    rel = tree.find(folders, names)
    if rel is None:
        return _result(check_id, False, "missing")
    return _result(check_id, True, f"found {rel}")


def _tst001(tree: _Tree) -> CheckResult:
    for rel in tree.files:
        base = rel.rpartition("/")[2]
        if any(fnmatch.fnmatchcase(base, pattern) for pattern in _TEST_PATTERNS):
            return _result("TST001", True, f"test file {rel}")
    for folder in sorted(tree.dirs):
        if folder.rpartition("/")[2] == "tests":
            return _result("TST001", True, f"tests directory {folder}")
    return _result("TST001", False, "no test files")


def _ci_files(tree: _Tree) -> list[str]:
    return [rel for rel in tree.files if rel.startswith(_WORKFLOW_DIR) or rel == _GITLAB_CI]


def _ci001(tree: _Tree) -> CheckResult:
    found = _ci_files(tree)
    if found:
        return _result("CI001", True, f"CI configuration {found[0]}")
    return _result("CI001", False, "no CI configuration")


def _ci002(tree: _Tree) -> CheckResult:
    unreadable = 0
    for rel in _ci_files(tree):
        try:
            text = tree.read(rel)
        except (_TooLargeError, OSError):
            unreadable += 1
            continue
        if _CI_COMMAND.search(text):
            return _result("CI002", True, f"test command in {rel}")
    if unreadable:
        return _result("CI002", False, f"no test command found ({unreadable} unreadable)")
    return _result("CI002", False, "no test command found")


def _is_secret_name(path: str) -> bool:
    name = posixpath.basename(path).lower()
    if name.endswith((".example", ".sample")):
        return False
    return (
        name == ".env"
        or name.startswith(".env.")
        or name.endswith((".pem", ".key"))
        or name in _SECRET_KEY_NAMES
    )


def _sec001(tracked: list[str] | None) -> CheckResult:
    if tracked is None:
        return _result("SEC001", None, "git unavailable")
    bad = [path for path in tracked if _is_secret_name(path)]
    if bad:
        return _result("SEC001", False, "tracked secret files: " + ", ".join(bad[:5]))
    return _result("SEC001", True, "no tracked secret files")


def _sec002(tree: _Tree) -> CheckResult:
    for rel in tree.files:
        if rel in _UPDATE_FILES:
            return _result("SEC002", True, f"found {rel}")
    return _result("SEC002", False, "no dependency update configuration")


def _mnt001(last: datetime | None, now: datetime) -> CheckResult:
    if last is None:
        return _result("MNT001", None, "git unavailable")
    _require_aware(last, "commit time")
    age = now.astimezone(timezone.utc) - last.astimezone(timezone.utc)
    return _result("MNT001", age <= _MAINTAINED_WINDOW, f"last commit {age.days} days ago")


def run_checks(
    root: Path,
    *,
    now: datetime,
    git: GitPort | None = None,
    max_file_bytes: int = 1_048_576,
    max_files: int = 50_000,
) -> list[CheckResult]:
    """Run the ten checks against the checkout at ``root``.

    Args:
        root: directory of the checkout.
        now: timezone-aware reference time (compared in UTC).
        git: git data; defaults to ``ProvidedGit()`` (git checks skipped).
        max_file_bytes: files larger than this are never read.
        max_files: maximum number of walked or tracked files.

    Returns:
        The results sorted by check id.

    Raises:
        RepoHealthError: ``naive_time``, ``root_missing`` or ``too_many_files``.
        OSError: if a directory cannot be listed.
    """
    _require_aware(now, "now")
    if not root.is_dir():
        raise RepoHealthError("root_missing", "root is not a directory")
    files, dirs = _scan(root, max_files)
    tree = _Tree(root, files, dirs, max_file_bytes)
    port: GitPort = ProvidedGit() if git is None else git
    tracked = port.tracked_files()
    if tracked is not None and len(tracked) > max_files:
        raise RepoHealthError("too_many_files", "too many tracked files")
    last = port.last_commit_time()
    results = [
        _doc001(tree),
        _presence(tree, "DOC002", ("",), _LICENSE_NAMES),
        _presence(tree, "DOC003", ("", ".github", "docs"), _CONTRIBUTING_NAMES),
        _presence(tree, "DOC004", ("", ".github", "docs"), _SECURITY_NAMES),
        _tst001(tree),
        _ci001(tree),
        _ci002(tree),
        _sec001(tracked),
        _sec002(tree),
        _mnt001(last, now),
    ]
    return sorted(results, key=lambda item: item.id)


# ---------------------------------------------------------------------------
# Scoring
# ---------------------------------------------------------------------------

Grade = Literal["A", "B", "C", "D", "F"]

_CATEGORIES: tuple[Category, ...] = ("docs", "tests", "ci", "security", "maintenance")


def _percent(results: Sequence[CheckResult]) -> int:
    """Weighted percentage of passed checks, rounded half up; skipped checks are ignored."""
    possible = sum(item.weight for item in results if item.status != "skipped")
    if possible == 0:
        return 0
    passed = sum(item.weight for item in results if item.status == "pass")
    return (200 * passed + possible) // (2 * possible)


def _grade(total: int) -> Grade:
    if total >= 90:
        return "A"
    if total >= 80:
        return "B"
    if total >= 70:
        return "C"
    if total >= 60:
        return "D"
    return "F"


@dataclass(frozen=True)
class HealthReport:
    """Aggregated score of a set of check results."""

    total: int
    by_category: dict[str, int]
    grade: Grade
    results: tuple[CheckResult, ...]

    def to_text(self) -> str:
        """Render a human-readable report."""
        lines = [f"Repo health score: {self.total}/100 (grade {self.grade})"]
        lines.append("Categories: " + ", ".join(f"{k} {v}" for k, v in self.by_category.items()))
        for item in sorted(self.results, key=lambda r: r.id):
            status = item.status.upper()
            lines.append(f"{status:7} {item.id} [{item.category}] w{item.weight}: {item.detail}")
        return "\n".join(lines)

    def to_json(self) -> str:
        """Render the results as a JSON list of objects, sorted by id."""
        payload = [
            {
                "id": item.id,
                "category": item.category,
                "weight": item.weight,
                "status": item.status,
                "detail": item.detail,
            }
            for item in sorted(self.results, key=lambda r: r.id)
        ]
        return json.dumps(payload, indent=2)


def score(results: Sequence[CheckResult]) -> HealthReport:
    """Compute the total, per-category scores and grade for ``results``.

    With ``p`` passed weight and ``w`` non-skipped weight, ``total = (200 * p + w) // (2 * w)``
    (round half up). When everything is skipped the total is 0.
    """
    total = _percent(results)
    by_category: dict[str, int] = {
        category: _percent([item for item in results if item.category == category])
        for category in _CATEGORIES
    }
    return HealthReport(total, by_category, _grade(total), tuple(results))


# ---------------------------------------------------------------------------
# Command line
# ---------------------------------------------------------------------------

_MAX_NUMBER_CHARS = 16
_MAX_TIMESTAMP_CHARS = 64


def _min_score(text: str) -> int:
    if len(text) > _MAX_NUMBER_CHARS:
        raise argparse.ArgumentTypeError("number is too long")
    try:
        value = int(text)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("must be an integer") from exc
    if not 0 <= value <= 100:
        raise argparse.ArgumentTypeError("must be between 0 and 100")
    return value


def _timestamp(text: str) -> datetime:
    if len(text) > _MAX_TIMESTAMP_CHARS:
        raise argparse.ArgumentTypeError("timestamp is too long")
    value = f"{text[:-1]}+00:00" if text.endswith(("Z", "z")) else text
    try:
        return datetime.fromisoformat(value)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("must be an ISO 8601 timestamp") from exc


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="repo_health.py",
        description="Score a local repository checkout with ten weighted offline checks.",
    )
    parser.add_argument("path", nargs="?", default=".", help="repository root (default: .)")
    parser.add_argument("--format", choices=("text", "json"), default="text")
    parser.add_argument("--min-score", type=_min_score, default=None, metavar="N")
    parser.add_argument("--now", type=_timestamp, default=None, metavar="ISO8601")
    parser.add_argument(
        "--tracked-files",
        default=None,
        metavar="FILE",
        help="file with the tracked paths, NUL or newline separated ('-' reads stdin)",
    )
    parser.add_argument(
        "--last-commit",
        type=_timestamp,
        default=None,
        metavar="ISO8601",
        help="committer time of HEAD, timezone-aware (enables MNT001)",
    )
    return parser


_MAX_TRACKED_BYTES = 16 * 1024 * 1024


def _read_tracked(spec: str) -> list[str]:
    """Read tracked paths from a file or stdin; NUL separated when a NUL is present."""
    if spec == "-":
        data = sys.stdin.buffer.read(_MAX_TRACKED_BYTES + 1)
    else:
        with open(spec, "rb") as handle:
            data = handle.read(_MAX_TRACKED_BYTES + 1)
    if len(data) > _MAX_TRACKED_BYTES:
        raise RepoHealthError("too_many_files", "tracked file list is too large")
    text = data.decode("utf-8", errors="replace")
    names = text.split("\0") if "\0" in text else text.splitlines()
    return [name for name in names if name]


def main(argv: list[str] | None = None) -> int:
    """Run the CLI and return the exit code.

    0: success; 1: score below ``--min-score`` or a domain failure; 2: usage or IO error.
    """
    parser = _build_parser()
    try:
        args = parser.parse_args(argv)
    except SystemExit as exc:
        code = exc.code
        return code if isinstance(code, int) else 2
    now = args.now if args.now is not None else datetime.now(timezone.utc)
    root = Path(args.path)
    try:
        tracked = _read_tracked(args.tracked_files) if args.tracked_files else None
        git = ProvidedGit(tracked, args.last_commit)
        results = run_checks(root, now=now, git=git)
    except RepoHealthError as exc:
        print(f"repo_health: error: {exc.code}: {exc}", file=sys.stderr)
        return 1
    except OSError as exc:
        print(f"repo_health: error: {exc.strerror or 'io error'}", file=sys.stderr)
        return 2
    report = score(results)
    print(report.to_json() if args.format == "json" else report.to_text())
    if args.min_score is not None and report.total < args.min_score:
        return 1
    return 0


if __name__ == "__main__":  # pragma: no cover
    sys.exit(main())

SKILL.md

tile.json