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.

27.2 KB
Raw Blame
"""Author-familiarity signal for the reviewer (judgment layer only).

Computes how familiar a PR author is with the code their PR touches, from the
trusted checkout's git history plus one `gh` call, or, in the hosted runtime,
from blame and history facts the server reads from GitHub (see
familiarity_from_facts). The result feeds the LLM
reviewer as TRUSTED facts so the ownership norms can treat strong familiarity
like owning-team membership.

Security / safety posture:
- This is a judgment-layer signal ONLY. It never touches the deterministic
  gates (deny, size, dismiss, tier assignment). Absence of the signal leaves
  behavior exactly as before - a one-way ratchet.
- Every external call (the single `gh` call, each `git blame`/`git log`) is
  timed out and failure-tolerant. A gh failure returns None (signal absent).
  A per-file git failure degrades that file to nothing, never a crash.
- All git history is read from the checked-out working tree passed in as
  `repo_root`; the base sha is an ancestor of the checkout, so blame resolves.
"""

import re
import json
import time
import subprocess
from bisect import bisect_right
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath

from gates import _ALL_LOCKFILE_NAMES
from policy import FamiliarityPolicy

# Bounds - keep the work predictable on large PRs.
_GH_TIMEOUT_SECONDS = 30
_GIT_TIMEOUT_SECONDS = 30
_MAX_CHANGED_LINES_PER_FILE = 2000
_MAX_BLAME_FILES = 30
_LOG_SINCE = "18.months"
_SECONDS_PER_DAY = 86400
_TWELVE_MONTHS_DAYS = 365
_TOP_PRIOR_AUTHORS = 2

# PostHog squash-merges; commit subjects end in `(#N)`. Take the last match so a
# subject that mentions another PR mid-text still resolves to its own number.
_SQUASH_PR_RE = re.compile(r"\(#(\d+)\)")

_HUNK_RE = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@")


# ── Public result ────────────────────────────────────────────────


@dataclass(frozen=True)
class AuthorFamiliarity:
    """How familiar the PR author is with the code the PR modifies."""

    band: str  # STRONG / MODERATE / NONE
    blame_overlap_pct: float
    modified_lines_owned: int
    modified_lines_total: int
    prior_prs_in_paths: int
    days_since_last_touch: int | None
    files_prev_count: int
    files_total: int
    capped: bool
    # Files whose blame failed. Their lines count as not owned, so a non-zero value means
    # blame_overlap_pct is a floor rather than a reading.
    blame_incomplete_files: int
    # Display-only hint: top prior authors of the modified lines, by git author
    # name (not login) - used to suggest reviewers when the LLM escalates.
    top_prior_authors: tuple[str, ...]


def familiarity_evidence(fam: AuthorFamiliarity | None) -> dict | None:
    """Serialize an AuthorFamiliarity for the evidence bundle (or null)."""
    if fam is None:
        return None
    return {
        "band": fam.band,
        "blame_overlap_pct": round(fam.blame_overlap_pct, 1),
        "modified_lines_owned": fam.modified_lines_owned,
        "modified_lines_total": fam.modified_lines_total,
        "prior_prs_in_paths": fam.prior_prs_in_paths,
        "days_since_last_touch": fam.days_since_last_touch,
        "files_prev_count": fam.files_prev_count,
        "files_total": fam.files_total,
        "capped": fam.capped,
        "blame_incomplete_files": fam.blame_incomplete_files,
        "top_prior_authors": list(fam.top_prior_authors),
    }


# ── Author's merged-PR set (one gh call) ─────────────────────────


def _fetch_author_pr_numbers(author_login: str, repo: str) -> set[int] | None:
    """The author's merged-PR numbers, or None on any failure (signal absent)."""
    cmd = [
        "gh",
        "pr",
        "list",
        "--repo",
        repo,
        "--author",
        author_login,
        "--state",
        "merged",
        "--limit",
        "1000",
        "--json",
        "number,mergedAt",
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=_GH_TIMEOUT_SECONDS)
    except (OSError, subprocess.SubprocessError):
        return None
    if result.returncode != 0:
        return None
    try:
        data = json.loads(result.stdout)
    except (json.JSONDecodeError, ValueError):
        return None
    if not isinstance(data, list):
        return None
    numbers: set[int] = set()
    for item in data:
        number = item.get("number") if isinstance(item, dict) else None
        if isinstance(number, int) and not isinstance(number, bool):
            numbers.add(number)
    return numbers


