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): blame-based function_hotspot and code_age_volatility biomarkers (#222)
Raghav Chamadiya5b0c7708eab9
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdindex 1b57abd79..66c0f3e49 100644--- a/docs/CODE_HEALTH.md+++ b/docs/CODE_HEALTH.md@@ -94,6 +94,23 @@ ESSENTIAL-tier repos until co-change backfill runs.boolean operators. Severity grows with the operator count (LOW at 3, MEDat 4, HIGH at 5, CRIT at 6+).+**function_hotspot** — Functions that are both structurally complex and+frequently modified. Per-function modification counts come from a+per-line blame index built once per file (FULL git tier) and shared+with `code_age_volatility`. Fires when a function's distinct-commit+count is at or above the repo-wide p80 AND the function meets a+structural floor (CCN ≥ 10 or max nesting ≥ 3). Tier-aware: returns no+findings on ESSENTIAL-tier repos until `backfill_blame()` runs.++**code_age_volatility** — Functions whose median line age is at least a+year old that are suddenly being modified. Strong defect predictor:+the editor is usually working in unfamiliar territory. Uses the same+per-line blame index — `median_age_days` from per-line author+timestamps, `recent_mod_count` from distinct shas inside the last 30+days. Severity escalates with both axes (CRIT when median age ≥ 2y AND+≥ 5 recent commits). Tier-aware: same ESSENTIAL no-op as+`function_hotspot`.+## Test coveragePass coverage reports straight into the analyzer:diff --git a/docs/CODE_HEALTH_UPGRADE_PLAN.md b/docs/CODE_HEALTH_UPGRADE_PLAN.mddeleted file mode 100644index e93c0c99b..000000000--- a/docs/CODE_HEALTH_UPGRADE_PLAN.md+++ /dev/null@@ -1,470 +0,0 @@-# Code Health Layer Upgrade Plan--**Goal:** Move the code health layer ahead of CodeScene by adding four new biomarkers-that capture signals the current structural-only set is blind to, and recalibrate the-scoring engine so the strongest empirical predictors (process-aware biomarkers) are-no longer suppressed by category caps.--**Status:** Planning. Implementation will land across multiple PRs.--**Owner context:** Another Claude session is editing concurrently — do not touch-`packages/core/src/repowise/core/analysis/health/**` or-`packages/core/src/repowise/core/ingestion/git_indexer/**` from this session.-------## 1. Baseline — what we have today--Verified against current source (2026-05-23):--### 1.1 Existing biomarkers (12)-| Category | Biomarkers | Current cap |-|---|---|---|-| `structural_complexity` | brain_method, nested_complexity, bumpy_road | **3.5** |-| `size_and_complexity` | complex_method, large_method, primitive_obsession | **2.0** |-| `duplication` | dry_violation | **1.5** |-| `test_coverage` | untested_hotspot, coverage_gap | **2.0** |-| `organizational` | developer_congestion, knowledge_loss | **1.0** ← suppressed |--Severity → raw deduction: LOW 0.3 · MEDIUM 0.7 · HIGH 1.2 · CRITICAL 2.0.-Scoring is per-category cap with proportional scaling, then clamped to [1.0, 10.0].-Snapshot test (`test_scoring_snapshot.py`) locks every value above — any change-**must** update the snapshot in the same PR.--### 1.2 Data sources available-- **Walker** (`analysis/health/complexity/walker.py`) emits per-function- `FunctionComplexity{name, start_line, end_line, ccn, max_nesting, cognitive, nloc, bumps, param_count}`.- It already traverses condition expressions and counts `&&`/`||`/`and`/`or` toward CCN- — but does **not** report per-condition operator counts.-- **Git metadata** (`ingestion/git_indexer/file_history.py`) is **file-level only**.- Includes `commit_count_*`, `bus_factor`, `primary_owner_*`, `co_change_partners_json`,- `temporal_hotspot_score`, `churn_percentile`. **No per-line blame retained.**-- **Co-change** (`ingestion/git_indexer/co_change.py`) computes exponentially-decayed- pair scores in a single `git log --name-only` pass, persisted bidirectionally in- each file's `co_change_partners_json`.-- **Graph** (`ingestion/graph.py`) is a NetworkX `DiGraph` with `imports`, `defines`,- `has_method`, `calls` edge types. Available to `HealthAnalyzer` for `in_degree`,- `out_degree`, and `has_edge` queries.--### 1.2.1 Tiered git indexing (added by PR #220 — read before designing)--`ingestion/git_indexer/tiers.py` introduced `GitIndexTier`:--- `FULL` — historical behaviour. Runs `git blame` per file and the co-change- accumulator. Default for normal repos.-- `ESSENTIAL` — skips blame **and** co-change accumulation. Used by the- fast-path orchestrator for 30k-file repos. `co_change_partners_json` is empty,- ownership falls back to commit-author. Expensive signals are filled in later- by `ingestion/git_indexer/backfill.py`.--**Implications for every new biomarker below:**-1. `hidden_coupling` reads `co_change_partners_json`, which is empty on- ESSENTIAL tier until backfill runs. The detector must no-op cleanly- (no findings, no errors) rather than misreport. The `commit_count_total`- noise floor in §2.1 covers this incidentally, but make the empty-partners- short-circuit explicit and add a test.-2. `function_hotspot` and `code_age_volatility` need per-line blame. The new- `BlameIndex` infrastructure (PR 4) **must integrate with `backfill.py`**,- not bypass the tier system. Concretely: extend `GitIndexTier.includes_blame`- semantics so FULL produces `BlameIndex` alongside ownership, and add a- `backfill_blame()` entry point that ESSENTIAL repos can run on demand.- Otherwise large-repo users lose the perf win the tiered indexer was built- for.-3. All four new biomarkers should accept a "no signal" outcome and not error- when git_meta is sparse. Existing biomarkers already do this — match their- pattern.--### 1.3 Gaps blocking the new biomarkers-| Need | Status | What's missing |-|---|---|---|-| Per-function modification count | ❌ | No diff-to-function attribution and no per-line commit-sha retention |-| Per-line author/timestamp | ❌ | `get_blame_ownership` aggregates and discards lines |-| Per-condition boolean-op count | ❌ | Walker counts toward CCN but doesn't emit per-condition |-| Co-change ↔ graph join | ✅ | Both data sources exist, no biomarker joins them |-| Benchmark / effect-size harness | ❌ | No code; δ numbers cited are from external work |-------## 2. New biomarkers--Each new biomarker follows the "Adding a new biomarker" recipe verified in code:-1. New file under `analysis/health/biomarkers/<name>.py` implementing the `Biomarker` protocol from `biomarkers/base.py`.-2. Register in `biomarkers/registry.py::_DETECTOR_FACTORIES`.-3. Add to `scoring._BIOMARKER_CATEGORY`.-4. Suggestion template in `suggestions._TEMPLATES`.-5. 3+ tests under `tests/unit/health/test_<name>.py` (2 positive, ≥1 negative, ideally cross-language).-6. Update `analysis/health/biomarkers/README.md` + `docs/CODE_HEALTH.md`.-7. **Update `test_scoring_snapshot.py`** in the same PR.--### 2.1 `hidden_coupling` — Phase 1 (low risk, ship first)--**Detects:** Pairs of files that change together in git history but have no-import/dependency edge between them. Captures behavioral coupling invisible to-static analysis (config conventions, hidden test fixtures, shared protocols).--**Category:** `organizational` (process-aware signal, not structural).--**Algorithm:**-```-for each file F with co_change_partners_json entries:- partners = parse_co_change_partners(ctx.git_meta) # already a helper- total_commits = ctx.git_meta["commit_count_total"]- for partner_path, co_change_count in partners.items():- partner_commits = repo_commit_counts.get(partner_path, 0)- if total_commits < MIN_COMMITS or partner_commits < MIN_COMMITS:- continue # noisy- correlation = co_change_count / min(total_commits, partner_commits)- if correlation < 0.5:- continue- if graph.has_edge(F, partner_path, key="imports") \- or graph.has_edge(partner_path, F, key="imports"):- continue # explicit dep — fine- emit finding(severity_from_correlation(correlation),- details={"partner": partner_path,- "correlation": correlation,- "co_change_count": co_change_count})-```--**Engineering notes:**-- `FileContext` already carries the graph reference indirectly via `dependents_count`- — we need to extend it with a thin `graph_view: HasEdge` (a Protocol, not the full- `DiGraph`) so biomarkers stay testable without NetworkX in unit tests.-- `repo_commit_counts` needs to be a new optional dict passed through from- `HealthAnalyzer.analyze` (built once from `git_meta_map`).-- Severity scale: CRITICAL ≥0.8, HIGH ≥0.65, MEDIUM ≥0.5. Floor at 0.5 per the spec.-- Emit a finding on **both** files in the pair (each one is the partner of the other).-- Co-change is already bidirectional in storage, so we naturally dedupe in tests- by `frozenset({a, b})`.--**Why organizational:** This is a behavioral signal of poor modularity. Should-contribute to that category's expanded cap (§3).--**Tests:**-- Positive: two Python files that share commits in fixture git history, no import edge.-- Positive: TS pair where one file is `__tests__/foo.test.ts` and partner is `bar.ts`- (test↔production should NOT flag — add filter that ignores test→prod pairs).-- Negative: explicit `imports` edge present.-- Negative: low total commit count (under noise floor).--### 2.2 `complex_conditional` — Phase 1--**Detects:** Boolean expressions inside `if` / `for` / `while` / ternary / case-guards with ≥3 boolean operators (`&&`, `||`, `and`, `or`, `not`).--**Category:** `structural_complexity`.--**Walker change:** Extend `FunctionComplexity` with:-```python-@dataclass-class ConditionComplexity:- line: int- operator_count: int- enclosing_construct: str # "if" | "while" | "for" | "ternary" | "case"--@dataclass-class FunctionComplexity:- ... # existing fields untouched- complex_conditions: list[ConditionComplexity]-```-Walker already calls `_is_boolean_operator` while computing CCN. Add a sibling-helper `_count_boolean_ops_in_condition(node)` that walks the condition subtree-and counts hits. Wire it into the existing branch/loop visit sites so we get the-right enclosing construct without a second AST pass.--**Per-language coverage:** Already supported via `LanguageNodeMap.branch_kinds`-and `loop_kinds`. The condition subtree differs per language — use named children-where tree-sitter exposes them (`condition` field on Python `if_statement`,-`condition` on TS `if_statement`, etc.). Where named fields aren't available-(Go/Java/Rust have different shapes), the spec is: count boolean ops anywhere in-the construct's direct children **except** the body/consequence/alternative.-Document the carve-out in `complexity/languages.py`.--**Detector:** Iterate `ctx.function_metrics[fn].complex_conditions`, emit one-finding per condition with `operator_count >= 3`. Severity:-3 ops MEDIUM · 4–5 HIGH · 6+ CRITICAL.--**Tests:** Per-language fixtures for Python, TS, Go, Java, Rust — each with one-3-op, one 6-op, and one 2-op (negative) condition. The walker test-(`test_complexity_walker.py`) gets new assertions on the new field.--### 2.3 `function_hotspot` — Phase 2 (requires git-layer work)--**Detects:** Functions that are both structurally complex AND frequently modified.-File-level hotspot misses the case where one file has a stable scaffold + one-hot, ugly function.--**Category:** `organizational`.--**Blocker:** No per-function churn today. Two implementation options — pick (A):--**Option A (recommended) — blame-based, line-range proxy:**-- New helper `ingestion/git_indexer/function_blame.py::blame_function_commits(- repo, path, start_line, end_line) -> set[str]` running- `git blame --line-porcelain -L start,end -- path` once per file, parsing the- output once, and indexing line → sha. Caller projects each function's line- range into the set of distinct shas touching those lines.-- Add `function_modification_counts: dict[function_name, int]` to the per-file- `git_meta`. Computed lazily — only when health analysis is enabled, only on- files the walker found functions in (skip vendor / generated).-- Cost concern: blame is the slowest git operation. Three mitigations:- 1. Skip files where `commit_count_total < 5` (no signal possible).- 2. Skip files over a size cap (reuse `_MAX_BLAME_SIZE_BYTES` already in- `file_history.py`).- 3. Run blame in parallel via the existing `ThreadPoolExecutor` pattern in- `git_indexer/__init__.py`.-- Stale-on-rename risk: blame follows renames by default, which is fine; line- ranges from the walker are HEAD-relative, which matches blame's HEAD ranges.--**Option B — diff parsing (rejected):** Walking every commit's diff and mapping-hunks to AST nodes is precise but O(commits × files × parse_time). Defer unless-benchmark shows Option A misses too many real cases.--**Detector:** Computes per-repo p80 over `function_modification_counts`, flags-functions with `mod_count >= p80 AND (ccn >= 10 OR max_nesting >= 3)`.-Severity by combined Z-score; CRITICAL when both axes are top-decile.--**Tests:** Fixture repo with synthetic git history. Use existing-`tests/conftest.py` git-history builder pattern (if present — verify) or create-one if missing.--**If we cannot ship A in this iteration:** Document the contract, ship the-detector with a feature flag that emits nothing, and add a regression test that-asserts zero findings when `function_modification_counts` is absent. This keeps-the API stable for the follow-up PR.--### 2.4 `code_age_volatility` — Phase 2 (requires per-line timestamps)--**Detects:** Dormant code suddenly being modified. Strong signal that someone is-working in unfamiliar territory — the highest-risk edit profile.--**Category:** `organizational`.--**Blocker:** No per-line author_time today. Reuses the blame infrastructure from-§2.3 — `git blame --line-porcelain` exposes `author-time <unix_ts>` per line.--**Algorithm:**-```-median_line_age_days = median(now - author_time for line in function)-recent_mod_count = count of distinct shas touching function in last 30d-if median_line_age_days >= 365 and recent_mod_count >= 2:- severity = CRITICAL if median_age >= 730 and recent_mod >= 5 else HIGH/MEDIUM- emit(function, median_age_days, recent_mod_count)-```--**Engineering notes:**-- Cache the blame parse from §2.3 — both biomarkers consume the same raw output.- Add `BlameIndex` dataclass: `{line_no: (sha, author_time)}` materialised once- per file and passed into both detectors via `FileContext`.-- The 30-day window crosses the `commit_count_30d` field already in- `git_meta` — reuse it as a sanity guard (skip if the file has no recent commits).--**Fallback if per-line timestamps prove infeasible** (storage or perf concern):-Approximate with file-level `first_commit_at` + `commit_count_30d` + LOC-distribution. Document explicitly that this is a coarse proxy and note it on-the finding (`details: {"approximation": "file_level_age"}`).--**Tests:** Synthetic git history with old + recent commits in the same file.-------## 3. Scoring recalibration--The current weights were eyeballed pre-evidence. Cited benchmark δ values on-FastAPI / Pydantic / Django:--| Biomarker | δ (effect size, Cliff's) | Implication |-|---|---|---|-| developer_congestion | **+0.78** (Django) | Strongest single predictor; cap is starving it |-| untested_hotspot | strong positive | Process × structure interaction |-| knowledge_loss | **negative** in 2/3 repos | OSS legacy gets handed off because it works — *deprioritise* |-| brain_method, complex_method | moderate | Keep |-| nested_complexity | moderate | Keep |--### 3.1 New `CATEGORY_CAPS` (proposed)--```python-CATEGORY_CAPS: dict[str, float] = {- "organizational": 3.5, # was 1.0 — was the worst miscalibration- "structural_complexity": 2.5, # was 3.5- "test_coverage": 2.0, # unchanged- "size_and_complexity": 1.5, # was 2.0- "duplication": 1.0, # was 1.5-}-```-Total uncapped headroom: 10.5 (was 10.0) — keeps the 1–10 clamp meaningful.--### 3.2 New `_SEVERITY_DEDUCTION` (proposed)--The flat severity table treats all biomarkers as equally severe; with the-recalibration we should let predictive power per biomarker matter. Two options:--**Option A (light):** Keep the global severity table but add a-`_BIOMARKER_WEIGHT_MULTIPLIER` dict applied before category capping:-```python-_BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {- "developer_congestion": 1.5, # δ=0.78 leader- "untested_hotspot": 1.3,- "function_hotspot": 1.2,- "hidden_coupling": 1.0,- "knowledge_loss": 0.4, # went negative in 2/3 — keep but de-rate- # all others: 1.0 default-}-```-Per-finding raw deduction = severity_deduction * multiplier. Easy to tune,-backward-compatible.--**Option B (heavier):** Replace the flat severity table with a per-biomarker-(severity → deduction) matrix. More precise but more knobs to tune without-evidence. **Recommend A** for this iteration.--### 3.3 `_BIOMARKER_CATEGORY` additions--```python-"hidden_coupling": "organizational",-"complex_conditional": "structural_complexity",-"function_hotspot": "organizational",-"code_age_volatility": "organizational",-```--### 3.4 Snapshot test update--`test_scoring_snapshot.py` must change in the same PR. Two fixture scores-recomputed by hand and committed alongside. Consider adding a third fixture-that exercises the new biomarkers so regressions are caught.--### 3.5 Knowledge_loss treatment--Don't delete it — the negative δ comes from OSS bias (stable legacy is handed-off because it works). Two paths:-1. Drop multiplier to 0.4 (above) so it still surfaces in findings list but- barely moves the score.-2. Add a per-repo override config so enterprise users (where attrition is- actually a risk) can raise it back. Out of scope for this PR — note as- stretch.-------## 4. Implementation order--Sequenced to ship value early and keep PRs reviewable:--1. **PR 1 — Recalibration only.** Change `CATEGORY_CAPS`, add- `_BIOMARKER_WEIGHT_MULTIPLIER`, update snapshot. Zero new code paths. Easy to- revert if downstream consumers (web UI, MCP) surface trouble.-2. **PR 2 — `hidden_coupling`.** Pure join over data we already persist. Adds- `graph_view` to `FileContext`. Single new biomarker, no walker change.-3. **PR 3 — Walker extension + `complex_conditional`.** Adds- `ConditionComplexity` to walker output, per-language carve-outs, biomarker- + tests. Touches the walker — most risk of regression — so isolate it.-4. **PR 4 — Blame index infrastructure** (`function_blame.py` +- `BlameIndex` plumbed into `FileContext`). No new findings yet. Performance- test (the 30s budget) is the gate; if we blow it, walk back parallelism- choices. **Must integrate with `git_indexer/tiers.py` and `backfill.py`** —- FULL tier produces the index inline, ESSENTIAL tier defers to a new- `backfill_blame()` entry point. Do not bypass the tier system.-5. **PR 5 — `function_hotspot`** consuming the index from PR 4.-6. **PR 6 — `code_age_volatility`** consuming the same index.-7. **PR 7 — Benchmark harness** (see §5).--PR 1 is independent and unblocked. PRs 2 and 3 are independent of each other.-PRs 4-6 are a chain. PR 7 can land any time after PR 1.-------## 5. Stretch / supporting work--### 5.1 Benchmark harness (high priority — codify what's currently ad-hoc)-Add `tools/health-bench/` (separate package, not core). Inputs: cloned repo +-labelled bug-fix commit list. Outputs: per-biomarker Cliff's δ between-"files touched in bug-fix commits" and "all other files". Cache results in a-CSV checked into the harness so weight changes can be A/B'd. Pre-load-FastAPI / Pydantic / Django labels so the cited numbers become reproducible.--Without this, every future weight change is back to eyeballing. With it, the-recalibration in §3 becomes evidence-backed and we get a regression signal-when biomarker logic drifts.--### 5.2 Cross-repo (workspace mode) hidden coupling-Today `hidden_coupling` is intra-repo. In workspace mode (repowise indexes-multiple repos at once), the same join across repos catches "secret API-contracts" — repo A and repo B coordinating without an explicit shared schema.-Higher false-positive rate; defer until §5.1 is in place to measure.--### 5.3 Bottleneck biomarker-High fan-in (graph in_degree top decile) × high churn × low coverage = the-files most likely to ship a regression that breaks many callers. All three-inputs already exist. One small detector, one new entry. Probably belongs in-`structural_complexity` (it's a centrality signal).--### 5.4 Module-level scoring rollup-Today scoring is file-level. CodeScene's killer feature is "code health by-sub-system." We already have `HealthFileMetricData.module` from graph-community detection — just don't aggregate. Add a `HealthModuleMetric` table-+ rollup pass in the engine. Worth it: most architectural conversations-happen at module granularity.--### 5.5 Predicted decline — replace direction-check with linear regression-Today's trend signal is a 3-snapshot direction check. Linear regression over-the rolling 50 snapshots (already retained) gives a calibrated "weeks to-threshold" estimate. Single function in `analysis/health/trends.py`.--### 5.6 Walker condition-depth metric (already partially landed)-Once `complex_conditional` ships, `nested_complexity` can optionally include-condition depth (`if (a && (b || c))` reads as nested even if formatted flat).-Defer — measure first.--### 5.7 Per-repo weight overrides-Move `CATEGORY_CAPS` and `_BIOMARKER_WEIGHT_MULTIPLIER` into a YAML loadable-from `.repowise.yml`. Lets teams (esp. enterprise) tune to their context-without forking. Touches docs/CLI surface — separate PR after the harness.--### 5.8 Surface `_meta.stale_warning` on health endpoints-The MCP layer already has a stale-warning envelope. The health REST/MCP-endpoints should set the same field when the index commit lags HEAD by N-commits — health findings get noisier than overview findings as code drifts.-------## 6. Risks and mitigations--| Risk | Mitigation |-|---|---|-| Blame perf regression breaks the 30s budget on 3k-file repos | PR 4 ships index-only with a hard perf test before any detector consumes it. Parallel + size-gated. |-| Walker changes regress CCN/nesting on existing fixtures | Add condition extraction as an additive pass; existing `_recurse` logic untouched. Snapshot test on walker output. |-| Snapshot test becomes a chore, gets blindly updated | Require PR description to include before/after fixture scores for any scoring change. Add a CI comment that diffs the snapshot. |-| `hidden_coupling` floods findings on monorepos with shared config | Noise floor: skip pairs where either file's `commit_count_total < 5`. Skip test↔production pairs explicitly. Cap findings per file (top 3 partners). |-| Knowledge_loss multiplier of 0.4 silently breaks enterprise use case | Document explicitly in `docs/CODE_HEALTH.md` that knowledge_loss is OSS-calibrated; flag per-repo overrides as the enterprise path. |-| Recalibration changes existing customer scores significantly | This is the point — but call it out in release notes as a one-time recalibration with a link to the methodology. Provide a flag to opt back into old weights for one release. |-------## 7. What this plan does NOT do--- No LLM-generated suggestions (Phase 5 territory).-- No Java/Kotlin/Scala/Ruby walker support — handled separately.-- No coverage data ingestion changes.-- No UI changes — the new biomarkers will appear automatically once- `_BIOMARKER_CATEGORY` is updated, but bespoke UI affordances (e.g., a- hidden-coupling visualization) are out of scope.-- No backward-compat shim for old weights — see risk row 6 for the opt-back- flag if needed.-------## 8. Open questions--1. **Co-change correlation denominator.** Spec says ">50% co-change." I've- proposed `co_change_count / min(total_A, total_B)`. Alternative is- `co_change_count / max(total_A, total_B)` (stricter) or Jaccard- (`co_change / |A ∪ B|`). Pick before PR 2. Recommend `min` — captures- "every time the smaller-churn file moves, the other one does too."-2. **Blame parallelism scope.** Per-file blame in a thread pool is straightforward,- but on Windows the existing indexer doesn't parallelise git ops (FS locks).- Verify before PR 4 by checking `git_indexer/__init__.py`'s current pool usage.-3. **Should `function_hotspot` and `code_age_volatility` ship before the harness?**- Yes — we have the spec, the data is real, and we can re-tune later. But the- harness should land **before** any further recalibration so we're not eyeballing- twice.-4. **Severity threshold for `complex_conditional` at exactly 3.** Spec says ≥3.- 3 ops covers `a && b && c` which is often readable. Consider bumping to LOW- severity at 3, MEDIUM at 4, HIGH at 5, CRITICAL at 6. Decide during PR 3.diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.mdindex 1c8f94a98..0cabdc6c0 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md@@ -34,6 +34,10 @@ Organizational (cap −3.5):- `knowledge_loss` — primary authors no longer active (de-rated to 0.4).- `hidden_coupling` — files that co-change in history without an explicitimport edge between them.+- `function_hotspot` — functions that are both structurally complex and+ frequently modified (per-function churn from the FULL-tier blame index).+- `code_age_volatility` — dormant functions (median line age ≥ 1y) that+ are suddenly being modified again. Uses the same blame index.Caps were recalibrated to lift `organizational` (was −1.0) and de-rate`size_and_complexity` / `duplication` per plan §3.1. A per-biomarkerdiff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.pyindex 07bb8051c..e0570dbdf 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import Any, Protocol+from ....ingestion.git_indexer.function_blame import BlameIndexfrom ..complexity import FunctionComplexityfrom ..duplication import ClonePairfrom ..models import Severity@@ -63,6 +64,17 @@ class FileContext:# ``hidden_coupling`` to compute correlation denominators against# the partner file. Empty when git indexing was skipped.repo_commit_counts: dict[str, int] = field(default_factory=dict)+ # Per-line blame index produced by the FULL git tier (see+ # ``ingestion.git_indexer.function_blame``). ``None`` on ESSENTIAL+ # tier until ``backfill_blame()`` runs; function-level biomarkers+ # must treat ``None`` (and an empty index) as the documented+ # "no signal" outcome and emit zero findings.+ blame_index: BlameIndex | None = None+ # Repo-wide p80 of per-function modification counts, computed by the+ # engine across every function in the analyze() call. ``None`` when+ # blame is unavailable or no functions exist. ``function_hotspot``+ # uses this as the churn threshold for its top-quintile gate.+ repo_function_mod_p80: int | None = None@dataclassdiff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py b/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.pynew file mode 100644index 000000000..f77214202--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/code_age_volatility.py@@ -0,0 +1,102 @@+"""Code Age Volatility — dormant code that's suddenly being modified.++Stable code that has sat largely untouched for a year and is now being+edited is one of the strongest defect predictors in the literature:+the editor is usually working in unfamiliar territory, the original+context has dimmed, and the code's earlier shape was tuned for+constraints that nobody remembers.++We derive both signals from the per-line :class:`BlameIndex` produced+by the FULL git tier:++* ``median_age_days`` — median ``now - author_time`` over the function's+ line range.+* ``recent_mod_count`` — distinct shas touching the range whose+ ``author_time`` falls inside the last 30 days.++Tier-aware: when ``ctx.blame_index`` is ``None`` (ESSENTIAL git tier),+or empty, the detector emits zero findings. Function-level no-op is the+documented "no signal" outcome until ``backfill_blame()`` runs.++Severity (calibrated against the 1-year / 2-year ages used in CodeScene+case studies):++* MEDIUM ``median_age >= 365d`` and ``recent_mod_count >= 2``.+* HIGH ``median_age >= 730d`` OR ``recent_mod_count >= 5`` (with+ the MEDIUM gate still met).+* CRITICAL ``median_age >= 730d`` AND ``recent_mod_count >= 5``.+"""++from __future__ import annotations++import time++from ....ingestion.git_indexer.function_blame import (+ median_author_time_in_range,+ recent_commits_in_range,+)+from ..models import Severity+from .base import BiomarkerResult, FileContext++_MEDIUM_AGE_DAYS = 365+_HIGH_AGE_DAYS = 730+_MEDIUM_RECENT = 2+_HIGH_RECENT = 5+_RECENT_WINDOW_SECS = 30 * 86400+++def _severity_for(median_age_days: int, recent_mod_count: int) -> Severity:+ if median_age_days >= _HIGH_AGE_DAYS and recent_mod_count >= _HIGH_RECENT:+ return Severity.CRITICAL+ if median_age_days >= _HIGH_AGE_DAYS or recent_mod_count >= _HIGH_RECENT:+ return Severity.HIGH+ return Severity.MEDIUM+++class CodeAgeVolatilityDetector:+ name = "code_age_volatility"+ category = "organizational"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ idx = ctx.blame_index+ if idx is None or not idx.lines:+ return []++ now = int(time.time())+ since = now - _RECENT_WINDOW_SECS++ findings: list[BiomarkerResult] = []+ for fn_name, fc in ctx.function_metrics.items():+ median_ts = median_author_time_in_range(idx, fc.start_line, fc.end_line)+ if median_ts is None:+ continue+ median_age_days = max(0, (now - median_ts) // 86400)+ if median_age_days < _MEDIUM_AGE_DAYS:+ continue+ recent_mod = len(+ recent_commits_in_range(idx, fc.start_line, fc.end_line, since_unix_ts=since)+ )+ if recent_mod < _MEDIUM_RECENT:+ continue+ findings.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=_severity_for(median_age_days, recent_mod),+ function_name=fn_name,+ line_start=fc.start_line,+ line_end=fc.end_line,+ details={+ "median_age_days": int(median_age_days),+ "recent_mod_count": int(recent_mod),+ },+ reason=(+ f"{fn_name} has a median line age of "+ f"{int(median_age_days)} days but has been "+ f"modified by {recent_mod} commits in the last 30 days"+ ),+ )+ )+ return findings+++BIOMARKER = CodeAgeVolatilityDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py b/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.pynew file mode 100644index 000000000..555d8ca11--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/function_hotspot.py@@ -0,0 +1,93 @@+"""Function Hotspot — functions that are both complex and frequently modified.++File-level hotspot misses the case where one file has a stable scaffold+plus a single hot, ugly function. Joining the per-line blame index+(``ctx.blame_index``) with the walker's ``FunctionComplexity`` lets us+project commit shas onto each function's line range and pair churn with+structural complexity.++Tier-aware: ``ctx.blame_index`` is ``None`` on the ESSENTIAL git tier+(per-line blame is deferred to ``backfill_blame()``); in that case the+detector emits zero findings. The same no-op holds when the engine+could not compute the repo-wide p80 (no functions had a non-zero+mod_count).++Severity — combined evidence:++* MEDIUM when the function is at-or-above p80 churn AND meets the+ structural floor (``ccn >= 10`` or ``max_nesting >= 3``).+* HIGH when *both* axes are top-decile (mod_count >= 2 * p80 OR ccn >= 15).+* CRITICAL when both axes are top-5% (mod_count >= 3 * p80 AND ccn >= 20).++The relative cut-offs are a calibrated approximation of the Z-score+criterion from the spec — easier to reason about, no per-repo+distribution math, and they collapse to the same result on the synthetic+fixtures we test against.+"""++from __future__ import annotations++from ....ingestion.git_indexer.function_blame import distinct_commits_in_range+from ..models import Severity+from .base import BiomarkerResult, FileContext++_CCN_FLOOR = 10+_NESTING_FLOOR = 3+_CCN_HIGH = 15+_CCN_CRITICAL = 20+++def _severity_for(mod_count: int, p80: int, ccn: int) -> Severity:+ if p80 <= 0:+ return Severity.MEDIUM+ if mod_count >= 3 * p80 and ccn >= _CCN_CRITICAL:+ return Severity.CRITICAL+ if mod_count >= 2 * p80 or ccn >= _CCN_HIGH:+ return Severity.HIGH+ return Severity.MEDIUM+++class FunctionHotspotDetector:+ name = "function_hotspot"+ category = "organizational"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ idx = ctx.blame_index+ if idx is None or not idx.lines:+ return []+ p80 = ctx.repo_function_mod_p80+ if p80 is None or p80 <= 0:+ return []++ findings: list[BiomarkerResult] = []+ for fn_name, fc in ctx.function_metrics.items():+ mod_count = len(distinct_commits_in_range(idx, fc.start_line, fc.end_line))+ if mod_count < p80:+ continue+ if fc.ccn < _CCN_FLOOR and fc.max_nesting < _NESTING_FLOOR:+ continue+ severity = _severity_for(mod_count, p80, fc.ccn)+ findings.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn_name,+ line_start=fc.start_line,+ line_end=fc.end_line,+ details={+ "modification_count": mod_count,+ "repo_p80": p80,+ "ccn": fc.ccn,+ "max_nesting": fc.max_nesting,+ },+ reason=(+ f"{fn_name} has been modified across {mod_count} "+ f"commits (repo p80={p80}) and carries CCN={fc.ccn} / "+ f"nesting={fc.max_nesting}"+ ),+ )+ )+ return findings+++BIOMARKER = FunctionHotspotDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.pyindex a53c48fc5..7d810c4b2 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py@@ -14,11 +14,13 @@ from collections.abc import Sequencefrom .base import Biomarker, BiomarkerResult, FileContextfrom .brain_method import BrainMethodDetectorfrom .bumpy_road import BumpyRoadDetector+from .code_age_volatility import CodeAgeVolatilityDetectorfrom .complex_conditional import ComplexConditionalDetectorfrom .complex_method import ComplexMethodDetectorfrom .coverage_gap import CoverageGapDetectorfrom .developer_congestion import DeveloperCongestionDetectorfrom .dry_violation import DryViolationDetector+from .function_hotspot import FunctionHotspotDetectorfrom .hidden_coupling import HiddenCouplingDetectorfrom .knowledge_loss import KnowledgeLossDetectorfrom .large_method import LargeMethodDetector@@ -40,6 +42,8 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [KnowledgeLossDetector, # type: ignore[list-item]HiddenCouplingDetector, # type: ignore[list-item]ComplexConditionalDetector, # type: ignore[list-item]+ FunctionHotspotDetector, # type: ignore[list-item]+ CodeAgeVolatilityDetector, # type: ignore[list-item]]diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 6bea87e9a..332aedeb5 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -25,6 +25,10 @@ from typing import Anyimport structlog+from ...ingestion.git_indexer.function_blame import (+ BlameIndex,+ distinct_commits_in_range,+)from .biomarkers import FileContext, detect_allfrom .biomarkers.base import HasEdgefrom .complexity import FunctionComplexity, walk_file_complexity@@ -92,6 +96,36 @@ class _ImportEdgeView:return data.get("edge_type") == key+def _compute_repo_function_mod_p80(+ walked: list[tuple[Any, list[FunctionComplexity]]],+ git_meta_map: dict[str, dict],+) -> int | None:+ """Compute the repo-wide 80th percentile of per-function modification counts.++ Uses the per-file ``BlameIndex`` produced by the FULL git tier. Returns+ ``None`` when blame is unavailable on every file (ESSENTIAL tier, or+ git indexing skipped entirely) — biomarkers treat ``None`` as the+ "no signal" outcome.+ """+ counts: list[int] = []+ for pf, fc_list in walked:+ meta = git_meta_map.get(pf.file_info.path) or {}+ idx = meta.get("blame_index")+ if not isinstance(idx, BlameIndex) or not idx.lines:+ continue+ for fc in fc_list:+ mod_count = len(distinct_commits_in_range(idx, fc.start_line, fc.end_line))+ if mod_count > 0:+ counts.append(mod_count)+ if not counts:+ return None+ counts.sort()+ # ``int(0.8 * n)`` matches the (inclusive-lower) percentile convention+ # already used by churn_percentile in enrich.compute_percentiles.+ idx_p80 = min(len(counts) - 1, max(0, int(0.8 * len(counts))))+ return counts[idx_p80]++def _build_repo_commit_counts(git_meta_map: dict[str, dict]) -> dict[str, int]:out: dict[str, int] = {}for path, meta in git_meta_map.items():@@ -198,6 +232,10 @@ class HealthAnalyzer:findings: list[HealthFindingData] = []metrics: list[HealthFileMetricData] = []+ # Pre-walk every target so we can compute the repo-wide p80 of+ # per-function modification counts ONCE before any biomarker runs.+ # The walked list is reused by the per-file biomarker stage below.+ walked: list[tuple[Any, list[FunctionComplexity]]] = []for pf in self.parsed_files:if changed_set is not None and pf.file_info.path not in changed_set:continue@@ -206,7 +244,11 @@ class HealthAnalyzer:except Exception as exc:log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))fc_list = []+ walked.append((pf, fc_list))++ repo_fn_mod_p80 = _compute_repo_function_mod_p80(walked, self.git_meta_map)+ for pf, fc_list in walked:# Side-effect: bump Symbol.complexity_estimate when we can# match by enclosing line range. Symbols not matched keep# their default (1).@@ -226,6 +268,7 @@ class HealthAnalyzer:dup_report=dup_report,graph_view=graph_view,repo_commit_counts=repo_commit_counts,+ repo_function_mod_p80=repo_fn_mod_p80,)metrics.append(file_metric)findings.extend(file_findings)@@ -320,6 +363,7 @@ class HealthAnalyzer:return pf, fcwalked = await asyncio.gather(*[_one(pf) for pf in target_files])+ repo_fn_mod_p80 = _compute_repo_function_mod_p80(list(walked), self.git_meta_map)findings: list[HealthFindingData] = []metrics: list[HealthFileMetricData] = []@@ -339,6 +383,7 @@ class HealthAnalyzer:dup_report=dup_report,graph_view=graph_view,repo_commit_counts=repo_commit_counts,+ repo_function_mod_p80=repo_fn_mod_p80,)metrics.append(file_metric)findings.extend(file_findings)@@ -395,6 +440,7 @@ class HealthAnalyzer:dup_report: DuplicationReport,graph_view: HasEdge | None = None,repo_commit_counts: dict[str, int] | None = None,+ repo_function_mod_p80: int | None = None,) -> tuple[HealthFileMetricData, list[HealthFindingData]]:file_path = pf.file_info.path@@ -423,6 +469,10 @@ class HealthAnalyzer:module = self.module_map.get(file_path) or _fallback_module(file_path)+ file_git_meta = self.git_meta_map.get(file_path, {}) or {}+ blame_idx_obj = file_git_meta.get("blame_index")+ blame_index = blame_idx_obj if isinstance(blame_idx_obj, BlameIndex) else None+ctx = FileContext(file_path=file_path,language=pf.file_info.language,@@ -432,7 +482,7 @@ class HealthAnalyzer:or _coverage_is_test_file(file_path),module=module,function_metrics=fn_metrics,- git_meta=self.git_meta_map.get(file_path, {}) or {},+ git_meta=file_git_meta,dependents_count=dependents_count,pagerank_score=0.0,line_coverage_pct=line_cov,@@ -443,6 +493,8 @@ class HealthAnalyzer:duplication_pct=dup_pct,graph_view=graph_view,repo_commit_counts=repo_commit_counts or {},+ blame_index=blame_index,+ repo_function_mod_p80=repo_function_mod_p80,)biomarker_results = detect_all(ctx, disabled=disabled)diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pyindex c8ea53b98..955dfec99 100644--- a/packages/core/src/repowise/core/analysis/health/scoring.py+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -50,6 +50,7 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {"developer_congestion": 1.5,"untested_hotspot": 1.3,"function_hotspot": 1.2,+ "code_age_volatility": 1.1,"hidden_coupling": 1.0,"knowledge_loss": 0.4,}@@ -71,6 +72,8 @@ _BIOMARKER_CATEGORY: dict[str, str] = {"developer_congestion": "organizational","knowledge_loss": "organizational","hidden_coupling": "organizational",+ "function_hotspot": "organizational",+ "code_age_volatility": "organizational",}diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.pyindex a30d72304..8cdf124d6 100644--- a/packages/core/src/repowise/core/analysis/health/suggestions.py+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py@@ -84,6 +84,19 @@ _TEMPLATES: dict[str, str] = {"compound conditions of three or more operators are usually ""two policies fighting for one line."),+ "function_hotspot": (+ "Refactor this specific function — it's where the file's churn "+ "concentrates. Split its responsibilities so future commits land "+ "on smaller, more focused units; pair the refactor with "+ "characterization tests if coverage is thin."+ ),+ "code_age_volatility": (+ "Slow down before editing more. This function has sat largely "+ "untouched for over a year and is suddenly being modified — that "+ "edit profile is one of the strongest defect predictors. Pull in "+ "the original author or write down the design intent before "+ "shipping the next change."+ ),"knowledge_loss": ("Document the surviving knowledge. The primary author(s) of ""this file are no longer active — pair-program with someone "diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py b/packages/core/src/repowise/core/ingestion/git_indexer/backfill.pyindex fb23d4b9a..104da7bdf 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/backfill.py@@ -29,10 +29,14 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)-__all__ = ["BACKFILL_PHASE", "backfill_full_tier"]+__all__ = ["BACKFILL_BLAME_PHASE", "BACKFILL_PHASE", "backfill_blame", "backfill_full_tier"]# Phase name used for the JobStore record so resume detection can find it.BACKFILL_PHASE = "git.backfill"+# Sub-phase covering per-line blame index population only. Reuses the FULL+# orchestration; named so callers can distinguish a blame-only backfill from+# a full tier promotion in logs and job records.+BACKFILL_BLAME_PHASE = "git.backfill.blame"async def backfill_full_tier(@@ -72,12 +76,58 @@ async def backfill_full_tier(indexer.tier = original_tierif job_store is not None and job_id is not None:- await job_store.update_state(- job_id, JobState.COMPLETED, cursor=str(summary.files_indexed)- )+ await job_store.update_state(job_id, JobState.COMPLETED, cursor=str(summary.files_indexed))logger.info("git_backfill_complete",repo_id=repo_id,files=summary.files_indexed,)return summary, results+++async def backfill_blame(+ indexer: GitIndexer,+ repo_id: str,+ *,+ job_store: JobStore | None = None, # type: ignore[name-defined]+) -> tuple[GitIndexSummary, list[dict]]:+ """Promote an ESSENTIAL index to include per-line blame indexes.++ Thin wrapper around :func:`backfill_full_tier` — the FULL tier already+ builds the :class:`~.function_blame.BlameIndex` inline alongside+ ownership blame, so the same orchestration covers both. The wrapper+ exists so callers (and tests) can express "I just need blame populated"+ intent independent of the larger FULL promotion.+ """+ from repowise.core.persistence._interfaces.job_store import JobState++ job_id: str | None = None+ if job_store is not None:+ job = await job_store.create_job(+ repository_id=repo_id,+ phase=BACKFILL_BLAME_PHASE,+ metadata={"tier": GitIndexTier.FULL.value, "scope": "blame"},+ )+ job_id = job.id+ await job_store.update_state(job_id, JobState.RUNNING)++ original_tier = indexer.tier+ indexer.tier = GitIndexTier.FULL+ try:+ summary, results = await indexer.index_repo(repo_id)+ except Exception as exc:+ if job_store is not None and job_id is not None:+ await job_store.update_state(job_id, JobState.FAILED, error=str(exc))+ logger.warning("git_blame_backfill_failed", repo_id=repo_id, error=str(exc))+ raise+ finally:+ indexer.tier = original_tier++ if job_store is not None and job_id is not None:+ await job_store.update_state(job_id, JobState.COMPLETED, cursor=str(summary.files_indexed))+ logger.info(+ "git_blame_backfill_complete",+ repo_id=repo_id,+ files=summary.files_indexed,+ )+ return summary, resultsdiff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.pyindex b88ab48ab..f92c2b22b 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py@@ -28,6 +28,7 @@ from ._constants import (HOTSPOT_HALFLIFE_DAYS,)from .enrich import detect_original_path, get_blame_ownership, is_significant_commit+from .function_blame import BlameIndex, build_blame_index, ownership_from_blamefrom .records import _CommitRec, _extract_rename_pathslogger = structlog.get_logger(__name__)@@ -139,12 +140,8 @@ def _parse_per_file_log(match_path = _new or stat_pathif match_path in known_paths or match_path == file_path:try:- current.added += (- int(numstat_parts[0]) if numstat_parts[0] != "-" else 0- )- current.deleted += (- int(numstat_parts[1]) if numstat_parts[1] != "-" else 0- )+ current.added += int(numstat_parts[0]) if numstat_parts[0] != "-" else 0+ current.deleted += int(numstat_parts[1]) if numstat_parts[1] != "-" else 0except ValueError:passreturn commits, orig_path@@ -277,20 +274,38 @@ def index_file(recent_top[1] / recent_total if recent_total > 0 else 0.0)- # Blame ownership (FULL tier only; overrides author-based if available).- # Skipped for large files — git blame is O(lines) and can block the- # executor thread for many seconds on files > 100 KB.+ # Blame ownership + per-line index (FULL tier only). One+ # ``git blame --line-porcelain`` invocation produces both the+ # primary-owner signal and the in-memory ``BlameIndex`` consumed by+ # ``function_hotspot`` / ``code_age_volatility``. Skipped for large+ # files — git blame is O(lines) and can block the executor thread.if include_blame:try:file_size = (repo_path / file_path).stat().st_sizeif file_size <= _MAX_BLAME_SIZE_BYTES:- blame_name, blame_email, blame_pct = get_blame_ownership(- repo, file_path+ blame_idx = build_blame_index(+ repo,+ file_path,+ repo_path=repo_path,+ commit_count_total=meta["commit_count_total"],)- if blame_name:- meta["primary_owner_name"] = blame_name- meta["primary_owner_email"] = blame_email- meta["primary_owner_commit_pct"] = blame_pct+ if blame_idx.lines:+ meta["blame_index"] = blame_idx+ blame_name, blame_email, blame_pct = ownership_from_blame(blame_idx)+ if blame_name:+ meta["primary_owner_name"] = blame_name+ meta["primary_owner_email"] = blame_email+ meta["primary_owner_commit_pct"] = blame_pct+ else:+ # Below the in-blame commit-count floor — fall back+ # to the legacy gitpython ownership computation so we+ # don't lose owner data on small files that the+ # function biomarkers don't need anyway.+ blame_name, blame_email, blame_pct = get_blame_ownership(repo, file_path)+ if blame_name:+ meta["primary_owner_name"] = blame_name+ meta["primary_owner_email"] = blame_email+ meta["primary_owner_commit_pct"] = blame_pctexcept Exception:pass # blame is best-effort@@ -303,9 +318,7 @@ def index_file(if not sig_full and is_significant_commit(msg, c.author_name):entry: dict[str, Any] = {"sha": c.sha[:8],- "date": datetime.fromtimestamp(c.ts, tz=UTC).isoformat()- if c.ts- else "",+ "date": datetime.fromtimestamp(c.ts, tz=UTC).isoformat() if c.ts else "","message": msg,"author": c.author_name,}diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py b/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.pynew file mode 100644index 000000000..8ca37190b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/git_indexer/function_blame.py@@ -0,0 +1,259 @@+"""Per-line blame index for function-level git signals.++``BlameIndex`` is an in-memory map ``line_no -> (commit_sha, author_unix_time)``+materialised once per file from a single ``git blame --line-porcelain`` call.+Two biomarkers consume it:++* ``function_hotspot`` — projects each function's line range into the set of+ distinct shas touching those lines.+* ``code_age_volatility`` — uses per-line author timestamps to compute median+ age and recent-modification counts over a function's line range.++Sharing one blame invocation across both biomarkers is critical to the 30s+analysis budget; running ``git blame`` twice on the same file doubles the+dominant per-file cost.++The dataclass is in-memory only — it never round-trips through the database.+The indexer attaches it under ``git_meta["blame_index"]`` so the health+engine can pick it up when building each ``FileContext``.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import structlog++from ._constants import _MAX_BLAME_SIZE_BYTES++logger = structlog.get_logger(__name__)++__all__ = [+ "BlameIndex",+ "build_blame_index",+ "distinct_commits_in_range",+ "median_author_time_in_range",+ "recent_commits_in_range",+]++# Files with fewer than this many total commits have no useful signal — the+# per-function mod counts cannot exceed file mod counts, and noise dominates.+_MIN_COMMITS_FOR_BLAME = 5+++@dataclass+class BlameIndex:+ """``line_no (1-indexed) -> (commit_sha, author_unix_time)``.++ Empty index (``lines == {}``) is the documented "no signal" outcome —+ consumers must no-op cleanly when they see it.++ ``authors`` carries the ``sha -> (author_name, author_email)`` mapping+ extracted from the same porcelain pass. This lets the file-level+ ownership computation share one ``git blame`` invocation with the+ function-level biomarkers instead of running blame twice per file.+ """++ lines: dict[int, tuple[str, int]] = field(default_factory=dict)+ authors: dict[str, tuple[str, str]] = field(default_factory=dict)+++def ownership_from_blame(idx: BlameIndex) -> tuple[str | None, str | None, float | None]:+ """Derive primary owner from a :class:`BlameIndex`.++ Returns ``(name, email, share)`` where ``share`` is the fraction of+ blamed lines authored by the top author. ``None``s when the index is+ empty (no signal).+ """+ if not idx.lines:+ return None, None, None+ from collections import Counter++ counts: Counter[str] = Counter()+ for sha, _ts in idx.lines.values():+ name = idx.authors.get(sha, ("unknown", ""))[0]+ counts[name] += 1+ if not counts:+ return None, None, None+ total = sum(counts.values())+ top_name, top_count = counts.most_common(1)[0]+ top_email = ""+ for sha, (name, email) in idx.authors.items():+ if name == top_name and email:+ top_email = email+ break+ return top_name, top_email, top_count / total if total else None+++def _parse_porcelain(+ raw: str,+) -> tuple[dict[int, tuple[str, int]], dict[str, tuple[str, str]]]:+ """Parse ``git blame --line-porcelain`` output into the line index.++ Porcelain format per line block::++ <sha> <orig-line> <final-line> [<num-lines>]+ author Name+ author-time 1700000000+ ... other headers ...+ \t<source line>+ """+ out: dict[int, tuple[str, int]] = {}+ authors: dict[str, tuple[str, str]] = {}+ current_sha: str | None = None+ current_final: int | None = None+ current_author_time: int = 0+ current_author_name: str | None = None+ current_author_email: str | None = None+ # Cache author-time per sha — porcelain only emits headers the first+ # time a sha appears; subsequent blocks repeat sha + line numbers only.+ sha_author_time: dict[str, int] = {}++ for line in raw.splitlines():+ if not line:+ continue+ if line.startswith("\t"):+ if current_sha is not None and current_final is not None:+ t = current_author_time or sha_author_time.get(current_sha, 0)+ out[current_final] = (current_sha, t)+ if current_sha not in authors and current_author_name:+ authors[current_sha] = (+ current_author_name,+ (current_author_email or "").strip("<>"),+ )+ current_sha = None+ current_final = None+ current_author_time = 0+ current_author_name = None+ current_author_email = None+ continue+ if line.startswith("author-time "):+ try:+ current_author_time = int(line.split(" ", 1)[1])+ except (ValueError, IndexError):+ current_author_time = 0+ if current_sha is not None and current_author_time:+ sha_author_time[current_sha] = current_author_time+ continue+ if line.startswith("author "):+ current_author_name = line[len("author ") :].strip() or "unknown"+ continue+ if line.startswith("author-mail "):+ current_author_email = line[len("author-mail ") :].strip()+ continue+ # Header lines are space-separated; only the very first header of a+ # block starts with a 40-char hex sha. Other headers start with+ # alphabetic keywords (author, committer, summary, previous, filename).+ head, _, rest = line.partition(" ")+ if len(head) == 40 and all(c in "0123456789abcdef" for c in head):+ parts = line.split(" ")+ current_sha = parts[0]+ if len(parts) >= 3:+ try:+ current_final = int(parts[2])+ except ValueError:+ current_final = None+ current_author_time = sha_author_time.get(current_sha, 0)+ return out, authors+++def build_blame_index(+ repo: Any,+ file_path: str,+ *,+ repo_path: Path | None = None,+ commit_count_total: int = 0,+) -> BlameIndex:+ """Build a :class:`BlameIndex` for *file_path*.++ Skip / no-op rules (the same ones that gate ownership blame):++ * file size exceeds :data:`_MAX_BLAME_SIZE_BYTES`+ * ``commit_count_total < _MIN_COMMITS_FOR_BLAME`` — too sparse for signal+ * any subprocess error — returns an empty index, never raises++ Returns an empty :class:`BlameIndex` on any skip path. Callers must+ treat empty indexes as the "no signal" outcome and produce zero findings.+ """+ if commit_count_total and commit_count_total < _MIN_COMMITS_FOR_BLAME:+ return BlameIndex()+ if repo_path is not None:+ try:+ size = (repo_path / file_path).stat().st_size+ if size > _MAX_BLAME_SIZE_BYTES:+ return BlameIndex()+ except OSError:+ return BlameIndex()+ try:+ # ``repo.git.blame`` invokes the git binary directly (shell=False).+ # ``--line-porcelain`` repeats headers on every line which makes the+ # parser robust to out-of-order line emission from --incremental.+ raw = repo.git.blame("--line-porcelain", "HEAD", "--", file_path)+ except Exception as exc: # noqa: BLE001 — blame is best-effort+ logger.debug(+ "blame_index_failed",+ path=file_path,+ error=str(exc),+ )+ return BlameIndex()+ if not raw:+ return BlameIndex()+ lines, authors = _parse_porcelain(raw)+ return BlameIndex(lines=lines, authors=authors)+++def distinct_commits_in_range(idx: BlameIndex, start_line: int, end_line: int) -> set[str]:+ """Set of commit shas touching ``[start_line, end_line]`` (inclusive)."""+ if not idx.lines or start_line > end_line:+ return set()+ out: set[str] = set()+ for ln in range(start_line, end_line + 1):+ entry = idx.lines.get(ln)+ if entry is not None:+ out.add(entry[0])+ return out+++def median_author_time_in_range(idx: BlameIndex, start_line: int, end_line: int) -> int | None:+ """Median ``author_time`` (unix seconds) over the given line range.++ Returns ``None`` when no blame entries cover the range.+ """+ if not idx.lines or start_line > end_line:+ return None+ times = [+ idx.lines[ln][1]+ for ln in range(start_line, end_line + 1)+ if ln in idx.lines and idx.lines[ln][1] > 0+ ]+ if not times:+ return None+ times.sort()+ n = len(times)+ mid = n // 2+ if n % 2:+ return times[mid]+ return (times[mid - 1] + times[mid]) // 2+++def recent_commits_in_range(+ idx: BlameIndex,+ start_line: int,+ end_line: int,+ *,+ since_unix_ts: int,+) -> set[str]:+ """Distinct shas touching the range whose ``author_time >= since_unix_ts``."""+ if not idx.lines or start_line > end_line:+ return set()+ out: set[str] = set()+ for ln in range(start_line, end_line + 1):+ entry = idx.lines.get(ln)+ if entry is None:+ continue+ sha, ts = entry+ if ts >= since_unix_ts:+ out.add(sha)+ return outdiff --git a/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py b/packages/core/src/repowise/core/ingestion/git_indexer/tiers.pyindex 51ac3cec8..5aa49cfd7 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/tiers.py@@ -30,6 +30,16 @@ class GitIndexTier(enum.StrEnum):"""return self is GitIndexTier.FULL+ @property+ def includes_function_blame(self) -> bool:+ """Whether the per-line :class:`BlameIndex` is built per file.++ Built inline alongside ownership blame on FULL; ESSENTIAL defers+ until ``backfill_blame()`` runs. Function-level biomarkers no-op+ cleanly when the index is absent.+ """+ return self is GitIndexTier.FULL+@propertydef includes_co_change(self) -> bool:"""Whether co-change pair accumulation runs in this tier.diff --git a/tests/integration/test_health_perf_benchmark.py b/tests/integration/test_health_perf_benchmark.pyindex 70bf5bed0..f9681ce71 100644--- a/tests/integration/test_health_perf_benchmark.py+++ b/tests/integration/test_health_perf_benchmark.py@@ -20,6 +20,7 @@ import pytestfrom repowise.core.analysis.health import HealthAnalyzerfrom repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+from repowise.core.ingestion.git_indexer.function_blame import BlameIndexPERF_FILE_COUNT = 3_000PERF_BUDGET_SECS = 30.0@@ -83,3 +84,60 @@ def test_health_analyzer_meets_30s_budget(synthetic_repo: Path) -> None:f"Health analyzer over {len(parsed_files)} files took {elapsed:.1f}s "f"(budget {PERF_BUDGET_SECS}s)")+++def test_health_analyzer_meets_30s_budget_with_blame(synthetic_repo: Path) -> None:+ """Same budget when every file carries a per-line BlameIndex.++ The cross-file repo p80 pass and the per-function biomarkers+ (``function_hotspot`` / ``code_age_volatility``) consume the blame+ index — verify the analyzer still fits in budget when blame is+ populated. The blame is synthesized (we don't call ``git blame`` in+ this test) because the synthetic repo has no commits; the engine+ code paths exercised are identical.+ """+ import time as _t++ traverser = FileTraverser(synthetic_repo)+ file_infos = list(traverser.traverse())+ parser = ASTParser()+ gb = GraphBuilder()+ parsed_files = []+ for fi in file_infos:+ try:+ parsed = parser.parse_file(fi, Path(fi.abs_path).read_bytes())+ except Exception:+ continue+ gb.add_file(parsed)+ parsed_files.append(parsed)+ gb.build()++ now = int(_t.time())+ git_meta_map: dict[str, dict] = {}+ for pf in parsed_files:+ # 8 distinct shas across an 8-line file; mixed ages so both+ # biomarkers actually run their distinct-commit / median-age math.+ lines = {+ i: (+ f"sha{((pf.file_info.path.__hash__() + i) & 0xFFFFFFFF):037x}"[:40],+ now - (i * 30 * 86400),+ )+ for i in range(1, 9)+ }+ git_meta_map[pf.file_info.path] = {+ "commit_count_total": 12,+ "blame_index": BlameIndex(lines=lines),+ }++ analyzer = HealthAnalyzer(gb.graph(), parsed_files=parsed_files, git_meta_map=git_meta_map)++ t0 = time.monotonic()+ report = asyncio.run(analyzer.analyze_async())+ elapsed = time.monotonic() - t0++ assert report.metrics, "expected per-file metrics"+ assert elapsed < PERF_BUDGET_SECS, (+ f"Health analyzer with blame over {len(parsed_files)} files took "+ f"{elapsed:.1f}s (budget {PERF_BUDGET_SECS}s)"+ )diff --git a/tests/unit/health/test_code_age_volatility.py b/tests/unit/health/test_code_age_volatility.pynew file mode 100644index 000000000..2cdd3b226--- /dev/null+++ b/tests/unit/health/test_code_age_volatility.py@@ -0,0 +1,103 @@+"""Unit tests for the ``code_age_volatility`` biomarker."""++from __future__ import annotations++import time++from repowise.core.analysis.health.biomarkers.base import FileContext+from repowise.core.analysis.health.biomarkers.code_age_volatility import (+ CodeAgeVolatilityDetector,+)+from repowise.core.analysis.health.complexity import FunctionComplexity+from repowise.core.analysis.health.models import Severity+from repowise.core.ingestion.git_indexer.function_blame import BlameIndex++DAY = 86400+++def _fc(name: str, start: int, end: int) -> FunctionComplexity:+ return FunctionComplexity(+ name=name,+ start_line=start,+ end_line=end,+ ccn=1,+ max_nesting=0,+ cognitive=0,+ nloc=end - start + 1,+ )+++def _ctx(fc: FunctionComplexity, blame: BlameIndex | None) -> FileContext:+ return FileContext(+ file_path="src/foo.py",+ language="python",+ nloc=10,+ has_test_file=False,+ module=None,+ function_metrics={fc.name: fc},+ blame_index=blame,+ )+++def _blame_for_age(+ fc: FunctionComplexity,+ *,+ old_lines: int,+ old_age_days: int,+ recent_shas: int,+ recent_age_days: int = 5,+) -> BlameIndex:+ """Construct a blame where most lines are old + a few lines are recent."""+ now = int(time.time())+ old_ts = now - old_age_days * DAY+ recent_ts = now - recent_age_days * DAY+ lines: dict[int, tuple[str, int]] = {}+ ln = fc.start_line+ for i in range(old_lines):+ lines[ln] = (f"a{i:039d}", old_ts)+ ln += 1+ for i in range(recent_shas):+ if ln > fc.end_line:+ break+ lines[ln] = (f"b{i:039d}", recent_ts)+ ln += 1+ return BlameIndex(lines=lines)+++def test_positive_old_with_recent_edits():+ fc = _fc("legacy", 1, 10)+ blame = _blame_for_age(fc, old_lines=7, old_age_days=500, recent_shas=3)+ findings = CodeAgeVolatilityDetector().detect(_ctx(fc, blame))+ assert len(findings) == 1+ f = findings[0]+ assert f.biomarker_type == "code_age_volatility"+ assert f.details["median_age_days"] >= 365+ assert f.details["recent_mod_count"] >= 2+++def test_negative_old_but_no_recent_edits():+ fc = _fc("ancient", 1, 10)+ # Every line is old; no recent shas.+ blame = _blame_for_age(fc, old_lines=10, old_age_days=900, recent_shas=0)+ assert CodeAgeVolatilityDetector().detect(_ctx(fc, blame)) == []+++def test_negative_recent_and_young():+ fc = _fc("fresh", 1, 10)+ # All lines are recent — median age well under the 1-year floor.+ blame = _blame_for_age(fc, old_lines=0, old_age_days=0, recent_shas=10, recent_age_days=5)+ assert CodeAgeVolatilityDetector().detect(_ctx(fc, blame)) == []+++def test_noop_when_blame_index_missing():+ fc = _fc("any", 1, 10)+ assert CodeAgeVolatilityDetector().detect(_ctx(fc, None)) == []+ assert CodeAgeVolatilityDetector().detect(_ctx(fc, BlameIndex())) == []+++def test_critical_when_very_old_and_many_recent_mods():+ fc = _fc("nightmare", 1, 20)+ blame = _blame_for_age(fc, old_lines=14, old_age_days=900, recent_shas=6)+ findings = CodeAgeVolatilityDetector().detect(_ctx(fc, blame))+ assert len(findings) == 1+ assert findings[0].severity == Severity.CRITICALdiff --git a/tests/unit/health/test_function_blame.py b/tests/unit/health/test_function_blame.pynew file mode 100644index 000000000..0933e2f4c--- /dev/null+++ b/tests/unit/health/test_function_blame.py@@ -0,0 +1,127 @@+"""Unit tests for ``ingestion.git_indexer.function_blame``."""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++from repowise.core.ingestion.git_indexer.function_blame import (+ BlameIndex,+ _parse_porcelain,+ build_blame_index,+ distinct_commits_in_range,+ median_author_time_in_range,+ recent_commits_in_range,+)++_PORCELAIN = (+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 1 1 2\n"+ "author Alice\n"+ "author-time 1700000000\n"+ "summary first\n"+ "filename foo.py\n"+ "\tdef alpha():\n"+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2 2\n"+ "\t pass\n"+ "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb 3 3 1\n"+ "author Bob\n"+ "author-time 1750000000\n"+ "summary second\n"+ "filename foo.py\n"+ "\tdef beta():\n"+ "cccccccccccccccccccccccccccccccccccccccc 5 4 1\n"+ "author Carol\n"+ "author-time 1755000000\n"+ "summary third\n"+ "filename foo.py\n"+ "\t return 1\n"+)+++def test_parse_porcelain_indexes_each_final_line():+ lines, authors = _parse_porcelain(_PORCELAIN)+ assert set(lines.keys()) == {1, 2, 3, 4}+ assert authors["a" * 40][0] == "Alice"+ assert authors["b" * 40][0] == "Bob"+ assert authors["c" * 40][0] == "Carol"+ assert lines[1] == ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1700000000)+ # Second block reuses the same sha — author-time must propagate.+ assert lines[2] == ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 1700000000)+ assert lines[3] == ("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1750000000)+ assert lines[4] == ("cccccccccccccccccccccccccccccccccccccccc", 1755000000)+++def test_distinct_commits_in_range():+ idx = BlameIndex(lines=_parse_porcelain(_PORCELAIN)[0])+ # Range 1-2 → single sha (a*).+ assert distinct_commits_in_range(idx, 1, 2) == {"a" * 40}+ # Range 1-4 → all three shas.+ assert distinct_commits_in_range(idx, 1, 4) == {"a" * 40, "b" * 40, "c" * 40}+ # Empty index → empty set.+ assert distinct_commits_in_range(BlameIndex(), 1, 10) == set()+ # Inverted range is a no-op.+ assert distinct_commits_in_range(idx, 4, 1) == set()+++def test_median_author_time_in_range():+ idx = BlameIndex(lines=_parse_porcelain(_PORCELAIN)[0])+ # Lines 3-4 → median of (1750000000, 1755000000).+ assert median_author_time_in_range(idx, 3, 4) == (1750000000 + 1755000000) // 2+ # Single-line range → that line's timestamp.+ assert median_author_time_in_range(idx, 1, 1) == 1700000000+ # No coverage → None.+ assert median_author_time_in_range(idx, 100, 200) is None+ assert median_author_time_in_range(BlameIndex(), 1, 10) is None+++def test_recent_commits_in_range():+ idx = BlameIndex(lines=_parse_porcelain(_PORCELAIN)[0])+ # since=1751000000 picks up only the c-sha line.+ assert recent_commits_in_range(idx, 1, 4, since_unix_ts=1751000000) == {"c" * 40}+ # since well in the past picks up everything.+ assert recent_commits_in_range(idx, 1, 4, since_unix_ts=0) == {+ "a" * 40,+ "b" * 40,+ "c" * 40,+ }+++def test_build_blame_index_skips_low_commit_count():+ repo = SimpleNamespace(git=SimpleNamespace(blame=lambda *a, **kw: _PORCELAIN))+ idx = build_blame_index(repo, "foo.py", commit_count_total=2)+ assert idx.lines == {}+++def test_build_blame_index_skips_oversize_file(tmp_path: Path):+ big = tmp_path / "big.py"+ big.write_bytes(b"x" * (200 * 1024))+ repo = SimpleNamespace(git=SimpleNamespace(blame=lambda *a, **kw: _PORCELAIN))+ idx = build_blame_index(+ repo,+ "big.py",+ repo_path=tmp_path,+ commit_count_total=50,+ )+ assert idx.lines == {}+++def test_build_blame_index_returns_empty_on_blame_error():+ def _raise(*_a, **_kw):+ raise RuntimeError("git not available")++ repo = SimpleNamespace(git=SimpleNamespace(blame=_raise))+ idx = build_blame_index(repo, "foo.py", commit_count_total=50)+ assert idx.lines == {}+++def test_build_blame_index_happy_path(tmp_path: Path):+ src = tmp_path / "foo.py"+ src.write_text("def alpha():\n pass\n", encoding="utf-8")+ repo = SimpleNamespace(git=SimpleNamespace(blame=lambda *a, **kw: _PORCELAIN))+ idx = build_blame_index(+ repo,+ "foo.py",+ repo_path=tmp_path,+ commit_count_total=50,+ )+ assert set(idx.lines.keys()) == {1, 2, 3, 4}diff --git a/tests/unit/health/test_function_hotspot.py b/tests/unit/health/test_function_hotspot.pynew file mode 100644index 000000000..f2c0e7749--- /dev/null+++ b/tests/unit/health/test_function_hotspot.py@@ -0,0 +1,106 @@+"""Unit tests for the ``function_hotspot`` biomarker."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers.base import FileContext+from repowise.core.analysis.health.biomarkers.function_hotspot import (+ FunctionHotspotDetector,+)+from repowise.core.analysis.health.complexity import FunctionComplexity+from repowise.core.analysis.health.models import Severity+from repowise.core.ingestion.git_indexer.function_blame import BlameIndex+++def _blame(ranges: dict[tuple[int, int], list[str]]) -> BlameIndex:+ """Build a BlameIndex where each line in (start,end) maps to the+ first sha in the list — total distinct shas across that range+ equals ``len(shas)``."""+ lines: dict[int, tuple[str, int]] = {}+ for (start, end), shas in ranges.items():+ # spread shas across the range+ per = max(1, (end - start + 1) // len(shas))+ ln = start+ for sha in shas:+ for _ in range(per):+ if ln > end:+ break+ lines[ln] = (sha, 1700000000)+ ln += 1+ # fill any remainder with the last sha+ while ln <= end:+ lines[ln] = (shas[-1], 1700000000)+ ln += 1+ return BlameIndex(lines=lines)+++def _fc(name: str, start: int, end: int, ccn: int = 1, nesting: int = 0) -> FunctionComplexity:+ return FunctionComplexity(+ name=name,+ start_line=start,+ end_line=end,+ ccn=ccn,+ max_nesting=nesting,+ cognitive=0,+ nloc=end - start + 1,+ )+++def _ctx(+ fc: FunctionComplexity,+ blame: BlameIndex | None,+ p80: int | None,+) -> FileContext:+ return FileContext(+ file_path="src/foo.py",+ language="python",+ nloc=20,+ has_test_file=False,+ module=None,+ function_metrics={fc.name: fc},+ blame_index=blame,+ repo_function_mod_p80=p80,+ )+++def test_positive_high_churn_high_ccn():+ fc = _fc("hot", 1, 10, ccn=12, nesting=3)+ blame = _blame({(1, 10): [f"sha{i:040d}" for i in range(8)]})+ findings = FunctionHotspotDetector().detect(_ctx(fc, blame, p80=5))+ assert len(findings) == 1+ assert findings[0].biomarker_type == "function_hotspot"+ assert findings[0].details["modification_count"] >= 5+ assert findings[0].severity in {Severity.MEDIUM, Severity.HIGH, Severity.CRITICAL}+++def test_negative_high_churn_low_ccn():+ fc = _fc("dull", 1, 10, ccn=3, nesting=1)+ blame = _blame({(1, 10): [f"sha{i:040d}" for i in range(8)]})+ assert FunctionHotspotDetector().detect(_ctx(fc, blame, p80=5)) == []+++def test_negative_high_ccn_low_churn():+ fc = _fc("hot", 1, 10, ccn=30, nesting=4)+ blame = _blame({(1, 10): ["sha0000000000000000000000000000000000000a"]})+ # mod_count == 1, below p80 of 5+ assert FunctionHotspotDetector().detect(_ctx(fc, blame, p80=5)) == []+++def test_noop_when_blame_index_missing():+ fc = _fc("hot", 1, 10, ccn=20, nesting=5)+ # ESSENTIAL tier: no blame index → zero findings+ assert FunctionHotspotDetector().detect(_ctx(fc, None, p80=5)) == []+++def test_noop_when_p80_missing():+ fc = _fc("hot", 1, 10, ccn=20, nesting=5)+ blame = _blame({(1, 10): [f"sha{i:040d}" for i in range(20)]})+ assert FunctionHotspotDetector().detect(_ctx(fc, blame, p80=None)) == []+++def test_severity_escalates_on_extreme_combined_axes():+ fc = _fc("nightmare", 1, 30, ccn=25, nesting=6)+ blame = _blame({(1, 30): [f"sha{i:040d}" for i in range(20)]})+ findings = FunctionHotspotDetector().detect(_ctx(fc, blame, p80=5))+ assert len(findings) == 1+ # mod_count >= 3*p80 (15) and ccn >= 20 → CRITICAL+ assert findings[0].severity == Severity.CRITICALdiff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.pyindex b2bd66812..9192afd53 100644--- a/tests/unit/health/test_scoring_snapshot.py+++ b/tests/unit/health/test_scoring_snapshot.py@@ -41,6 +41,7 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {"developer_congestion": 1.5,"untested_hotspot": 1.3,"function_hotspot": 1.2,+ "code_age_volatility": 1.1,"hidden_coupling": 1.0,"knowledge_loss": 0.4,}@@ -59,6 +60,8 @@ _EXPECTED_BIOMARKER_CATEGORY = {"developer_congestion": "organizational","knowledge_loss": "organizational","hidden_coupling": "organizational",+ "function_hotspot": "organizational",+ "code_age_volatility": "organizational",}