Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): self-validate the score against each repo's bug history (#438)
Raghav Chamadiya85b0b56fb12f
diff --git a/README.md b/README.mdindex cd248afb5..9ed443a18 100644--- a/README.md+++ b/README.md@@ -102,6 +102,12 @@ repowise health --refactoring-targets # ranked by impact / effortrepowise health --trend # snapshots + declining / predicted-decline alerts```+And it proves itself on *your* repo, not just a benchmark: after every index,+repowise checks its own flags against your git history and reports the hit rate+in the terminal and on the dashboard — *"16/20 lowest-health files had a bug fix+in the last 6 months, 3.3x the 24% baseline"*. See+[Does the score find the bugs?](docs/CODE_HEALTH.md#does-the-score-find-the-bugs).+**Does the score actually find bugs? Yes — and it out-ranks the leadingcommercial code-health tool.** On the **same 2,770 files across 9 languages**,scored at the same leakage-free commit against the same defect labels:diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex a937c5948..99506f150 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -66,6 +66,31 @@ The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:- **Average Health** — NLOC-weighted average over all files.- **Worst Performer** — single lowest-scoring file.+## Does the score find the bugs?++The score is only worth anything if the files it flags are the files that+actually break. After an index, repowise checks that against the repo's own+history and prints a one-line callout:++```+Does the score find the bugs? 16/20 lowest-health files had a bug fix in the+last 6 months, 3.3x the 24% baseline (80% vs 24%).+```++It ranks every file by health score, takes the 20 lowest, and counts how many+were touched by a `fix:` commit in the trailing ~180-day window (the same+signal the `prior_defect` biomarker uses). That precision is contrasted with+the repo-wide base rate — the fraction of *all* files with a recent fix — to+give the lift. The same number appears on the web `health` and `overview`+dashboards, where it expands into a per-K table (worst 10/20/30), a+concentration stat (what share of recently-fixed files fall in the+least-healthy 20%), and the exact flagged files.++It stays silent on repos without enough history to be honest (fewer than 25+scored files, or fewer than 5 recently-fixed files). One caveat it discloses:+`prior_defect` is itself one (down-weighted) input to the score, so this is an+association on the indexed history, not a leakage-free forward prediction.+## The biomarkers**brain_method** — A single function that is simultaneously long, deeplydiff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.pyindex 46fe70b14..b1aac3578 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from typing import Anyimport clickfrom rich.table import Table@@ -338,6 +339,8 @@ def health_command(f"({kpis.get('worst_performer_path', 'n/a')})\n")+ _render_defect_accuracy_line(report)+table = Table(title=f"Lowest-scoring files ({min(len(metrics_sorted), 20)})")table.add_column("File", style="cyan")table.add_column("Score", justify="right")@@ -376,6 +379,40 @@ def health_command(console.print(f_table)+def _render_defect_accuracy_line(report: Any) -> None:+ """One-line "does the score find the bugs?" validation, or nothing.++ Silent when there isn't enough history for an honest number (the core+ compute returns ``None``).+ """+ try:+ from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy++ stat = compute_defect_accuracy(report.metrics, report.findings)+ except Exception:+ return+ if not stat:+ return++ months = max(1, round(stat["window_days"] / 30))+ window = "month" if months == 1 else f"{months} months"+ line = (+ f"[dim]Does the score find the bugs? [/dim]"+ f"[bold]{stat['hits']}/{stat['k']}[/bold]"+ f"[dim] lowest-health files had a bug fix in the last {window}[/dim]"+ )+ if stat.get("lift") is not None:+ base_pct = round(stat["base_rate"] * 100)+ prec_pct = round(stat["precision"] * 100)+ line += (+ f"[dim], [/dim][bold]{stat['lift']}x[/bold]"+ f"[dim] the {base_pct}% baseline ({prec_pct}% vs {base_pct}%).[/dim]"+ )+ else:+ line += "[dim].[/dim]"+ console.print(line + "\n")++def _effort_bucket(nloc: int) -> tuple[str, int]:if nloc <= 40:return "S", 1diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.pyindex abdbe2a5d..9d648fee9 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd/reporting.py@@ -73,6 +73,41 @@ def show_analysis_summary(result: Any) -> None:)+def _render_defect_accuracy(result: Any) -> None:+ """Print a one-line "does the score find the bugs?" validation callout.++ Stays silent unless the health analysis ran and the repo has enough files+ and recent bug-fix history for an honest number (the core compute returns+ ``None`` otherwise).+ """+ report = getattr(result, "health_report", None)+ if report is None:+ return+ try:+ from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy++ stat = compute_defect_accuracy(report.metrics, report.findings)+ except Exception:+ return+ if not stat:+ return++ months = max(1, round(stat["window_days"] / 30))+ window = "month" if months == 1 else f"{months} months"+ line = (+ f" [dim]Health check: [/dim]"+ f"[bold]{stat['hits']}/{stat['k']}[/bold]"+ f"[dim] lowest-health files had a bug fix in the last {window}[/dim]"+ )+ if stat.get("lift") is not None:+ base_pct = round(stat["base_rate"] * 100)+ line += f"[dim], [/dim][bold]{stat['lift']}x[/bold][dim] the {base_pct}% baseline.[/dim]"+ else:+ line += "[dim].[/dim]"+ console.print(line)+ console.print()++def show_completion(*,repo_path: Any,@@ -163,6 +198,7 @@ def show_completion(build_completion_panel("repowise index complete", metrics, next_steps=next_steps))console.print()+ _render_defect_accuracy(result)else:total_tokens = sum(p.total_tokens for p in (result.generated_pages or []))metrics = [@@ -198,6 +234,7 @@ def show_completion(build_completion_panel("repowise init complete", metrics, next_steps=next_steps))console.print()+ _render_defect_accuracy(result)console.print(format_setup_instructions(repo_path))console.print()diff --git a/packages/core/src/repowise/core/analysis/health/defect_accuracy.py b/packages/core/src/repowise/core/analysis/health/defect_accuracy.pynew file mode 100644index 000000000..3d138b9f8--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/defect_accuracy.py@@ -0,0 +1,116 @@+"""Does the score actually find the buggy files?++A small, interpretable self-validation of the health score, computed purely+from the metrics + findings the analyzer already produced — no git pass, no+extra artifact, no re-index.++Label: a file is "recently bug-fixed" when it carries a ``prior_defect``+biomarker (the indexer attributes Conventional-Commit ``fix:`` commits in a+~180-day window to the files they touched). We then ask: of the K+lowest-health files, how many were recently bug-fixed, vs. the repo-wide base+rate. ``prior_defect`` is one (down-weighted) input to the score, so this is an+association on the indexed history, not a leakage-free forward prediction — the+UI/CLI disclose that.++The two inputs are duck-typed: each entry may be a mapping (``m["score"]``) or+an object with attributes (``m.score``), so the same function serves the server+(dict rows), the CLI (``HealthFileMetricData`` / ``HealthFindingData``), and the+hosted backend (``health.json`` dicts) without per-call-site adapters.+"""++from __future__ import annotations++from typing import Any++_DEFAULT_K = 20+_MIN_FILES = 25 # below this a precision@K headline is noise+_MIN_DEFECT_FILES = 5 # need a real positive class to divide by+_DEFAULT_WINDOW_DAYS = 180+++def _get(obj: Any, key: str, default: Any = None) -> Any:+ """Read ``key`` from a mapping or an attribute-bearing object."""+ if isinstance(obj, dict):+ return obj.get(key, default)+ return getattr(obj, key, default)+++def _recent_fix_counts(findings: list[Any]) -> tuple[dict[str, int], int]:+ """Map file_path -> recent bug-fix count, plus the window in days."""+ counts: dict[str, int] = {}+ window_days = _DEFAULT_WINDOW_DAYS+ for f in findings:+ if _get(f, "biomarker_type") != "prior_defect":+ continue+ details = _get(f, "details") or {}+ path = _get(f, "file_path", "")+ counts[path] = int(details.get("prior_defect_count", 1) or 1)+ window_days = int(details.get("window_days", window_days) or window_days)+ counts.pop("", None)+ return counts, window_days+++def compute_defect_accuracy(+ metrics: list[Any],+ findings: list[Any],+ *,+ k: int = _DEFAULT_K,+) -> dict[str, Any] | None:+ """Precision-style accuracy summary, or ``None`` when there isn't enough+ signal to show an honest number (too few files / too few defects)."""+ scored = [m for m in metrics if _get(m, "file_path")]+ n = len(scored)+ fix_counts, window_days = _recent_fix_counts(findings)+ total_defect_files = sum(+ 1 for m in scored if fix_counts.get(_get(m, "file_path"), 0) > 0+ )++ if n < _MIN_FILES or total_defect_files < _MIN_DEFECT_FILES:+ return None++ ranked = sorted(scored, key=lambda m: float(_get(m, "score", 10.0)))++ def hits_in(top: list[Any]) -> int:+ return sum(1 for m in top if fix_counts.get(_get(m, "file_path"), 0) > 0)++ kk = min(k, n)+ hits = hits_in(ranked[:kk])+ base_rate = total_defect_files / n+ precision = hits / kk++ # Concentration: share of all recently-fixed files that fall in the+ # least-healthy 20% — the "something to think about" Pareto stat.+ k_conc = max(1, round(n * 0.20))+ conc_share = hits_in(ranked[:k_conc]) / total_defect_files++ # Per-K table for the dig-deeper breakdown.+ table = [+ {"k": kx, "hits": hits_in(ranked[:kx])}+ for kx in (10, 20, 30)+ if kx <= n+ ]++ # The flagged files themselves, for a bulletproof drill-down.+ sample = [+ {+ "file_path": _get(m, "file_path"),+ "score": round(float(_get(m, "score", 10.0)), 2),+ "recent_fixes": fix_counts.get(_get(m, "file_path"), 0),+ }+ for m in ranked[:kk]+ ]++ return {+ "k": kk,+ "hits": hits,+ "precision": round(precision, 4),+ "base_rate": round(base_rate, 4),+ "lift": round(precision / base_rate, 2) if base_rate else None,+ "window_days": window_days,+ "scored_files": n,+ "defect_files": total_defect_files,+ "concentration_file_fraction": 0.20,+ "concentration_defect_share": round(conc_share, 4),+ "precision_table": table,+ "flagged_files": sample,+ }diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.pyindex 2dc95ea49..1d1b11808 100644--- a/packages/server/src/repowise/server/routers/code_health.py+++ b/packages/server/src/repowise/server/routers/code_health.py@@ -15,6 +15,7 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom pydantic import BaseModel, Fieldfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracyfrom repowise.core.analysis.health.models import Severityfrom repowise.core.analysis.health.scoring import (CATEGORY_CAPS,@@ -161,8 +162,17 @@ async def health_overview("severity_breakdown": _severity_breakdown(findings),}+ # "Does the score find the bugs?" self-validation, derived from the same+ # metrics + findings (prior_defect biomarker) already loaded above. ``None``+ # when the repo lacks enough files / defect history to be honest.+ defect_accuracy = compute_defect_accuracy(+ [_metric_to_dict(m) for m in metrics],+ [_finding_to_dict(f) for f in findings],+ )+return {"summary": summary,+ "defect_accuracy": defect_accuracy,"files": [_metric_to_dict(m) for m in metrics[:limit]],"top_findings": [_finding_to_dict(f) for f in findings[:limit]],"modules": _module_rollups(metrics),diff --git a/packages/ui/src/health/defect-accuracy-card.tsx b/packages/ui/src/health/defect-accuracy-card.tsxnew file mode 100644index 000000000..641332f28--- /dev/null+++ b/packages/ui/src/health/defect-accuracy-card.tsx@@ -0,0 +1,170 @@+"use client";++import { useState } from "react";+import { Check, Minus, Target, HelpCircle } from "lucide-react";+import { Card } from "../ui/card";++export interface DefectAccuracyFile {+ file_path: string;+ score: number;+ recent_fixes: number;+}++export interface DefectAccuracyPoint {+ k: number;+ hits: number;+}++export interface DefectAccuracy {+ k: number;+ hits: number;+ precision: number;+ base_rate: number;+ lift: number | null;+ window_days: number;+ scored_files: number;+ defect_files: number;+ concentration_file_fraction: number;+ concentration_defect_share: number;+ precision_table: DefectAccuracyPoint[];+ flagged_files: DefectAccuracyFile[];+}++/**+ * "Does the score actually find the buggy files?" card.+ *+ * Of the K lowest-health files, how many were touched by a bug-fix commit+ * in the recent window (`prior_defect` biomarker). We contrast that+ * precision against the repo-wide base rate (the lift) and let the user+ * expand a bulletproof breakdown: the per-K table, the concentration stat,+ * the exact flagged files, and an honest note on what the number is.+ *+ * The backend computes it from the same metrics + findings the page already+ * loads (`health/overview` -> `defect_accuracy`); it is null when the repo+ * lacks enough files or defect history to be honest, in which case the+ * caller should render nothing.+ */+export function DefectAccuracyCard({ data }: { data: DefectAccuracy }) {+ const [open, setOpen] = useState(false);++ const months = Math.max(1, Math.round(data.window_days / 30));+ const windowLabel = months === 1 ? "month" : `${months} months`;+ const pct = Math.round(data.precision * 100);+ const basePct = Math.round(data.base_rate * 100);+ const concPct = Math.round(data.concentration_defect_share * 100);+ const concFilePct = Math.round(data.concentration_file_fraction * 100);++ return (+ <Card className="p-4">+ <div className="flex items-start justify-between gap-3">+ <div className="flex items-center gap-2">+ <Target className="h-4 w-4 text-[var(--color-accent-primary)]" aria-hidden />+ <h3 className="text-sm font-medium text-[var(--color-text-primary)]">+ Does the health score find the bugs?+ </h3>+ </div>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] hover:text-[var(--color-accent-primary)] transition shrink-0"+ aria-expanded={open}+ aria-controls="defect-accuracy-breakdown"+ >+ <HelpCircle className="h-3 w-3" aria-hidden />+ {open ? "Hide" : "How?"}+ </button>+ </div>++ {/* Headline */}+ <div className="mt-3 flex flex-wrap items-baseline gap-x-2 gap-y-1">+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">+ {data.hits} / {data.k}+ </span>+ <span className="text-sm text-[var(--color-text-secondary)]">+ of the lowest-health files had a bug fix in the last {windowLabel}+ </span>+ </div>++ {data.lift != null && (+ <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">+ That's{" "}+ <span className="font-semibold text-[var(--color-accent-primary)]">+ {data.lift}× the repo's {basePct}% baseline+ </span>{" "}+ — a random file has a {basePct}% chance; a file the score flags has {pct}%.+ </p>+ )}++ {open && (+ <div+ id="defect-accuracy-breakdown"+ className="mt-3 space-y-3 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-3 text-xs"+ >+ <p className="leading-snug text-[var(--color-text-secondary)]">+ We rank every file by its health score, then check how many of the+ worst were touched by a bug-fix commit in the last {windowLabel}+ {" "}(from this repo's own git history).+ </p>++ {/* Per-K precision table */}+ <div className="space-y-1">+ {data.precision_table.map((row) => (+ <div key={row.k} className="flex items-center justify-between">+ <span className="text-[var(--color-text-tertiary)]">+ Worst {row.k} files+ </span>+ <span className="tabular-nums text-[var(--color-text-primary)]">+ {row.hits}/{row.k} were bug-fixed+ </span>+ </div>+ ))}+ </div>++ {/* Concentration */}+ <p className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 py-1.5 leading-snug text-[var(--color-text-secondary)]">+ The least-healthy <strong>{concFilePct}%</strong> of files contain{" "}+ <strong>{concPct}%</strong> of every recently bug-fixed file.+ </p>++ {/* Flagged files drill-down */}+ {data.flagged_files.length > 0 && (+ <div className="space-y-1">+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ The {data.k} flagged files+ </p>+ <ul className="max-h-48 space-y-0.5 overflow-y-auto pr-1">+ {data.flagged_files.map((f) => (+ <li+ key={f.file_path}+ className="flex items-center justify-between gap-2"+ >+ <span className="flex min-w-0 items-center gap-1.5">+ {f.recent_fixes > 0 ? (+ <Check className="h-3 w-3 shrink-0 text-[var(--color-success)]" aria-label="bug-fixed" />+ ) : (+ <Minus className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" aria-label="no recent fix" />+ )}+ <span className="truncate font-mono text-[11px] text-[var(--color-text-secondary)]">+ {f.file_path}+ </span>+ </span>+ <span className="shrink-0 tabular-nums text-[10px] text-[var(--color-text-tertiary)]">+ {f.score.toFixed(1)}+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}++ <p className="text-[10px] leading-snug text-[var(--color-text-tertiary)]">+ Based on {data.defect_files} recently bug-fixed files out of{" "}+ {data.scored_files} scored. This is an association on the indexed+ history, not a forward prediction — recent bug-fix history is one of+ the score's many inputs.+ </p>+ </div>+ )}+ </Card>+ );+}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex 22a719516..1523cd01b 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -26,3 +26,4 @@ export * from "./ai-prompt-modal";export * from "./hot-functions-panel";export * from "./hidden-coupling-list";export * from "./recalibration-banner";+export * from "./defect-accuracy-card";diff --git a/packages/web/src/app/repos/[id]/health/page.tsx b/packages/web/src/app/repos/[id]/health/page.tsxindex 71ca7c90e..d33a70bd7 100644--- a/packages/web/src/app/repos/[id]/health/page.tsx+++ b/packages/web/src/app/repos/[id]/health/page.tsx@@ -14,6 +14,7 @@ import {HotFunctionsPanel,HiddenCouplingList,RecalibrationBanner,+ DefectAccuracyCard,type FileSortField,type Severity,} from "@repowise-dev/ui/health";@@ -176,6 +177,10 @@ export default function HealthPage() {hotspotDelta={trend?.summary?.hotspot_delta ?? undefined}/>+ {overview.defect_accuracy ? (+ <DefectAccuracyCard data={overview.defect_accuracy} />+ ) : null}+<div className="grid grid-cols-1 lg:grid-cols-3 gap-6"><div className="lg:col-span-2 space-y-3"><div className="flex flex-wrap items-center gap-2">diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsxindex 39fd3edf0..3607b9eaf 100644--- a/packages/web/src/app/repos/[id]/overview/page.tsx+++ b/packages/web/src/app/repos/[id]/overview/page.tsx@@ -8,10 +8,12 @@ import { listDecisions, getDecisionHealth } from "@/lib/api/decisions";import { getGraph, getModuleGraph, getCommunities, getExecutionFlows } from "@/lib/api/graph";import { getProviders } from "@/lib/api/providers";import { getDistillSavings } from "@/lib/api/costs";+import { getHealthOverview } from "@/lib/api/code-health";import { listJobs } from "@/lib/api/jobs";import { getKnowledgeMap } from "@/lib/api/knowledge-map";import { Badge } from "@repowise-dev/ui/ui/badge";import { StatCard } from "@repowise-dev/ui/shared/stat-card";+import { DefectAccuracyCard } from "@repowise-dev/ui/health";import { HealthScoreRing } from "@repowise-dev/ui/dashboard/health-score-ring";import { AttentionPanel } from "@repowise-dev/ui/dashboard/attention-panel";import { QuickActionsWrapper as QuickActions } from "@/components/dashboard/quick-actions-wrapper";@@ -63,7 +65,7 @@ export default async function OverviewPage({ params }: Props) {if (!repo) notFound();// Fetch all data in parallel — each independently failable- const [stats, gitSummary, hotspots, ownership, deadCodeSummary, deadCodeSafe, decisions, decisionHealth, graph, moduleGraph, providers, completedJobs, knowledgeMap, communities, executionFlows, distillSavings] =+ const [stats, gitSummary, hotspots, ownership, deadCodeSummary, deadCodeSafe, decisions, decisionHealth, graph, moduleGraph, providers, completedJobs, knowledgeMap, communities, executionFlows, distillSavings, healthOverview] =await Promise.all([safeFetch(() => getRepoStats(id)),safeFetch(() => getGitSummary(id)),@@ -81,6 +83,7 @@ export default async function OverviewPage({ params }: Props) {safeFetch(() => getCommunities(id)),safeFetch(() => getExecutionFlows(id, { top_n: 5, max_depth: 5 })),safeFetch(() => getDistillSavings(id)),+ safeFetch(() => getHealthOverview(id, 25)),]);// Find timestamps for last sync and last full re-index from completed jobs@@ -203,6 +206,11 @@ export default async function OverviewPage({ params }: Props) {</div></div>+ {/* ── Does the health score find the bugs? — self-validation ── */}+ {healthOverview?.defect_accuracy ? (+ <DefectAccuracyCard data={healthOverview.defect_accuracy} />+ ) : null}+{/* ── At a glance: what needs eyes now ── */}<div className="grid grid-cols-1 gap-4 lg:grid-cols-3"><div className="lg:col-span-2">diff --git a/packages/web/src/lib/api/code-health.ts b/packages/web/src/lib/api/code-health.tsindex d5a42415b..9d0f60789 100644--- a/packages/web/src/lib/api/code-health.ts+++ b/packages/web/src/lib/api/code-health.ts@@ -1,5 +1,8 @@+import type { DefectAccuracy } from "@repowise-dev/ui/health";import { apiGet, apiPatch } from "./client";+export type { DefectAccuracy } from "@repowise-dev/ui/health";+export interface HealthFileMetric {file_path: string;score: number;@@ -54,6 +57,7 @@ export interface HealthOverviewResponse {open_findings: number;severity_breakdown?: { critical: number; high: number; medium: number; low: number };};+ defect_accuracy?: DefectAccuracy | null;files: HealthFileMetric[];top_findings: HealthFinding[];modules?: HealthModuleRow[];diff --git a/tests/unit/health/test_defect_accuracy.py b/tests/unit/health/test_defect_accuracy.pynew file mode 100644index 000000000..d458c5074--- /dev/null+++ b/tests/unit/health/test_defect_accuracy.py@@ -0,0 +1,70 @@+"""Tests for the "does the score find the bugs?" self-validation stat."""++from __future__ import annotations++from repowise.core.analysis.health.defect_accuracy import compute_defect_accuracy+++def _metrics(n: int) -> list[dict]:+ # Ascending score == ascending health; index i is the i-th lowest-health file.+ return [{"file_path": f"f{i}.py", "score": float(i)} for i in range(n)]+++def _fix(path: str, count: int = 1, window_days: int = 180) -> dict:+ return {+ "biomarker_type": "prior_defect",+ "file_path": path,+ "details": {"prior_defect_count": count, "window_days": window_days},+ }+++def test_returns_none_without_enough_files() -> None:+ metrics = _metrics(10)+ findings = [_fix(f"f{i}.py") for i in range(5)]+ assert compute_defect_accuracy(metrics, findings) is None+++def test_returns_none_without_enough_defects() -> None:+ metrics = _metrics(30)+ findings = [_fix(f"f{i}.py") for i in range(4)] # < _MIN_DEFECT_FILES+ assert compute_defect_accuracy(metrics, findings) is None+++def test_precision_lift_and_concentration() -> None:+ # 30 files; the 8 lowest-health files are exactly the bug-fixed ones.+ metrics = _metrics(30)+ findings = [_fix(f"f{i}.py") for i in range(8)]++ stat = compute_defect_accuracy(metrics, findings)+ assert stat is not None+ assert stat["k"] == 20+ assert stat["hits"] == 8+ assert stat["scored_files"] == 30+ assert stat["defect_files"] == 8+ # base_rate = 8/30, precision = 8/20.+ assert stat["base_rate"] == round(8 / 30, 4)+ assert stat["precision"] == round(8 / 20, 4)+ assert stat["lift"] == round((8 / 20) / (8 / 30), 2)+ # All 8 fixed files sit inside the least-healthy 20% (6 files) ... only 6 fit,+ # so concentration counts the 6 in the top bucket out of 8 total defect files.+ assert 0 < stat["concentration_defect_share"] <= 1.0+ assert stat["window_days"] == 180+ assert {row["k"] for row in stat["precision_table"]} == {10, 20, 30}+++def test_lift_none_when_no_baseline_is_handled() -> None:+ # Guardrails fire long before base_rate could be zero (it needs >=5 defect+ # files), so a real call always has a baseline; lift is therefore a number.+ metrics = _metrics(40)+ findings = [_fix(f"f{i}.py") for i in range(5)]+ stat = compute_defect_accuracy(metrics, findings)+ assert stat is not None+ assert stat["lift"] is not None+++def test_window_days_from_finding_details() -> None:+ metrics = _metrics(30)+ findings = [_fix(f"f{i}.py", window_days=90) for i in range(6)]+ stat = compute_defect_accuracy(metrics, findings)+ assert stat is not None+ assert stat["window_days"] == 90