def _extract_pr_number(subject: str) -> int | None:
    matches = _SQUASH_PR_RE.findall(subject)
    return int(matches[-1]) if matches else None


# ── Diff parsing (base-side modified lines per file) ─────────────


@dataclass
class _FileDiff:
    old_path: str | None = None
    new_path: str | None = None
    base_modified_lines: list[int] = field(default_factory=list)
    changed_lines: int = 0
    is_binary: bool = False

    @property
    def path(self) -> str:
        return self.new_path or self.old_path or ""


def _strip_diff_path(raw: str) -> str | None:
    raw = raw.strip()
    if raw == "/dev/null":
        return None
    for prefix in ("a/", "b/"):
        if raw.startswith(prefix):
            return raw[len(prefix) :]
    return raw


def _parse_diff(diff_text: str) -> list[_FileDiff]:
    """Parse a unified diff into per-file base-side modified line numbers.

    Only base-side lines the PR deletes/replaces (unified-diff `-` lines) count:
    a pure addition has no base-side lines to blame, which is correct - blame
    overlap measures how much of the code the PR *changes* the author wrote.
    """
    files: list[_FileDiff] = []
    current: _FileDiff | None = None
    seen_hunk = False
    old_line = 0
    for line in diff_text.splitlines():
        if line.startswith("diff --git"):
            if current is not None:
                files.append(current)
            current = _FileDiff()
            seen_hunk = False
            old_line = 0
            continue
        if current is None:
            continue
        if line.startswith("Binary files") or line.startswith("GIT binary patch"):
            current.is_binary = True
            continue
        if not seen_hunk and line.startswith("--- "):
            current.old_path = _strip_diff_path(line[4:])
            continue
        if not seen_hunk and line.startswith("+++ "):
            current.new_path = _strip_diff_path(line[4:])
            continue
        hunk = _HUNK_RE.match(line)
        if hunk:
            seen_hunk = True
            old_line = int(hunk.group(1))
            continue
        if not seen_hunk or not line:
            continue
        tag = line[0]
        if tag == "-":
            current.base_modified_lines.append(old_line)
            current.changed_lines += 1
            old_line += 1
        elif tag == "+":
            current.changed_lines += 1
        elif tag == " ":
            old_line += 1
        # "\ No newline at end of file" and anything else: ignore.
    if current is not None:
        files.append(current)
    return files


def _coalesce(lines: list[int]) -> list[tuple[int, int]]:
    """Sorted, de-duplicated line numbers merged into contiguous (start, end) ranges."""
    ranges: list[tuple[int, int]] = []
    for n in sorted(set(lines)):
        if ranges and n == ranges[-1][1] + 1:
            ranges[-1] = (ranges[-1][0], n)
        else:
            ranges.append((n, n))
    return ranges


def _is_lockfile(file_diff: _FileDiff) -> bool:
    return PurePosixPath(file_diff.path).name.lower() in _ALL_LOCKFILE_NAMES


def _select_considered_files(file_diffs: list[_FileDiff]) -> tuple[list[_FileDiff], bool]:
    """Bound the blame work: drop binaries and lockfiles, skip huge files, cap at 30 (largest first).

    Returns (considered, capped) where capped is True when work was dropped for
    a bound (an oversize file or the 30-file cap) - binaries don't count as
    capping, they carry no reviewable lines.

    Lockfiles don't count either. A package manager writes their lines, so blame
    names whoever last ran the install, which says nothing about the author's
    familiarity. Their history is also the largest a blobless clone has to fetch.
    The server mirrors this selection for its GitHub facts and its blame prefetch
    (`LOCKFILE_NAMES` and `select_considered_files` in the backend's
    logic/familiarity_facts.py). Keep the two in sync.
    """
    blameable = [f for f in file_diffs if not f.is_binary and not _is_lockfile(f)]
    eligible = [f for f in blameable if f.changed_lines <= _MAX_CHANGED_LINES_PER_FILE]
    oversize = any(f.changed_lines > _MAX_CHANGED_LINES_PER_FILE for f in blameable)
    eligible.sort(key=lambda f: f.changed_lines, reverse=True)
    considered = eligible[:_MAX_BLAME_FILES]
    capped = oversize or len(eligible) > _MAX_BLAME_FILES
    return considered, capped


