Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): recalibrate scoring + add hidden_coupling and complex_conditional (#221)

Raghav Chamadiya2fc2830bc9bf
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index c30fcbc55..1b57abd79 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -25,11 +25,20 @@ most:
| Category | Cap | Biomarkers |
|------------------------|-------|------------|
-| Structural complexity | −3.5 | brain_method, nested_complexity, bumpy_road |
-| Size & complexity | −2.0 | complex_method, large_method, primitive_obsession |
-| Duplication | −1.5 | dry_violation |
+| Organizational | −3.5 | developer_congestion, knowledge_loss, hidden_coupling |
+| Structural complexity | −2.5 | brain_method, nested_complexity, bumpy_road, complex_conditional |
| Test coverage | −2.0 | untested_hotspot, coverage_gap |
-| Organizational | −1.0 | developer_congestion, knowledge_loss |
+| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
+| Duplication | −1.0 | dry_violation |
+
+Per-biomarker weight multipliers (see `scoring._BIOMARKER_WEIGHT_MULTIPLIER`)
+let the strongest empirical predictors deduct more than the uniform severity
+table alone allows. `developer_congestion` is multiplied by 1.5,
+`untested_hotspot` by 1.3, `function_hotspot` (a follow-up biomarker) by 1.2,
+and `knowledge_loss` is de-rated to 0.4. The de-rating is OSS-calibrated
+(legacy code gets handed off because it works); enterprise users where
+attrition is a real risk should raise it back via per-repo overrides — see
+plan §3.5.
The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:
@@ -37,7 +46,7 @@ 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.
-## The 12 biomarkers
+## The biomarkers
**brain_method** — A single function that is simultaneously long, deeply
nested, highly complex, and central to the dependency graph. The strongest
@@ -75,6 +84,16 @@ Usually an ownership problem dressed up as a code problem.
**knowledge_loss** — The primary authors of the file are no longer active
on the project. Refactor while someone still remembers why.
+**hidden_coupling** — Files that consistently change in the same commits
+without an explicit import or dependency edge between them. Captures
+behavioral coupling (shared protocols, parallel config, copy-pasted
+constants) that static analysis cannot see. Tier-aware: empty on
+ESSENTIAL-tier repos until co-change backfill runs.
+
+**complex_conditional** — Branch / loop guards that combine three or more
+boolean operators. Severity grows with the operator count (LOW at 3, MED
+at 4, HIGH at 5, CRIT at 6+).
+
## Test coverage
Pass coverage reports straight into the analyzer:
diff --git a/docs/CODE_HEALTH_UPGRADE_PLAN.md b/docs/CODE_HEALTH_UPGRADE_PLAN.md
new file mode 100644
index 000000000..e93c0c99b
--- /dev/null
+++ b/docs/CODE_HEALTH_UPGRADE_PLAN.md
@@ -0,0 +1,470 @@
+# 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.md
index d55d4bcb3..1c8f94a98 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -9,28 +9,37 @@ class Biomarker(Protocol):
def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...
```
-## Registered v1 detectors (12)
+## Registered detectors (14)
-Structural complexity (cap −3.5):
+Structural complexity (cap −2.5):
- `brain_method` — symbols simultaneously long, complex, and central.
- `nested_complexity` — functions with deep nesting (≥ 4 levels).
- `bumpy_road` — multiple branches at the same nesting depth.
+- `complex_conditional` — compound boolean expressions with ≥ 3 ops.
-Size & complexity (cap −2.0):
+Size & complexity (cap −1.5):
- `complex_method` — functions with CCN ≥ 9.
- `large_method` — functions exceeding the NLOC threshold.
- `primitive_obsession` — many primitive parameters in a single signature.
-Duplication (cap −1.5):
+Duplication (cap −1.0):
- `dry_violation` — Rabin–Karp clone pairs, weighted by co-change.
Test coverage (cap −2.0):
- `untested_hotspot` — hotspot × low coverage × many dependents.
- `coverage_gap` — non-test files with meaningful uncovered surface.
-Organizational (cap −1.0):
+Organizational (cap −3.5):
- `developer_congestion` — too many active authors competing on a file.
-- `knowledge_loss` — primary authors no longer active.
+- `knowledge_loss` — primary authors no longer active (de-rated to 0.4).
+- `hidden_coupling` — files that co-change in history without an explicit
+ import edge between them.
+
+Caps were recalibrated to lift `organizational` (was −1.0) and de-rate
+`size_and_complexity` / `duplication` per plan §3.1. A per-biomarker
+weight multiplier in `scoring._BIOMARKER_WEIGHT_MULTIPLIER` lets the
+strongest empirical predictors deduct more than the uniform severity
+table alone would allow.
## Inputs
@@ -45,6 +54,10 @@ Organizational (cap −1.0):
- `line_coverage_pct`, `branch_coverage_pct`, `covered_lines` — coverage
signals; `None` when no coverage was ingested.
- `clones`, `duplication_pct` — pre-computed cross-file clone data.
+- `graph_view` — thin `HasEdge` protocol wrapper over the dependency
+ graph; `None` on test fixtures that didn't construct a graph.
+- `repo_commit_counts` — `dict[path, commit_count_total]` populated once
+ per `analyze` call so co-change detectors can look up partner totals.
## Outputs
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index 2d08015a4..07bb8051c 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -10,6 +10,16 @@ from ..duplication import ClonePair
from ..models import Severity
+class HasEdge(Protocol):
+ """Minimal graph view for biomarkers that need to ask "is there an
+ edge between these two files?" without depending on NetworkX in
+ tests. ``engine.py`` wraps the real ``DiGraph`` in an adapter that
+ implements this protocol.
+ """
+
+ def has_edge(self, src: str, dst: str, key: str = "imports") -> bool: ...
+
+
@dataclass
class FileContext:
"""All inputs a biomarker may need to evaluate a file.
@@ -45,6 +55,14 @@ class FileContext:
# is the percent of NLOC covered by clones.
clones: list[ClonePair] = field(default_factory=list)
duplication_pct: float | None = None
+ # Thin graph view exposing only ``has_edge`` — see ``HasEdge`` above.
+ # ``None`` on test fixtures that never construct a graph.
+ graph_view: HasEdge | None = None
+ # Repo-wide per-file commit totals (``commit_count_total`` from
+ # git_meta), keyed by repo-relative POSIX path. Used by
+ # ``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)
@dataclass
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
new file mode 100644
index 000000000..7a2eab9bd
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_conditional.py
@@ -0,0 +1,67 @@
+"""Complex Conditional — compound boolean expressions inside one branch.
+
+Flags ``if`` / ``while`` / ``for`` / ternary / case guards whose
+condition is glued together from three or more boolean operators
+(``&&`` / ``||`` / ``and`` / ``or``). Three-operator conditions are
+already harder to read at a glance than a single equality; six-operator
+conditions are routinely cited in defect-mining studies as the noisy
+end of a branch's lifetime.
+
+Category: ``structural_complexity``.
+
+Consumes ``FunctionComplexity.complex_conditions`` — collected by the
+walker as a side-channel without affecting CCN/cognitive scores.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_LOW = 3
+_MEDIUM = 4
+_HIGH = 5
+_CRITICAL = 6
+
+
+def _severity_for(op_count: int) -> Severity:
+ if op_count >= _CRITICAL:
+ return Severity.CRITICAL
+ if op_count >= _HIGH:
+ return Severity.HIGH
+ if op_count >= _MEDIUM:
+ return Severity.MEDIUM
+ return Severity.LOW
+
+
+class ComplexConditionalDetector:
+ name = "complex_conditional"
+ category = "structural_complexity"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for fn_name, fc in ctx.function_metrics.items():
+ for cond in fc.complex_conditions or []:
+ if cond.operator_count < _LOW:
+ continue
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=_severity_for(cond.operator_count),
+ function_name=fn_name,
+ line_start=cond.line,
+ line_end=cond.line,
+ details={
+ "operator_count": cond.operator_count,
+ "enclosing_construct": cond.enclosing_construct,
+ },
+ reason=(
+ f"{cond.enclosing_construct} condition combines "
+ f"{cond.operator_count} boolean operators"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = ComplexConditionalDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
new file mode 100644
index 000000000..199f13139
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
@@ -0,0 +1,184 @@
+"""Hidden Coupling — files that change together but don't import each other.
+
+Joins two existing signals: ``co_change_partners_json`` (from the git
+indexer) and the file-level import edges in the dependency graph. A
+high correlation between commits of files A and B that have no static
+dependency between them captures behavioral coupling invisible to a
+pure type/import analyzer — shared protocols, parallel config, hidden
+test fixtures, copy-pasted constants.
+
+Fires when:
+
+- ``commit_count_total`` for both files is at or above the noise floor
+- ``co_change_count(A, B) / min(total_A, total_B) >= 0.5``
+- there is **no** ``imports`` edge in either direction
+- the pair is not a test ↔ production pairing (those are expected to
+ co-change)
+
+Tier-aware: when ``co_change_partners_json`` is empty (ESSENTIAL git
+tier, plan §1.2.1) the detector short-circuits to zero findings. The
+empty short-circuit is explicit so backfill behavior is testable.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_MIN_COMMITS = 5
+_MIN_CORRELATION = 0.5
+_HIGH_THRESHOLD = 0.65
+_CRITICAL_THRESHOLD = 0.8
+_MAX_FINDINGS_PER_FILE = 3
+
+# Same conventions used by engine._has_paired_test_file. Keeping them
+# inline (rather than importing) avoids a circular dependency between
+# the engine and the biomarker package.
+_TEST_BASENAME_PATTERNS: tuple[str, ...] = (
+ "test_", # prefix
+)
+_TEST_SUFFIXES: tuple[str, ...] = (
+ "_test.py",
+ ".test.ts",
+ ".test.tsx",
+ ".test.js",
+ ".spec.ts",
+ ".spec.js",
+ "_test.go",
+)
+_TEST_DIR_FRAGMENTS: tuple[str, ...] = (
+ "/test/",
+ "/tests/",
+ "/__tests__/",
+)
+
+
+def _is_test_path(path: str) -> bool:
+ p = path.replace("\\", "/").lower()
+ if any(frag in f"/{p}" for frag in _TEST_DIR_FRAGMENTS):
+ return True
+ base = Path(p).name
+ if base.startswith(_TEST_BASENAME_PATTERNS):
+ return True
+ return any(p.endswith(suf) for suf in _TEST_SUFFIXES)
+
+
+def _parse_partners(meta: dict[str, Any]) -> dict[str, int]:
+ raw = meta.get("co_change_partners_json")
+ if not raw:
+ return {}
+ try:
+ partners = json.loads(raw)
+ except (TypeError, ValueError):
+ return {}
+ out: dict[str, int] = {}
+ for p in partners:
+ if not isinstance(p, dict):
+ continue
+ path = p.get("file_path") or p.get("path")
+ count = p.get("co_change_count") or p.get("count") or 0
+ if not path:
+ continue
+ try:
+ out[str(path)] = int(count)
+ except (TypeError, ValueError):
+ continue
+ return out
+
+
+def _as_int(value: object, default: int = 0) -> int:
+ try:
+ return int(value or 0) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return default
+
+
+def _severity_for(correlation: float) -> Severity:
+ if correlation >= _CRITICAL_THRESHOLD:
+ return Severity.CRITICAL
+ if correlation >= _HIGH_THRESHOLD:
+ return Severity.HIGH
+ return Severity.MEDIUM
+
+
+class HiddenCouplingDetector:
+ name = "hidden_coupling"
+ category = "organizational"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ meta = ctx.git_meta or {}
+ partners = _parse_partners(meta)
+ # Explicit ESSENTIAL-tier short-circuit (plan §1.2.1).
+ if not partners:
+ return []
+
+ total_self = _as_int(meta.get("commit_count_total"))
+ if total_self < _MIN_COMMITS:
+ return []
+
+ self_is_test = _is_test_path(ctx.file_path)
+ graph = ctx.graph_view
+ counts = ctx.repo_commit_counts or {}
+
+ candidates: list[tuple[float, str, int]] = []
+ for partner_path, co_count in partners.items():
+ if partner_path == ctx.file_path:
+ continue
+ partner_total = counts.get(partner_path, 0)
+ if partner_total < _MIN_COMMITS:
+ continue
+ denom = min(total_self, partner_total)
+ if denom <= 0:
+ continue
+ correlation = co_count / denom
+ if correlation < _MIN_CORRELATION:
+ continue
+ # Skip test ↔ production pairings — expected to co-change.
+ if self_is_test ^ _is_test_path(partner_path):
+ continue
+ # Skip when an explicit import edge already documents the
+ # coupling.
+ if graph is not None and (
+ graph.has_edge(ctx.file_path, partner_path, "imports")
+ or graph.has_edge(partner_path, ctx.file_path, "imports")
+ ):
+ continue
+ candidates.append((correlation, partner_path, co_count))
+
+ if not candidates:
+ return []
+
+ candidates.sort(key=lambda t: t[0], reverse=True)
+ capped = candidates[:_MAX_FINDINGS_PER_FILE]
+
+ findings: list[BiomarkerResult] = []
+ for correlation, partner_path, co_count in capped:
+ findings.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=_severity_for(correlation),
+ function_name=None,
+ line_start=None,
+ line_end=None,
+ details={
+ "partner": partner_path,
+ "correlation": round(correlation, 3),
+ "co_change_count": co_count,
+ "self_commits": total_self,
+ "partner_commits": counts.get(partner_path, 0),
+ },
+ reason=(
+ f"{partner_path} co-changes with this file "
+ f"{co_count} times ({correlation:.0%} of shared "
+ "commits) but no static dependency exists"
+ ),
+ )
+ )
+ return findings
+
+
+BIOMARKER = HiddenCouplingDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 547ac6a89..a53c48fc5 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -14,10 +14,12 @@ from collections.abc import Sequence
from .base import Biomarker, BiomarkerResult, FileContext
from .brain_method import BrainMethodDetector
from .bumpy_road import BumpyRoadDetector
+from .complex_conditional import ComplexConditionalDetector
from .complex_method import ComplexMethodDetector
from .coverage_gap import CoverageGapDetector
from .developer_congestion import DeveloperCongestionDetector
from .dry_violation import DryViolationDetector
+from .hidden_coupling import HiddenCouplingDetector
from .knowledge_loss import KnowledgeLossDetector
from .large_method import LargeMethodDetector
from .nested_complexity import NestedComplexityDetector
@@ -36,6 +38,8 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
CoverageGapDetector, # type: ignore[list-item]
DeveloperCongestionDetector, # type: ignore[list-item]
KnowledgeLossDetector, # type: ignore[list-item]
+ HiddenCouplingDetector, # type: ignore[list-item]
+ ComplexConditionalDetector, # type: ignore[list-item]
]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
index 3e2bcb527..6f7f2bb2a 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
@@ -2,6 +2,6 @@
from __future__ import annotations
-from .walker import FunctionComplexity, walk_file_complexity
+from .walker import ConditionComplexity, FunctionComplexity, walk_file_complexity
-__all__ = ["FunctionComplexity", "walk_file_complexity"]
+__all__ = ["ConditionComplexity", "FunctionComplexity", "walk_file_complexity"]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index c7ed69621..b17f3b348 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -33,6 +33,20 @@ if TYPE_CHECKING:
log = structlog.get_logger(__name__)
+@dataclass
+class ConditionComplexity:
+ """One control-flow condition with its boolean-operator count.
+
+ Emitted by the walker as a side-channel to ``FunctionComplexity``;
+ does not affect CCN or cognitive complexity. Consumed by the
+ ``complex_conditional`` biomarker.
+ """
+
+ line: int # 1-indexed start line of the enclosing construct
+ operator_count: int
+ enclosing_construct: str # "if" | "while" | "for" | "ternary" | "case"
+
+
@dataclass
class FunctionComplexity:
"""Per-function metrics produced by the walker."""
@@ -51,6 +65,13 @@ class FunctionComplexity:
# ``primitive_obsession``. Counted via the tree-sitter ``parameters``
# field; 0 when the language lacks an explicit list or extraction fails.
param_count: int = 0
+ # Per-condition boolean-operator counts collected during the walk.
+ # Empty when no branch/loop carries compound boolean expressions.
+ complex_conditions: list[ConditionComplexity] = None # type: ignore[assignment]
+
+ def __post_init__(self) -> None:
+ if self.complex_conditions is None:
+ self.complex_conditions = []
def _find_name(node: Node) -> str:
@@ -97,11 +118,90 @@ def _is_boolean_operator(node: Node, lmap: LanguageNodeMap) -> bool:
return False
+_BODY_FIELD_NAMES = (
+ "body",
+ "consequence",
+ "alternative",
+ "else_clause",
+ "block",
+)
+
+
+def _count_boolean_ops_in_condition(node: Node, lmap: LanguageNodeMap) -> int:
+ """Count ``&&`` / ``||`` / ``and`` / ``or`` operators in a condition.
+
+ Walks the subtree rooted at *node* but does not descend into nested
+ function bodies (lambdas / closures used as condition values are
+ rare and would skew the count).
+ """
+ if node is None:
+ return 0
+ count = 0
+ stack: list[Node] = [node]
+ while stack:
+ cur = stack.pop()
+ if cur is not node and cur.type in lmap.function_kinds:
+ continue
+ if _is_boolean_operator(cur, lmap):
+ count += 1
+ for child in cur.children:
+ stack.append(child)
+ return count
+
+
+def _enclosing_construct(node: Node, lmap: LanguageNodeMap) -> str:
+ if node.type in lmap.loop_kinds:
+ return "for" if "for" in node.type else "while"
+ if node.type in lmap.case_kinds:
+ return "case"
+ if node.type in lmap.catch_kinds:
+ return "catch"
+ if node.type in lmap.branch_kinds:
+ if "ternary" in node.type or "conditional" in node.type:
+ return "ternary"
+ return "if"
+ return "if"
+
+
+def _condition_subtrees(node: Node) -> list[Node]:
+ """Best-effort: pull the *condition* parts out of a branch/loop node.
+
+ Prefers the tree-sitter ``condition`` named field where exposed
+ (Python, TS, Java, Rust, Go all use it for most branch shapes).
+ Falls back to all direct children except recognised body fields and
+ syntactic punctuation.
+ """
+ cond = node.child_by_field_name("condition")
+ if cond is not None:
+ return [cond]
+ # Switch case value (TS, Java)
+ value = node.child_by_field_name("value")
+ if value is not None and "case" in node.type:
+ return [value]
+ # Fallback: direct children minus bodies / blocks.
+ body_nodes: set[int] = set()
+ for fname in _BODY_FIELD_NAMES:
+ child = node.child_by_field_name(fname)
+ if child is not None:
+ body_nodes.add(child.id)
+ out: list[Node] = []
+ for child in node.children:
+ if child.id in body_nodes:
+ continue
+ if not child.is_named:
+ continue
+ if child.type in ("block", "compound_statement", "statement_block"):
+ continue
+ out.append(child)
+ return out
+
+
def _walk_function_body(
body_node: Node,
lmap: LanguageNodeMap,
-) -> tuple[int, int, int, int]:
- """Recursive AST walk. Returns (ccn, max_nesting, cognitive, bumps).
+) -> tuple[int, int, int, int, list[ConditionComplexity]]:
+ """Recursive AST walk. Returns (ccn, max_nesting, cognitive, bumps,
+ complex_conditions).
Starts CCN at 1 (the entry path). Nested function bodies are
skipped — they will (or already did) produce their own
@@ -111,12 +211,17 @@ def _walk_function_body(
contain nested control flow that reaches a depth of ≥ 2. A function
with several heavy independent branches is "bumpy" in
CodeScene/SonarSource terminology.
+
+ ``complex_conditions`` is an additive side-channel — collected for
+ every branch/loop/case construct encountered. The CCN / cognitive
+ accumulation logic is unchanged.
"""
ccn = 1
max_nesting = 0
cognitive = 0
bumps = 0
+ conditions: list[ConditionComplexity] = []
def _recurse(node: Node, depth: int) -> None:
nonlocal ccn, max_nesting, cognitive
@@ -138,6 +243,21 @@ def _walk_function_body(
):
ccn_increment = 1
nesting_increment = 1
+ # Side-channel: count compound boolean ops in this
+ # construct's condition. Does not affect ccn/cognitive
+ # (boolean operators are still tallied independently by
+ # the regular recursion below).
+ op_count = 0
+ for sub in _condition_subtrees(node):
+ op_count += _count_boolean_ops_in_condition(sub, lmap)
+ if op_count > 0:
+ conditions.append(
+ ConditionComplexity(
+ line=node.start_point[0] + 1,
+ operator_count=op_count,
+ enclosing_construct=_enclosing_construct(node, lmap),
+ )
+ )
elif node.type in lmap.try_kinds:
# TRY opens a nesting level but does not branch on its own.
nesting_increment = 1
@@ -173,7 +293,7 @@ def _walk_function_body(
if child_peak >= 2:
bumps += 1
- return ccn, max_nesting, cognitive, bumps
+ return ccn, max_nesting, cognitive, bumps, conditions
def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
@@ -240,7 +360,7 @@ def walk_file_complexity(
results: list[FunctionComplexity] = []
for fn_node in _collect_function_nodes(tree.root_node, lmap):
body = fn_node.child_by_field_name("body") or fn_node
- ccn, max_nest, cognitive, bumps = _walk_function_body(body, lmap)
+ ccn, max_nest, cognitive, bumps, conditions = _walk_function_body(body, lmap)
results.append(
FunctionComplexity(
name=_find_name(fn_node),
@@ -252,6 +372,7 @@ def walk_file_complexity(
nloc=_count_nloc(body, source),
bumps=bumps,
param_count=_count_parameters(fn_node),
+ complex_conditions=conditions,
)
)
return results
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index edd4f7665..6bea87e9a 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -26,6 +26,7 @@ from typing import Any
import structlog
from .biomarkers import FileContext, detect_all
+from .biomarkers.base import HasEdge
from .complexity import FunctionComplexity, walk_file_complexity
from .coverage import is_test_file as _coverage_is_test_file
from .duplication import DuplicationReport, detect_clones
@@ -65,6 +66,44 @@ def _fallback_module(rel_path: str) -> str | None:
return head or None
+class _ImportEdgeView:
+ """Thin ``HasEdge`` adapter over a NetworkX DiGraph.
+
+ The graph stores ``edge_type`` as an attribute on each (single)
+ edge between two file nodes. We look it up directly rather than
+ pulling NetworkX into the biomarker test surface.
+ """
+
+ __slots__ = ("_graph",)
+
+ def __init__(self, graph: Any) -> None:
+ self._graph = graph
+
+ def has_edge(self, src: str, dst: str, key: str = "imports") -> bool:
+ g = self._graph
+ if g is None:
+ return False
+ try:
+ if not g.has_edge(src, dst):
+ return False
+ data = g.get_edge_data(src, dst) or {}
+ except Exception:
+ return False
+ return data.get("edge_type") == key
+
+
+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():
+ if not isinstance(meta, dict):
+ continue
+ try:
+ out[path] = int(meta.get("commit_count_total") or 0)
+ except (TypeError, ValueError):
+ continue
+ return out
+
+
def _has_paired_test_file(rel_path: str, all_paths: set[str]) -> bool:
"""Heuristic: does any other file look like a test for *rel_path*?
@@ -139,6 +178,8 @@ class HealthAnalyzer:
# is symbol-level; we use file-level in-degree as the dependents
# signal (cheap, deterministic, conservative).
all_paths = {pf.file_info.path for pf in self.parsed_files}
+ repo_commit_counts = _build_repo_commit_counts(self.git_meta_map)
+ graph_view: HasEdge | None = _ImportEdgeView(self.graph) if self.graph is not None else None
# Duplication runs once, up-front, so each file biomarker can see
# its clone list. Cheap when the repo is small; when disabled
@@ -178,7 +219,13 @@ class HealthAnalyzer:
if name not in file_disabled:
file_disabled.append(name)
file_metric, file_findings = self._evaluate_file(
- pf, fc_list, all_paths, disabled=file_disabled, dup_report=dup_report
+ pf,
+ fc_list,
+ all_paths,
+ disabled=file_disabled,
+ dup_report=dup_report,
+ graph_view=graph_view,
+ repo_commit_counts=repo_commit_counts,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -229,6 +276,8 @@ class HealthAnalyzer:
changed_set: set[str] | None = set(changed_files) if changed_files is not None else None
all_paths = {pf.file_info.path for pf in self.parsed_files}
+ repo_commit_counts = _build_repo_commit_counts(self.git_meta_map)
+ graph_view: HasEdge | None = _ImportEdgeView(self.graph) if self.graph is not None else None
if "dry_violation" in disabled:
dup_report = DuplicationReport()
@@ -283,7 +332,13 @@ class HealthAnalyzer:
if name not in file_disabled:
file_disabled.append(name)
file_metric, file_findings = self._evaluate_file(
- pf, fc_list, all_paths, disabled=file_disabled, dup_report=dup_report
+ pf,
+ fc_list,
+ all_paths,
+ disabled=file_disabled,
+ dup_report=dup_report,
+ graph_view=graph_view,
+ repo_commit_counts=repo_commit_counts,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -338,6 +393,8 @@ class HealthAnalyzer:
*,
disabled: list[str],
dup_report: DuplicationReport,
+ graph_view: HasEdge | None = None,
+ repo_commit_counts: dict[str, int] | None = None,
) -> tuple[HealthFileMetricData, list[HealthFindingData]]:
file_path = pf.file_info.path
@@ -384,6 +441,8 @@ class HealthAnalyzer:
total_coverable_lines=total_coverable_lines,
clones=list(clones),
duplication_pct=dup_pct,
+ graph_view=graph_view,
+ repo_commit_counts=repo_commit_counts or {},
)
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.py
index e0dcad4c1..c8ea53b98 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -4,13 +4,17 @@ Each file starts at 10.0. Biomarker findings deduct; deductions are
capped per category so no single category can drive the score below the
cap. Final score is clamped to [1.0, 10.0].
-The category caps in §5 of the plan:
+The recalibrated category caps (plan §3.1):
- structural_complexity -> -3.5
- size_and_complexity -> -2.0
- duplication -> -1.5
+ organizational -> -3.5 # was -1.0 (process-aware signals)
+ structural_complexity -> -2.5 # was -3.5
test_coverage -> -2.0
- organizational -> -1.0
+ size_and_complexity -> -1.5 # was -2.0
+ duplication -> -1.0 # was -1.5
+
+Per-biomarker weight multipliers (plan §3.2 Option A) are applied to
+the per-finding raw deduction *before* category capping, so the strongest
+empirical predictors are no longer suppressed by uniform severity values.
"""
from __future__ import annotations
@@ -22,11 +26,11 @@ from .models import HealthFileMetricData, HealthFindingData, Severity
# Per-category max deduction.
CATEGORY_CAPS: dict[str, float] = {
- "structural_complexity": 3.5,
- "size_and_complexity": 2.0,
- "duplication": 1.5,
+ "organizational": 3.5,
+ "structural_complexity": 2.5,
"test_coverage": 2.0,
- "organizational": 1.0,
+ "size_and_complexity": 1.5,
+ "duplication": 1.0,
}
# Per-biomarker deduction by severity. The scorer caps the per-category
@@ -38,6 +42,18 @@ _SEVERITY_DEDUCTION: dict[Severity, float] = {
Severity.CRITICAL: 2.0,
}
+# Per-biomarker weight multiplier (plan §3.2 Option A). Applied to the
+# severity deduction BEFORE category capping. Lets stronger empirical
+# predictors deduct more without re-tuning the severity table itself.
+# Unknown biomarkers fall back to 1.0.
+_BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
+ "developer_congestion": 1.5,
+ "untested_hotspot": 1.3,
+ "function_hotspot": 1.2,
+ "hidden_coupling": 1.0,
+ "knowledge_loss": 0.4,
+}
+
# Map biomarker name → category. Kept here (single source of truth)
# rather than on each biomarker class because some biomarkers naturally
# span categories and we may want to retune without re-deploying.
@@ -45,6 +61,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"brain_method": "structural_complexity",
"nested_complexity": "structural_complexity",
"bumpy_road": "structural_complexity",
+ "complex_conditional": "structural_complexity",
"complex_method": "size_and_complexity",
"large_method": "size_and_complexity",
"primitive_obsession": "size_and_complexity",
@@ -53,6 +70,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"coverage_gap": "test_coverage",
"developer_congestion": "organizational",
"knowledge_loss": "organizational",
+ "hidden_coupling": "organizational",
}
@@ -60,6 +78,11 @@ def severity_deduction(sev: Severity) -> float:
return _SEVERITY_DEDUCTION.get(sev, 0.5)
+def biomarker_weight(name: str) -> float:
+ """Per-biomarker multiplier; 1.0 for unknown biomarkers."""
+ return _BIOMARKER_WEIGHT_MULTIPLIER.get(name, 1.0)
+
+
def biomarker_category(name: str) -> str:
"""Default to ``size_and_complexity`` for unknown biomarkers."""
return _BIOMARKER_CATEGORY.get(name, "size_and_complexity")
@@ -78,7 +101,8 @@ def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:
raw: dict[str, list[tuple[int, float]]] = {}
for idx, r in enumerate(results_list):
cat = biomarker_category(r.biomarker_type)
- raw.setdefault(cat, []).append((idx, severity_deduction(r.severity)))
+ weighted = severity_deduction(r.severity) * biomarker_weight(r.biomarker_type)
+ raw.setdefault(cat, []).append((idx, weighted))
per_result = [0.0] * len(results_list)
total = 0.0
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index 9658a8a97..a30d72304 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -72,6 +72,18 @@ _TEMPLATES: dict[str, str] = {
"at once — clarify ownership, or split the file along its "
"natural seams so contributors don't collide."
),
+ "hidden_coupling": (
+ "Surface the hidden dependency. This file co-changes with a "
+ "sibling that it doesn't import — promote the implicit contract "
+ "into a shared module, type, or interface so the coupling is "
+ "visible at the source level instead of hidden in commit history."
+ ),
+ "complex_conditional": (
+ "Decompose the boolean expression. Extract sub-clauses into "
+ "named predicates that explain *what* each branch checks; "
+ "compound conditions of three or more operators are usually "
+ "two policies fighting for one line."
+ ),
"knowledge_loss": (
"Document the surviving knowledge. The primary author(s) of "
"this file are no longer active — pair-program with someone "
diff --git a/tests/fixtures/lang_samples/go/conditionals.go b/tests/fixtures/lang_samples/go/conditionals.go
new file mode 100644
index 000000000..bd0a01db4
--- /dev/null
+++ b/tests/fixtures/lang_samples/go/conditionals.go
@@ -0,0 +1,22 @@
+package conditionals
+
+func ThreeOps(a, b, c, d bool) int {
+ if a && b && c && d {
+ return 1
+ }
+ return 0
+}
+
+func SixOps(a, b, c, d, e, f, g bool) int {
+ for a && b && c && d && e && f && g {
+ return 1
+ }
+ return 0
+}
+
+func TwoOps(a, b, c bool) int {
+ if a && b || c {
+ return 1
+ }
+ return 0
+}
diff --git a/tests/fixtures/lang_samples/java/Conditionals.java b/tests/fixtures/lang_samples/java/Conditionals.java
new file mode 100644
index 000000000..2a1b71d11
--- /dev/null
+++ b/tests/fixtures/lang_samples/java/Conditionals.java
@@ -0,0 +1,22 @@
+public class Conditionals {
+ public int threeOps(boolean a, boolean b, boolean c, boolean d) {
+ if (a && b && c && d) {
+ return 1;
+ }
+ return 0;
+ }
+
+ public int sixOps(boolean a, boolean b, boolean c, boolean d, boolean e, boolean f, boolean g) {
+ while (a && b && c && d && e && f && g) {
+ return 1;
+ }
+ return 0;
+ }
+
+ public int twoOps(boolean a, boolean b, boolean c) {
+ if (a && b || c) {
+ return 1;
+ }
+ return 0;
+ }
+}
diff --git a/tests/fixtures/lang_samples/python/conditionals.py b/tests/fixtures/lang_samples/python/conditionals.py
new file mode 100644
index 000000000..90c8781f9
--- /dev/null
+++ b/tests/fixtures/lang_samples/python/conditionals.py
@@ -0,0 +1,16 @@
+def three_ops(a, b, c, d):
+ if a and b and c and d:
+ return 1
+ return 0
+
+
+def six_ops(a, b, c, d, e, f, g):
+ while a and b and c and d and e and f and g:
+ return 1
+ return 0
+
+
+def two_ops(a, b, c):
+ if a and b or c:
+ return 1
+ return 0
diff --git a/tests/fixtures/lang_samples/rust/conditionals.rs b/tests/fixtures/lang_samples/rust/conditionals.rs
new file mode 100644
index 000000000..c82270c09
--- /dev/null
+++ b/tests/fixtures/lang_samples/rust/conditionals.rs
@@ -0,0 +1,20 @@
+pub fn three_ops(a: bool, b: bool, c: bool, d: bool) -> i32 {
+ if a && b && c && d {
+ return 1;
+ }
+ 0
+}
+
+pub fn six_ops(a: bool, b: bool, c: bool, d: bool, e: bool, f: bool, g: bool) -> i32 {
+ while a && b && c && d && e && f && g {
+ return 1;
+ }
+ 0
+}
+
+pub fn two_ops(a: bool, b: bool, c: bool) -> i32 {
+ if a && b || c {
+ return 1;
+ }
+ 0
+}
diff --git a/tests/fixtures/lang_samples/typescript/conditionals.ts b/tests/fixtures/lang_samples/typescript/conditionals.ts
new file mode 100644
index 000000000..ae0ddd040
--- /dev/null
+++ b/tests/fixtures/lang_samples/typescript/conditionals.ts
@@ -0,0 +1,28 @@
+export function threeOps(a: boolean, b: boolean, c: boolean, d: boolean): number {
+ if (a && b && c && d) {
+ return 1;
+ }
+ return 0;
+}
+
+export function sixOps(
+ a: boolean,
+ b: boolean,
+ c: boolean,
+ d: boolean,
+ e: boolean,
+ f: boolean,
+ g: boolean,
+): number {
+ while (a && b && c && d && e && f && g) {
+ return 1;
+ }
+ return 0;
+}
+
+export function twoOps(a: boolean, b: boolean, c: boolean): number {
+ if (a && b || c) {
+ return 1;
+ }
+ return 0;
+}
diff --git a/tests/unit/health/test_complex_conditional.py b/tests/unit/health/test_complex_conditional.py
new file mode 100644
index 000000000..2b3353f93
--- /dev/null
+++ b/tests/unit/health/test_complex_conditional.py
@@ -0,0 +1,101 @@
+"""Cross-language tests for the ``complex_conditional`` biomarker."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.complex_conditional import (
+ ComplexConditionalDetector,
+)
+from repowise.core.analysis.health.complexity import walk_file_complexity
+from repowise.core.analysis.health.models import Severity
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples"
+
+
+def _walk(rel_path: str, language: str):
+ p = FIXTURES / rel_path
+ if not p.exists():
+ pytest.skip(f"fixture missing: {p}")
+ results = walk_file_complexity(str(p), language, p.read_bytes())
+ if not results:
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ return results
+
+
+def _ctx(metrics):
+ return FileContext(
+ file_path="x",
+ language="python",
+ nloc=10,
+ has_test_file=False,
+ module=None,
+ function_metrics={fc.name: fc for fc in metrics},
+ )
+
+
+def _find(results, name):
+ for r in results:
+ if r.name == name:
+ return r
+ return None
+
+
+def _assert_three_six_two(metrics, three: str, six: str, two: str):
+ findings = ComplexConditionalDetector().detect(_ctx(metrics))
+ by_fn = {f.function_name: f for f in findings}
+
+ # 3-op → flagged at LOW
+ assert three in by_fn, f"expected finding on {three} (3-op condition)"
+ assert by_fn[three].severity == Severity.LOW
+ assert by_fn[three].details["operator_count"] == 3
+
+ # 6-op → CRITICAL
+ assert six in by_fn, f"expected finding on {six} (6-op condition)"
+ assert by_fn[six].severity == Severity.CRITICAL
+ assert by_fn[six].details["operator_count"] == 6
+
+ # 2-op → not flagged
+ assert two not in by_fn, f"{two} (2-op) should not flag"
+
+
+def test_python_conditions():
+ metrics = _walk("python/conditionals.py", "python")
+ _assert_three_six_two(metrics, "three_ops", "six_ops", "two_ops")
+
+
+def test_typescript_conditions():
+ metrics = _walk("typescript/conditionals.ts", "typescript")
+ _assert_three_six_two(metrics, "threeOps", "sixOps", "twoOps")
+
+
+def test_go_conditions():
+ metrics = _walk("go/conditionals.go", "go")
+ _assert_three_six_two(metrics, "ThreeOps", "SixOps", "TwoOps")
+
+
+def test_java_conditions():
+ metrics = _walk("java/Conditionals.java", "java")
+ _assert_three_six_two(metrics, "threeOps", "sixOps", "twoOps")
+
+
+def test_rust_conditions():
+ metrics = _walk("rust/conditionals.rs", "rust")
+ _assert_three_six_two(metrics, "three_ops", "six_ops", "two_ops")
+
+
+def test_walker_emits_complex_conditions_field():
+ """Lock the new walker contract — assertion lives here so the
+ cross-language fixtures double as walker coverage."""
+ metrics = _walk("python/conditionals.py", "python")
+ fc = _find(metrics, "six_ops")
+ assert fc is not None
+ assert len(fc.complex_conditions) == 1
+ cond = fc.complex_conditions[0]
+ assert cond.operator_count == 6
+ assert cond.enclosing_construct == "while"
+ # Existing CCN field must still be populated (regression guard).
+ assert fc.ccn >= 7 # entry + while + 6 booleans
diff --git a/tests/unit/health/test_hidden_coupling.py b/tests/unit/health/test_hidden_coupling.py
new file mode 100644
index 000000000..ce9883682
--- /dev/null
+++ b/tests/unit/health/test_hidden_coupling.py
@@ -0,0 +1,185 @@
+"""Tests for the ``hidden_coupling`` biomarker."""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.hidden_coupling import (
+ HiddenCouplingDetector,
+)
+from repowise.core.analysis.health.models import Severity
+
+
+class _FakeGraph:
+ """Minimal ``HasEdge`` fake for unit tests."""
+
+ def __init__(self, edges: set[tuple[str, str, str]] | None = None) -> None:
+ # (src, dst, edge_type)
+ self._edges = edges or set()
+
+ def has_edge(self, src: str, dst: str, key: str = "imports") -> bool:
+ return (src, dst, key) in self._edges
+
+
+def _partners(d: dict[str, int]) -> str:
+ return json.dumps([{"file_path": p, "co_change_count": c} for p, c in d.items()])
+
+
+def _ctx(
+ path: str,
+ *,
+ partners: dict[str, int],
+ self_commits: int,
+ repo_commits: dict[str, int],
+ graph: _FakeGraph | None = None,
+) -> FileContext:
+ repo_commits = {**repo_commits, path: self_commits}
+ return FileContext(
+ file_path=path,
+ language="python",
+ nloc=120,
+ has_test_file=False,
+ module=None,
+ function_metrics={},
+ git_meta={
+ "commit_count_total": self_commits,
+ "co_change_partners_json": _partners(partners),
+ },
+ dependents_count=0,
+ graph_view=graph,
+ repo_commit_counts=repo_commits,
+ )
+
+
+def test_positive_python_pair_no_import_edge():
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": 18},
+ self_commits=20,
+ repo_commits={"src/billing.py": 22},
+ )
+ out = HiddenCouplingDetector().detect(ctx)
+ assert len(out) == 1
+ assert out[0].details["partner"] == "src/billing.py"
+ # 18 / min(20, 22) = 0.9 → CRITICAL
+ assert out[0].severity == Severity.CRITICAL
+
+
+def test_positive_ts_pair_at_medium():
+ ctx = _ctx(
+ "web/checkout.ts",
+ partners={"web/cart.ts": 6},
+ self_commits=10,
+ repo_commits={"web/cart.ts": 12},
+ )
+ out = HiddenCouplingDetector().detect(ctx)
+ assert len(out) == 1
+ # 6 / min(10, 12) = 0.6 → HIGH (>= 0.5, < 0.65 is MEDIUM; 0.6 -> MEDIUM)
+ assert out[0].severity == Severity.MEDIUM
+
+
+def test_negative_explicit_import_edge_suppresses():
+ graph = _FakeGraph({("src/payments.py", "src/billing.py", "imports")})
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": 18},
+ self_commits=20,
+ repo_commits={"src/billing.py": 22},
+ graph=graph,
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_negative_low_commit_count_noise_floor():
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": 3},
+ self_commits=4, # below MIN_COMMITS=5
+ repo_commits={"src/billing.py": 22},
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_negative_partner_below_noise_floor():
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": 3},
+ self_commits=20,
+ repo_commits={"src/billing.py": 3},
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_essential_tier_empty_partners_short_circuits():
+ """Plan §1.2.1: ESSENTIAL git tier leaves co_change_partners_json empty."""
+ ctx = FileContext(
+ file_path="src/payments.py",
+ language="python",
+ nloc=120,
+ has_test_file=False,
+ module=None,
+ function_metrics={},
+ git_meta={"commit_count_total": 100, "co_change_partners_json": "[]"},
+ dependents_count=0,
+ repo_commit_counts={"src/payments.py": 100, "src/billing.py": 100},
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+ # Also defend the literal absence of the field.
+ ctx.git_meta = {"commit_count_total": 100}
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_test_to_production_pair_is_filtered():
+ ctx = _ctx(
+ "src/__tests__/cart.test.ts",
+ partners={"src/cart.ts": 18},
+ self_commits=20,
+ repo_commits={"src/cart.ts": 22},
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []
+
+
+def test_findings_capped_at_top_three_partners():
+ partners = {
+ "src/a.py": 18,
+ "src/b.py": 17,
+ "src/c.py": 16,
+ "src/d.py": 15,
+ "src/e.py": 14,
+ }
+ repo_commits = {p: 20 for p in partners}
+ ctx = _ctx(
+ "src/payments.py",
+ partners=partners,
+ self_commits=20,
+ repo_commits=repo_commits,
+ )
+ out = HiddenCouplingDetector().detect(ctx)
+ assert len(out) == 3
+ # Sorted by correlation desc — top three are the highest counts.
+ assert [f.details["partner"] for f in out] == ["src/a.py", "src/b.py", "src/c.py"]
+
+
+def test_pair_dedupes_naturally_by_frozenset():
+ """Each side of a pair emits independently; the union dedupes via
+ ``frozenset({a, b})`` at the caller level. Verifies symmetry."""
+ a = _ctx(
+ "src/a.py",
+ partners={"src/b.py": 18},
+ self_commits=20,
+ repo_commits={"src/b.py": 22},
+ )
+ b = _ctx(
+ "src/b.py",
+ partners={"src/a.py": 18},
+ self_commits=22,
+ repo_commits={"src/a.py": 20},
+ )
+ out_a = HiddenCouplingDetector().detect(a)
+ out_b = HiddenCouplingDetector().detect(b)
+ pairs = {
+ frozenset({a.file_path, out_a[0].details["partner"]}),
+ frozenset({b.file_path, out_b[0].details["partner"]}),
+ }
+ assert pairs == {frozenset({"src/a.py", "src/b.py"})}
diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.py
index 81d1b25dd..494ed810e 100644
--- a/tests/unit/health/test_scoring.py
+++ b/tests/unit/health/test_scoring.py
@@ -35,8 +35,8 @@ def test_score_clamps_floor_at_one():
results = [_r("complex_method", Severity.CRITICAL) for _ in range(20)]
score, _ = score_file(results)
assert score >= 1.0
- # Cap on size_and_complexity is 2.0 → score should be 8.0.
- assert score == 8.0
+ # Cap on size_and_complexity is 1.5 (post-recalibration) → score 8.5.
+ assert score == 8.5
def test_category_cap_applied():
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index bfe5895bd..b2bd66812 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -1,9 +1,10 @@
"""Snapshot tests guarding scoring stability across refactors.
-Locks the published per-category caps, per-severity deductions, and the
-biomarker → category mapping. A change to any of these tables shifts every
-file's score on every repo using repowise, so this test exists to force
-the reviewer to acknowledge the impact before landing.
+Locks the published per-category caps, per-severity deductions, the
+per-biomarker weight multipliers, and the biomarker → category mapping.
+A change to any of these tables shifts every file's score on every repo
+using repowise, so this test exists to force the reviewer to acknowledge
+the impact before landing.
If a deliberate retune lands, regenerate the snapshot by updating the
``_EXPECTED_*`` constants below in the same PR — never silently.
@@ -15,17 +16,18 @@ from repowise.core.analysis.health.biomarkers.base import BiomarkerResult
from repowise.core.analysis.health.models import Severity
from repowise.core.analysis.health.scoring import (
_BIOMARKER_CATEGORY,
+ _BIOMARKER_WEIGHT_MULTIPLIER,
_SEVERITY_DEDUCTION,
CATEGORY_CAPS,
score_file,
)
_EXPECTED_CATEGORY_CAPS = {
- "structural_complexity": 3.5,
- "size_and_complexity": 2.0,
- "duplication": 1.5,
+ "organizational": 3.5,
+ "structural_complexity": 2.5,
"test_coverage": 2.0,
- "organizational": 1.0,
+ "size_and_complexity": 1.5,
+ "duplication": 1.0,
}
_EXPECTED_SEVERITY_DEDUCTION = {
@@ -35,10 +37,19 @@ _EXPECTED_SEVERITY_DEDUCTION = {
Severity.CRITICAL: 2.0,
}
+_EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
+ "developer_congestion": 1.5,
+ "untested_hotspot": 1.3,
+ "function_hotspot": 1.2,
+ "hidden_coupling": 1.0,
+ "knowledge_loss": 0.4,
+}
+
_EXPECTED_BIOMARKER_CATEGORY = {
"brain_method": "structural_complexity",
"nested_complexity": "structural_complexity",
"bumpy_road": "structural_complexity",
+ "complex_conditional": "structural_complexity",
"complex_method": "size_and_complexity",
"large_method": "size_and_complexity",
"primitive_obsession": "size_and_complexity",
@@ -47,6 +58,7 @@ _EXPECTED_BIOMARKER_CATEGORY = {
"coverage_gap": "test_coverage",
"developer_congestion": "organizational",
"knowledge_loss": "organizational",
+ "hidden_coupling": "organizational",
}
@@ -58,6 +70,10 @@ def test_severity_deductions_locked():
assert _SEVERITY_DEDUCTION == _EXPECTED_SEVERITY_DEDUCTION
+def test_biomarker_weight_multipliers_locked():
+ assert _BIOMARKER_WEIGHT_MULTIPLIER == _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER
+
+
def test_biomarker_to_category_locked():
assert _BIOMARKER_CATEGORY == _EXPECTED_BIOMARKER_CATEGORY
@@ -84,17 +100,27 @@ def test_known_fixture_score_is_stable():
_result("knowledge_loss", Severity.LOW),
]
score, _ = score_file(findings)
- # Math: structural cat = 2.0 + 1.2 = 3.2 (under 3.5 cap)
- # size_and_complexity = 0.7 (under 2.0 cap)
- # coverage = 1.2 (under 2.0 cap)
- # organizational = 0.3 (under 1.0 cap)
- # total deduction = 3.2 + 0.7 + 1.2 + 0.3 = 5.4 → 10 - 5.4 = 4.6
- assert score == 4.6
+ # Math (post-recalibration):
+ # structural = 2.0 + 1.2 = 3.2 → capped at 2.5
+ # size_and_cx = 0.7 (under 1.5 cap)
+ # coverage = 1.2 * 1.3 = 1.56 (under 2.0 cap)
+ # organizational = 0.3 * 0.4 = 0.12 (under 3.5 cap)
+ # total deduction = 2.5 + 0.7 + 1.56 + 0.12 = 4.88 → 10 - 4.88 = 5.12
+ assert score == 5.12
def test_category_cap_clamps_score():
- """Many critical structural findings should not exceed the -3.5 cap."""
+ """Many critical structural findings should not exceed the -2.5 cap."""
findings = [_result("brain_method", Severity.CRITICAL) for _ in range(10)]
score, _ = score_file(findings)
- # Cap at -3.5, so floor on this category alone is 6.5.
+ # Cap at -2.5, so floor on this category alone is 7.5.
+ assert score == 7.5
+
+
+def test_organizational_cap_now_dominant():
+ """Recalibration lifts organizational from -1.0 to -3.5 — verify a high-volume
+ developer_congestion stream now lands a real dent instead of being suppressed."""
+ findings = [_result("developer_congestion", Severity.CRITICAL) for _ in range(3)]
+ score, _ = score_file(findings)
+ # 3 * 2.0 * 1.5 = 9.0 weighted, capped at 3.5 → score = 6.5
assert score == 6.5