# ── blame overlap ────────────────────────────────────────────────


def _parse_blame_porcelain(text: str) -> list[tuple[str | None, str | None]]:
    """Parse `git blame --line-porcelain` into (author_name, summary) per line."""
    entries: list[tuple[str | None, str | None]] = []
    author: str | None = None
    summary: str | None = None
    for line in text.splitlines():
        if line.startswith("author "):
            author = line[len("author ") :]
        elif line.startswith("summary "):
            summary = line[len("summary ") :]
        elif line.startswith("\t"):
            entries.append((author, summary))
            author = None
            summary = None
    return entries


def _merge_base(base_sha: str, head_sha: str, repo_root: Path) -> str | None:
    """The commit the PR's diff line numbers are relative to.

    The pipeline diffs three-dot (base...head), whose old-side line numbers are
    relative to merge-base(base, head), not the base branch tip. Blame must run
    against the same commit or -L ranges point at shifted lines whenever the
    base branch advanced after the PR branched. None on any error (skip blame).
    """
    cmd = ["git", "merge-base", base_sha, head_sha]
    try:
        result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True, timeout=_GIT_TIMEOUT_SECONDS)
    except (OSError, subprocess.SubprocessError):
        return None
    if result.returncode != 0:
        return None
    return result.stdout.strip() or None


def _blame_file(
    blame_sha: str, path: str, ranges: list[tuple[int, int]], repo_root: Path
) -> list[tuple[str | None, str | None]] | None:
    """Blame all of one file's base-side ranges in a single invocation.

    git blame accepts repeated -L flags, so the subprocess count is one per
    file, not one per hunk. None on any error (degrade this file).
    """
    range_flags = [flag for start, end in ranges for flag in ("-L", f"{start},{end}")]
    cmd = ["git", "blame", blame_sha, *range_flags, "--line-porcelain", "--", path]
    try:
        result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True, timeout=_GIT_TIMEOUT_SECONDS)
    except (OSError, subprocess.SubprocessError):
        return None
    if result.returncode != 0:
        return None
    return _parse_blame_porcelain(result.stdout)


@dataclass(frozen=True)
class _BlameOverlap:
    """How much of the code a PR changes was written by its author.

    The two line counts share a type, so they are named rather than returned as a pair: swapping
    them silently inverts the signal the STRONG band reads.
    """

    owned_lines: int
    total_lines: int
    # Files whose blame failed. Their lines count towards total_lines and never towards
    # owned_lines, so the percentage is a floor whenever this is non-zero.
    incomplete_files: int
    # Display-only: top prior authors of the lines the PR author does not own.
    top_prior_authors: tuple[str, ...]


def _blame_overlap(considered: list[_FileDiff], blame_sha: str, author_prs: set[int], repo_root: Path) -> _BlameOverlap:
    owned = 0
    total = 0
    incomplete = 0
    author_line_counts: Counter[str] = Counter()
    for file_diff in considered:
        blame_path = file_diff.old_path
        if not blame_path:
            continue
        ranges = _coalesce(file_diff.base_modified_lines)
        if not ranges:
            continue
        entries = _blame_file(blame_sha, blame_path, ranges, repo_root)
        if entries is None:
            # A file whose blame fails still owes its lines to the denominator. Dropping it from
            # both sides would let unread evidence raise the percentage; charging the lines as
            # unowned can only lower it, which is the direction the signal may safely be wrong in.
            total += sum(end - start + 1 for start, end in ranges)
            incomplete += 1
            continue
        for author_name, summary in entries:
            total += 1
            pr_number = _extract_pr_number(summary or "")
            if pr_number is not None and pr_number in author_prs:
                owned += 1
            elif author_name:
                # Reviewer-suggestion hint: count only lines the PR author does
                # NOT own, since suggesting the author to themselves is noise.
                author_line_counts[author_name] += 1
    return _BlameOverlap(
        owned_lines=owned,
        total_lines=total,
        incomplete_files=incomplete,
        top_prior_authors=tuple(name for name, _ in author_line_counts.most_common(_TOP_PRIOR_AUTHORS)),
    )


# ── prior PRs / last touch / previously-modified files ───────────


def _path_specs(paths: list[str]) -> list[str]:
    """Directory pathspecs for the changed files (a root-level file maps to itself)."""
    specs: set[str] = set()
    for path in paths:
        parent = str(PurePosixPath(path).parent)
        specs.add(path if parent == "." else parent)
    return sorted(specs)


def _prior_prs_in_paths(paths: list[str], author_prs: set[int], repo_root: Path, now: float) -> tuple[int, int | None]:
    """(author's merged PRs touching these paths in 12 months, days since last touch)."""
    specs = _path_specs(paths)
    if not specs:
        return 0, None
    cmd = ["git", "log", f"--since={_LOG_SINCE}", "--format=%ct%x09%s", "--", *specs]
    try:
        result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True, timeout=_GIT_TIMEOUT_SECONDS)
    except (OSError, subprocess.SubprocessError):
        return 0, None
    if result.returncode != 0:
        return 0, None

    cutoff = now - _TWELVE_MONTHS_DAYS * _SECONDS_PER_DAY
    prs_recent: set[int] = set()
    last_touch: int | None = None
    for line in result.stdout.splitlines():
        if "\t" not in line:
            continue
        ct_str, subject = line.split("\t", 1)
        try:
            commit_time = int(ct_str)
        except ValueError:
            continue
        pr_number = _extract_pr_number(subject)
        if pr_number is None or pr_number not in author_prs:
            continue
        if last_touch is None or commit_time > last_touch:
            last_touch = commit_time
        if commit_time >= cutoff:
            prs_recent.add(pr_number)

    days_since = int((now - last_touch) // _SECONDS_PER_DAY) if last_touch is not None else None
    return len(prs_recent), days_since


def _files_previously_modified(considered: list[_FileDiff], author_prs: set[int], repo_root: Path) -> tuple[int, int]:
    """(changed files the author previously modified, total changed files considered).

    One batched `git log --name-only` over all paths instead of a subprocess
    per file; the author "previously modified" a file when any of their merged
    PRs touched it within the log window. Matches on both the old and new path
    of a renamed file, since `git log --name-only -- <new_path>` alone misses
    commits recorded under the pre-rename name - the file itself still counts
    once towards the total either way.

    ``--no-renames``: rename detection compares blob contents, and on a blobless checkout that is a
    fetch per commit. The old/new path union above already covers renames, so the detection only
    buys latency.
    """
    if not considered:
        return 0, 0
    all_paths = sorted({p for f in considered for p in (f.old_path, f.new_path) if p})
    if not all_paths:
        return 0, len(considered)
    cmd = ["git", "log", f"--since={_LOG_SINCE}", "--format=%x01%s", "--name-only", "--no-renames", "--", *all_paths]
    try:
        result = subprocess.run(cmd, cwd=repo_root, capture_output=True, text=True, timeout=_GIT_TIMEOUT_SECONDS)
    except (OSError, subprocess.SubprocessError):
        return 0, len(considered)
    if result.returncode != 0:
        return 0, len(considered)

    wanted = set(all_paths)
    touched: set[str] = set()
    current_is_authors = False
    for line in result.stdout.splitlines():
        if line.startswith("\x01"):
            pr_number = _extract_pr_number(line[1:])
            current_is_authors = pr_number is not None and pr_number in author_prs
        elif line and current_is_authors and line in wanted:
            touched.add(line)
    owned_count = sum(1 for f in considered if (f.old_path in touched) or (f.new_path in touched))
    return owned_count, len(considered)


# ── Band ─────────────────────────────────────────────────────────


def _band(
    blame_overlap_pct: float,
    prior_prs_in_paths: int,
    days_since_last_touch: int | None,
    thresholds: FamiliarityPolicy,
) -> str:
    """STRONG / MODERATE / NONE from the policy thresholds (numbers-only diff to tune)."""
    if blame_overlap_pct >= thresholds.strong.min_blame_overlap_pct:
        return "STRONG"

    moderate = thresholds.moderate
    if (
        prior_prs_in_paths >= moderate.min_prior_prs
        and days_since_last_touch is not None
        and days_since_last_touch <= moderate.max_days_since_touch
    ):
        return "MODERATE"
    return "NONE"


# ── Server-collected facts (hosted runtime) ──────────────────────
#
# The hosted server reads blame and path history from GitHub's GraphQL API, so the sandbox
# checkout needs no history. The facts are raw: a commit table, the commit that last touched each
# blamed base-side line range, and the author's commits in the changed paths. All matching,
# counting and banding happens here, with the same bounds and thresholds as the git path.


@dataclass(frozen=True)
class _AuthorIdentity:
    """Decides whether a commit from the server's facts belongs to the PR author.

    GitHub's blame follows renames and copies, so it often names a different commit than
    `git blame` for the same line, but it names the same person. The commit author's GitHub login
    is therefore the primary match. The squash-merge `(#N)` subject is the fallback for a commit
    whose author email links to no GitHub account.
    """

    login: str
    pr_numbers: frozenset[int]

    def owns(self, commit: dict) -> bool:
        commit_login = commit.get("login")
        if commit_login:
            return str(commit_login).lower() == self.login.lower()
        pr_number = _extract_pr_number(str(commit.get("subject") or ""))
        return pr_number is not None and pr_number in self.pr_numbers


def _commit_for_line(line: int, blame_ranges: list[dict], starts: list[int], commits: dict) -> dict | None:
    """The commit of the range covering ``line``, by binary search over ranges sorted by start.

    Blame ranges never overlap, so the last range that starts at or before the line is the only
    candidate.
    """
    index = bisect_right(starts, line) - 1
    if index < 0 or line > blame_ranges[index].get("end", -1):
        return None
    return commits.get(blame_ranges[index].get("oid"))


def _blame_overlap_from_facts(considered: list[_FileDiff], facts: dict, identity: _AuthorIdentity) -> _BlameOverlap:
    """_blame_overlap with the server's blame ranges in place of `git blame`.

    A considered file that has no blame in the facts failed or was skipped on the server. Its
    lines count as not owned, the same as a failed `git blame` on the git path.
    """
    blame = facts.get("blame") or {}
    commits = facts.get("commits") or {}
    owned = 0
    total = 0
    incomplete = 0
    author_line_counts: Counter[str] = Counter()
    for file_diff in considered:
        blame_path = file_diff.old_path
        if not blame_path:
            continue
        ranges = _coalesce(file_diff.base_modified_lines)
        if not ranges:
            continue
        line_count = sum(end - start + 1 for start, end in ranges)
        if blame_path not in blame:
            total += line_count
            incomplete += 1
            continue
        file_blame = sorted(blame[blame_path], key=lambda blame_range: blame_range.get("start", 0))
        starts = [blame_range.get("start", 0) for blame_range in file_blame]
        for start, end in ranges:
            for line in range(start, end + 1):
                total += 1
                commit = _commit_for_line(line, file_blame, starts, commits)
                if commit is None:
                    continue
                if identity.owns(commit):
                    owned += 1
                elif commit.get("name"):
                    author_line_counts[str(commit["name"])] += 1
    return _BlameOverlap(
        owned_lines=owned,
        total_lines=total,
        incomplete_files=incomplete,
        top_prior_authors=tuple(name for name, _ in author_line_counts.most_common(_TOP_PRIOR_AUTHORS)),
    )


def _prior_prs_from_facts(facts: dict, identity: _AuthorIdentity, now: float) -> tuple[int, int | None]:
    """_prior_prs_in_paths over the server's path history. Only commits that name a PR count."""
    commits = facts.get("commits") or {}
    cutoff = now - _TWELVE_MONTHS_DAYS * _SECONDS_PER_DAY
    prs_recent: set[int] = set()
    last_touch: int | None = None
    for oid in facts.get("path_history") or []:
        commit = commits.get(oid)
        if commit is None or not identity.owns(commit):
            continue
        pr_number = _extract_pr_number(str(commit.get("subject") or ""))
        if pr_number is None:
            continue
        commit_time = int(commit.get("committed_at") or 0)
        if last_touch is None or commit_time > last_touch:
            last_touch = commit_time
        if commit_time >= cutoff:
            prs_recent.add(pr_number)
    days_since = int((now - last_touch) // _SECONDS_PER_DAY) if last_touch is not None else None
    return len(prs_recent), days_since


def _files_previously_modified_from_facts(considered: list[_FileDiff], facts: dict, identity: _AuthorIdentity) -> int:
    """_files_previously_modified over the server's per-file history, matched on old and new path."""
    commits = facts.get("commits") or {}
    file_history = facts.get("file_history") or {}
    touched = {
        path
        for path, oids in file_history.items()
        if any(oid in commits and identity.owns(commits[oid]) for oid in oids)
    }
    return sum(1 for f in considered if (f.old_path in touched) or (f.new_path in touched))


# ── Orchestration ────────────────────────────────────────────────


def _read_diff(diff_path: Path) -> str:
    try:
        return diff_path.read_text()
    except OSError:
        return ""


def compute_familiarity(
    author_login: str,
    diff_path: Path,
    base_sha: str,
    head_sha: str,
    repo: str,
    repo_root: Path,
    thresholds: FamiliarityPolicy,
    *,
    now: float | None = None,
) -> AuthorFamiliarity | None:
    """Compute the author's familiarity with the code the PR modifies.

    Returns None only when the signal is genuinely absent (the gh call failed);
    every other degradation yields a populated result (possibly band NONE), so
    the reviewer sees either a trustworthy fact or nothing at all.
    """
    author_prs = _fetch_author_pr_numbers(author_login, repo)
    if author_prs is None:
        return None

    now = time.time() if now is None else now
    file_diffs = _parse_diff(_read_diff(diff_path))
    considered, capped = _select_considered_files(file_diffs)
    considered_paths = [f.path for f in considered if f.path]

    blame_sha = _merge_base(base_sha, head_sha, repo_root)
    overlap = (
        _blame_overlap(considered, blame_sha, author_prs, repo_root)
        if blame_sha is not None
        else _BlameOverlap(owned_lines=0, total_lines=0, incomplete_files=0, top_prior_authors=())
    )
    blame_overlap_pct = (100.0 * overlap.owned_lines / overlap.total_lines) if overlap.total_lines else 0.0

    prior_prs, days_since = _prior_prs_in_paths(considered_paths, author_prs, repo_root, now)
    files_prev_count, files_total = _files_previously_modified(considered, author_prs, repo_root)

    band = _band(blame_overlap_pct, prior_prs, days_since, thresholds)

    return AuthorFamiliarity(
        band=band,
        blame_overlap_pct=blame_overlap_pct,
        modified_lines_owned=overlap.owned_lines,
        modified_lines_total=overlap.total_lines,
        prior_prs_in_paths=prior_prs,
        days_since_last_touch=days_since,
        files_prev_count=files_prev_count,
        files_total=files_total,
        capped=capped,
        blame_incomplete_files=overlap.incomplete_files,
        top_prior_authors=overlap.top_prior_authors,
    )


def familiarity_from_facts(
    facts: dict,
    author_login: str,
    author_prs: set[int],
    diff_path: Path,
    thresholds: FamiliarityPolicy,
    *,
    now: float | None = None,
) -> AuthorFamiliarity:
    """compute_familiarity with the server's GitHub facts in place of git history and `gh`.

    File selection, line mapping, and the band come from the local diff and the same helpers as
    the git path, so the two paths differ only in where blame and history come from. The band
    thresholds were calibrated on `git blame`, which attributes lines differently from GitHub's
    blame (see _AuthorIdentity).
    """
    now = time.time() if now is None else now
    identity = _AuthorIdentity(login=author_login, pr_numbers=frozenset(author_prs))
    file_diffs = _parse_diff(_read_diff(diff_path))
    considered, capped = _select_considered_files(file_diffs)

    overlap = _blame_overlap_from_facts(considered, facts, identity)
    blame_overlap_pct = (100.0 * overlap.owned_lines / overlap.total_lines) if overlap.total_lines else 0.0
    prior_prs, days_since = _prior_prs_from_facts(facts, identity, now)
    files_prev_count = _files_previously_modified_from_facts(considered, facts, identity)
    files_total = len(considered)
    band = _band(blame_overlap_pct, prior_prs, days_since, thresholds)

    return AuthorFamiliarity(
        band=band,
        blame_overlap_pct=blame_overlap_pct,
        modified_lines_owned=overlap.owned_lines,
        modified_lines_total=overlap.total_lines,
        prior_prs_in_paths=prior_prs,
        days_since_last_touch=days_since,
        files_prev_count=files_prev_count,
        files_total=files_total,
        capped=capped,
        blame_incomplete_files=overlap.incomplete_files,
        top_prior_authors=overlap.top_prior_authors,
    )