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): error-handling maintainability biomarker (#453)

Raghav Chamadiya9c6b6bebcfb1
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 99506f150..588aa063f 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -35,8 +35,9 @@ most:
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
| Test quality | −0.5 | large_assertion_block, duplicated_assertion_block |
+| Error handling | −0.5 | error_handling |
-Twenty-five biomarkers across the categories above. `function_hotspot` and
+Twenty-six biomarkers across the categories above. `function_hotspot` and
`code_age_volatility` are blame-based and sit in the organizational bucket —
both are tier-aware and stay silent on ESSENTIAL-tier repos until the per-line
blame index is built.
@@ -227,6 +228,19 @@ that overlap an assertion block on a test file. A change to the asserted
behaviour then has to be edited in several places — and usually isn't, so the
copies drift.
+**error_handling** — Swallowed-exception and unsafe-unwrap anti-patterns: an
+empty or comment-only `catch`/`except` body, a Python catch-all `except:` /
+`except Exception:`, Rust `.unwrap()` / `.expect()` / `panic!`-family macros,
+and Go's empty `if err != nil {}` or blank-identifier discard of a call's
+error. Detection is precision-first — only the unambiguous shapes fire, and an
+unsupported language or parse failure yields no signal rather than a guess.
+Each occurrence is a LOW finding anchored to its line, and the whole category
+is capped at −0.5 per file: this is an advisory maintainability flag (every
+linter is expected to surface `except: pass`), deliberately not a calibrated
+defect predictor — on the 21-repo benchmark it is AUC-neutral, so it is
+excluded from the weight calibration and bounded so it can never move a file's
+score by more than half a point.
+
## Test coverage
Pass coverage reports straight into the analyzer:
@@ -332,7 +346,7 @@ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)
| Feature | Repowise | CodeScene | DeepSource | Sourcery |
|----------------------------------|:--:|:--:|:--:|:--:|
-| Code health score (1–10) | ✅ 25 biomarkers | ✅ 25–30 | ❌ | ❌ |
+| Code health score (1–10) | ✅ 26 biomarkers | ✅ 25–30 | ❌ | ❌ |
| Brain Method detection | ✅ | ✅ | ❌ | ❌ |
| Low cohesion (LCOM4) / god class | ✅ | ✅ | ❌ | ❌ |
| Test coverage intelligence | ✅ LCOV/Cobertura/Clover/JSON | ❌ | ❌ | ❌ |
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 8577bd6eb..44507a025 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -110,7 +110,8 @@ analysis/health/
├── ownership_risk.py
├── churn_risk.py
├── change_entropy.py
- └── co_change_scatter.py
+ ├── co_change_scatter.py
+ └── error_handling.py
```
### Persistence
@@ -317,7 +318,7 @@ higher than dormant ones.
---
-## 5. The 25 biomarkers and their categories
+## 5. The 26 biomarkers and their categories
Each biomarker is a stateless class implementing the `Biomarker` Protocol
from `biomarkers/base.py`:
@@ -338,6 +339,7 @@ class Biomarker(Protocol):
| Size & complexity | −1.5 | complex_method, large_method, primitive_obsession |
| Duplication | −1.0 | dry_violation |
| Test quality | −0.5 | large_assertion_block, duplicated_assertion_block |
+| Error handling | −0.5 | error_handling |
`large_assertion_block` and `duplicated_assertion_block` are the two
**test-quality** smells (see §5.3). They fire only on test files and sit in
@@ -431,6 +433,23 @@ references (a static utility, or an unmapped language) reports `lcom4 = 1`
turn signal on — never produce a false-positive flood. See
`complexity/README.md` for the full heuristic and its limits.
+`error_handling` is the **advisory maintainability** biomarker: swallowed
+catches (an empty/comment-only `catch` / `except: pass` body), Python
+catch-all `except:` / `except Exception:`, Rust `.unwrap()` / `.expect()` /
+panic-family macros, and Go's empty `if err != nil {}` or blank-identifier
+discard of a call's error. The walker collects each occurrence (with its
+line) in a whole-tree pass — module-level code included — reusing the
+`LanguageNodeMap` catch kinds for the seven catch-shaped languages and
+dedicated recognizers for Rust/Go; an unsupported language or parse failure
+yields no hits ("no signal", never a guess). The biomarker emits one LOW
+finding per occurrence (0.15 after its floored 0.5 weight) in its own
+`error_handling` category capped at −0.5, mirroring `test_quality`'s
+advisory framing. It is deliberately **excluded from the defect-weight
+calibration**: on the 21-repo / 9-language T0 benchmark it is AUC-neutral
+(OOF delta ≈ 0, CI crosses zero) but size-orthogonal and the least redundant
+signal tested, and it ships because users expect `except: pass` flagged —
+bounded so it can never move a file by more than half a point.
+
### 5.3 Assertion-block walker metrics (test-quality)
The same single walker pass records `assertion_blocks` on each
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 6aa20124e..ce96c30d8 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md
@@ -9,7 +9,7 @@ class Biomarker(Protocol):
def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...
```
-## Registered detectors (24)
+## Registered detectors (26)
Structural complexity (cap −2.5):
- `brain_method` — symbols simultaneously long, complex, and central. The
@@ -83,6 +83,20 @@ Test quality (cap −0.5, test files only):
- `duplicated_assertion_block` — copy-pasted assertion runs across tests,
found by intersecting the clone detector with assertion spans.
+Error handling (cap −0.5, own category `error_handling`):
+- `error_handling` — swallowed-exception / unsafe-unwrap anti-patterns: an
+ empty or trivial `catch`/`except` body (Python/JS/TS/Java/Kotlin/C#/C++), a
+ Python catch-all `except:` / `except Exception:`, Rust `.unwrap()` /
+ `.expect()` / panic-family macros, and Go's empty `if err != nil {}` or
+ blank-identifier discard of a call's error. One LOW finding per occurrence
+ (0.15 after the floored 0.5 weight), bounded at 0.5/file by the category
+ cap. **A maintainability flag, not a defect predictor** — AUC-neutral on
+ the 21-repo T0 benchmark and deliberately excluded from the defect
+ calibration roster; it ships because developers expect a health tool to
+ flag `except: pass`. Detection is precision-first (unambiguous shapes only;
+ unsupported language / parse failure ⇒ no signal) and runs as a whole-tree
+ pass in the complexity walker, so module-level code is covered too.
+
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
@@ -110,6 +124,8 @@ table alone would allow.
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.
+- `error_handling_hits` — `list[ErrorHandlingHit]` (kind + line) from the
+ walker's whole-tree anti-pattern pass; empty means "no signal".
## 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 c3a00c2b6..60b1cf561 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -6,7 +6,7 @@ from dataclasses import dataclass, field
from typing import Any, Protocol
from ....ingestion.git_indexer.function_blame import BlameIndex
-from ..complexity import ClassComplexity, FunctionComplexity
+from ..complexity import ClassComplexity, ErrorHandlingHit, FunctionComplexity
from ..duplication import ClonePair
from ..models import Severity
@@ -95,6 +95,12 @@ class FileContext:
# ownership findings are downgraded to informational severity unless
# corroborated (issue #361).
repo_active_contributors_90d: int | None = None
+ # Error-handling anti-pattern occurrences (swallowed catch, bare
+ # except, unsafe unwrap, discarded Go error) collected by the
+ # complexity walker's whole-tree pass. Empty when the language is
+ # unsupported or parsing failed — the documented "no signal" outcome.
+ # Consumed by the ``error_handling`` biomarker.
+ error_handling_hits: list[ErrorHandlingHit] = field(default_factory=list)
# A repo whose trailing-90-day window has at most this many active human
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py
new file mode 100644
index 000000000..f027d62db
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py
@@ -0,0 +1,56 @@
+"""Error Handling — swallowed-exception / unsafe-unwrap anti-patterns.
+
+Surfaces the error-handling smells every linter is expected to flag: an
+empty ``catch`` / ``except: pass``, a Python catch-all ``except:``, a
+Rust ``.unwrap()`` / ``panic!``, a Go error checked-then-ignored or
+discarded via the blank identifier. One LOW finding per occurrence, each
+anchored to its line.
+
+This is a bounded maintainability signal, NOT a defect predictor: on the
+21-repo / 9-language T0 benchmark it is AUC-neutral (OOF delta ~0, CI
+crosses zero) but size-orthogonal and the least redundant signal tested
+(max |rho| ~0.21 vs the calibrated roster; churn rho ~0.02). It therefore
+ships in its own ``error_handling`` category with an advisory 0.5 cap and
+a floored 0.5 weight, and is excluded from the defect-calibration roster.
+
+Detection happens in the complexity walker's whole-tree pass (see
+``complexity.walker._collect_error_handling``); this detector just lifts
+the pre-collected hits into findings. Precision-first: unsupported
+languages and parse failures yield zero hits, never a false positive.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_REASONS: dict[str, str] = {
+ "swallowed_catch": "caught exception is swallowed without any handling",
+ "bare_except": "catch-all except hides every error, including KeyboardInterrupt",
+ "unsafe_unwrap": "unwrap/expect/panic turns a recoverable error into a crash",
+ "go_swallow": "error value is checked then ignored, or discarded via the blank identifier",
+}
+
+
+class ErrorHandlingDetector:
+ name = "error_handling"
+ category = "error_handling"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.error_handling_hits:
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.LOW,
+ function_name=None,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"kind": hit.kind},
+ reason=_REASONS.get(hit.kind, hit.kind),
+ )
+ )
+ return out
+
+
+BIOMARKER = ErrorHandlingDetector()
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 a22173a6b..2787f89a8 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -25,6 +25,7 @@ from .coverage_gradient import CoverageGradientDetector
from .developer_congestion import DeveloperCongestionDetector
from .dry_violation import DryViolationDetector
from .duplicated_assertion_block import DuplicatedAssertionBlockDetector
+from .error_handling import ErrorHandlingDetector
from .function_hotspot import FunctionHotspotDetector
from .god_class import GodClassDetector
from .hidden_coupling import HiddenCouplingDetector
@@ -64,6 +65,7 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
PriorDefectDetector, # type: ignore[list-item]
LargeAssertionBlockDetector, # type: ignore[list-item]
DuplicatedAssertionBlockDetector, # type: ignore[list-item]
+ ErrorHandlingDetector, # 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 448bc6bdd..9070a13d8 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from .walker import (
ClassComplexity,
ConditionComplexity,
+ ErrorHandlingHit,
FileComplexity,
FunctionComplexity,
walk_file,
@@ -14,6 +15,7 @@ from .walker import (
__all__ = [
"ClassComplexity",
"ConditionComplexity",
+ "ErrorHandlingHit",
"FileComplexity",
"FunctionComplexity",
"walk_file",
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 eaa19ebbe..1a61cdb70 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -20,7 +20,7 @@ their containing function's metrics — they do not produce their own
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from typing import TYPE_CHECKING
import structlog
@@ -108,6 +108,29 @@ class ClassComplexity:
field_count: int = 0
+@dataclass(frozen=True)
+class ErrorHandlingHit:
+ """One error-handling anti-pattern occurrence in a file.
+
+ Collected by the walker's whole-tree pass (see
+ ``_collect_error_handling``) and consumed by the ``error_handling``
+ biomarker. ``kind`` is one of:
+
+ - ``swallowed_catch`` — a catch/except whose body has no real handling
+ (empty, or only ``pass`` / ``...`` / a docstring / comments).
+ - ``bare_except`` — Python ``except:`` / ``except Exception:`` /
+ ``except BaseException:`` (catch-all) regardless of body.
+ - ``unsafe_unwrap`` — Rust ``.unwrap()`` / ``.expect()`` /
+ ``.unwrap_unchecked()`` calls and ``panic!`` / ``unreachable!`` /
+ ``todo!`` / ``unimplemented!`` macros (latent panic-on-error).
+ - ``go_swallow`` — Go empty ``if err != nil {}`` block, or a
+ blank-identifier discard of a multi-return call's value.
+ """
+
+ kind: str
+ line: int # 1-indexed
+
+
@dataclass
class FileComplexity:
"""Walker output for one file: per-function and per-class metrics.
@@ -119,6 +142,10 @@ class FileComplexity:
functions: list[FunctionComplexity]
classes: list[ClassComplexity]
file_nloc: int = 0
+ # Error-handling anti-pattern occurrences (whole-tree pass). Empty when
+ # the language is unsupported or parsing failed — "no signal", never a
+ # false positive.
+ error_handling_hits: list[ErrorHandlingHit] = field(default_factory=list)
# Leaf node types that carry a declared name at the bottom of a C/C++
@@ -619,6 +646,154 @@ def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:
return out
+# ----------------------------------------------------------------------
+# Error-handling anti-pattern detection (error_handling biomarker)
+# ----------------------------------------------------------------------
+# Ported from the bench-validated detector (24/24 fixtures across 11
+# languages). Precision-first: every detector targets the unambiguous
+# shape and degrades to "no signal" rather than guessing.
+
+# Block-like body node types of a catch/except clause.
+_EH_BLOCK_KINDS = frozenset({"block", "statement_block", "compound_statement"})
+# Statement node types that count as "no real handling" inside a catch body.
+_EH_TRIVIAL_STMT = frozenset({"comment", "pass_statement", "line_comment", "block_comment"})
+# Rust: each of these is a latent panic-on-error.
+_RUST_UNWRAP_METHODS = frozenset({"unwrap", "expect", "unwrap_unchecked"})
+_RUST_PANIC_MACROS = frozenset({"panic", "unreachable", "todo", "unimplemented"})
+
+
+def _eh_text(node: Node) -> str:
+ return (node.text or b"").decode("utf-8", errors="replace")
+
+
+def _eh_named(node: Node) -> list[Node]:
+ return [c for c in node.children if c.is_named]
+
+
+def _eh_find_body_block(clause: Node) -> Node | None:
+ """The block-like child of a catch/except clause (its handler body)."""
+ for c in clause.children:
+ if c.type in _EH_BLOCK_KINDS:
+ return c
+ # Kotlin catch_block / some grammars nest the block one level down.
+ for c in clause.children:
+ for g in c.children:
+ if g.type in _EH_BLOCK_KINDS:
+ return g
+ return None
+
+
+def _eh_is_trivial_stmt(stmt: Node, language: str) -> bool:
+ if stmt.type in _EH_TRIVIAL_STMT:
+ return True
+ if language == "python" and stmt.type == "expression_statement":
+ inner = _eh_named(stmt)
+ if not inner:
+ return True
+ # ``...`` or a docstring as the entire statement.
+ if inner[0].type in ("ellipsis", "string"):
+ return True
+ return False
+
+
+def _eh_body_is_swallowed(block: Node, language: str) -> bool:
+ real = [c for c in _eh_named(block) if not _eh_is_trivial_stmt(c, language)]
+ return len(real) == 0
+
+
+def _eh_is_bare_except(clause: Node) -> bool:
+ """Python ``except:`` / ``except Exception:`` / ``except BaseException:``."""
+ kids = [c for c in clause.children if c.type != "comment"]
+ after = [c for c in kids if c.type not in ("except", ":") and c.type not in _EH_BLOCK_KINDS]
+ if not after:
+ return True # bare ``except:``
+ # ``except Exception:`` / ``except BaseException:`` (single catch-all
+ # identifier — a tuple of specific types or an ``as`` binding on a
+ # specific type does not match).
+ first = after[0]
+ return first.type == "identifier" and _eh_text(first) in ("Exception", "BaseException")
+
+
+def _eh_rust_hit(node: Node) -> bool:
+ """True when *node* is an unwrap/expect call or a panic-family macro."""
+ if node.type == "call_expression":
+ fn = node.child_by_field_name("function")
+ if fn is not None and fn.type == "field_expression":
+ fld = fn.child_by_field_name("field")
+ return fld is not None and _eh_text(fld) in _RUST_UNWRAP_METHODS
+ return False
+ if node.type == "macro_invocation":
+ mac = node.child_by_field_name("macro")
+ return mac is not None and _eh_text(mac) in _RUST_PANIC_MACROS
+ return False
+
+
+def _eh_go_cond_is_err_check(cond_text: str) -> bool:
+ t = cond_text.replace(" ", "")
+ return "err!=nil" in t or "err==nil" in t
+
+
+def _eh_go_hit(node: Node) -> bool:
+ """Go: empty ``if err != nil {}`` or blank-identifier discard of a call."""
+ if node.type == "if_statement":
+ cond = node.child_by_field_name("condition")
+ cons = node.child_by_field_name("consequence")
+ return (
+ cond is not None
+ and cons is not None
+ and _eh_go_cond_is_err_check(_eh_text(cond))
+ and len(_eh_named(cons)) == 0
+ )
+ if node.type in ("short_var_declaration", "assignment_statement"):
+ left = node.child_by_field_name("left")
+ right = node.child_by_field_name("right")
+ if left is None or right is None:
+ return False
+ left_kids = _eh_named(left)
+ has_blank = any(c.type == "blank_identifier" or _eh_text(c) == "_" for c in left_kids)
+ right_is_call = any(c.type == "call_expression" for c in _eh_named(right)) or (
+ right.type == "expression_list"
+ and any(c.type == "call_expression" for c in _eh_named(right))
+ )
+ # Multi-return discard: ≥2 LHS targets, a call on the RHS, a blank present.
+ return has_blank and len(left_kids) >= 2 and right_is_call
+ return False
+
+
+def _collect_error_handling(
+ root: Node, language: str, lmap: LanguageNodeMap
+) -> list[ErrorHandlingHit]:
+ """Whole-tree pass: every error-handling anti-pattern with its line.
+
+ Catch-clause shapes reuse the ``LanguageNodeMap`` catch kinds (Python
+ ``except_clause``; JS/TS/Java/C++/C# ``catch_clause``; Kotlin
+ ``catch_block``); Rust and Go have no catch nodes and use their own
+ recognizers. Module-level code is covered too — anti-patterns are not
+ confined to function bodies.
+ """
+ hits: list[ErrorHandlingHit] = []
+ catch_kinds = lmap.catch_kinds
+ is_python = language == "python"
+ is_rust = language == "rust"
+ is_go = language == "go"
+ stack: list[Node] = [root]
+ while stack:
+ node = stack.pop()
+ if catch_kinds and node.type in catch_kinds:
+ block = _eh_find_body_block(node)
+ if block is not None and _eh_body_is_swallowed(block, language):
+ hits.append(ErrorHandlingHit("swallowed_catch", node.start_point[0] + 1))
+ if is_python and _eh_is_bare_except(node):
+ hits.append(ErrorHandlingHit("bare_except", node.start_point[0] + 1))
+ elif is_rust and _eh_rust_hit(node):
+ hits.append(ErrorHandlingHit("unsafe_unwrap", node.start_point[0] + 1))
+ elif is_go and _eh_go_hit(node):
+ hits.append(ErrorHandlingHit("go_swallow", node.start_point[0] + 1))
+ stack.extend(node.children)
+ hits.sort(key=lambda h: h.line)
+ return hits
+
+
# ----------------------------------------------------------------------
# Class-level analysis (LCOM4 / god-class)
# ----------------------------------------------------------------------
@@ -915,6 +1090,7 @@ def walk_file(
functions=functions,
classes=classes,
file_nloc=_count_file_nloc_tree(tree.root_node, source),
+ error_handling_hits=_collect_error_handling(tree.root_node, language, lmap),
)
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 0e18e869f..91fb8d5cb 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -659,6 +659,7 @@ class HealthAnalyzer:
blame_index=blame_index,
repo_function_mod_p80=repo_function_mod_p80,
repo_active_contributors_90d=repo_active_contributors_90d,
+ error_handling_hits=fcx.error_handling_hits,
)
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 23eaec471..749df74b9 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -43,6 +43,13 @@ CATEGORY_CAPS: dict[str, float] = {
# Test-quality smells are mild, advisory signals - a small cap keeps a
# noisy test file from dominating its own health score.
"test_quality": 0.5,
+ # Error-handling anti-patterns (swallowed catch / bare except / unsafe
+ # unwrap / discarded Go error) are an advisory maintainability signal,
+ # not a calibrated defect predictor (AUC-neutral on the 21-repo T0
+ # benchmark; size-orthogonal, least redundant signal tested). Own
+ # capped category so the bounded deduction can never squeeze - or be
+ # squeezed by - the predictive categories.
+ "error_handling": 0.5,
}
# Per-biomarker deduction by severity. The scorer caps the per-category
@@ -113,6 +120,12 @@ _BIOMARKER_WEIGHT_MULTIPLIER: dict[str, float] = {
"primitive_obsession": 0.5,
"dry_violation": 0.5,
"knowledge_loss": 0.4, # confirmed weak-negative since Phase 1
+ # Error-handling anti-patterns: maintainability flag, NOT a fitted
+ # predictor - deliberately excluded from the calibration roster (same
+ # treatment as governance biomarkers). Floored weight + LOW severity
+ # (0.3 x 0.5 = 0.15/finding) + the 0.5 category cap keep the impact
+ # bounded at half a point per file regardless of hit count.
+ "error_handling": 0.5,
# (coverage_gap, hidden_coupling, large_assertion_block,
# duplicated_assertion_block default to 1.0 - kept at prior)
# Governance - additive pass, weights are informational
@@ -150,6 +163,7 @@ _BIOMARKER_CATEGORY: dict[str, str] = {
"prior_defect": "organizational",
"large_assertion_block": "test_quality",
"duplicated_assertion_block": "test_quality",
+ "error_handling": "error_handling",
# Governance biomarkers - written by the additive governance pass
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index 5d0002b16..75eb22dd2 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -161,6 +161,13 @@ _TEMPLATES: dict[str, str] = {
"places and usually isn't. Extract the shared assertions into a "
"helper or parametrize the cases over the varying inputs."
),
+ "error_handling": (
+ "Handle or propagate the error. A swallowed exception, catch-all "
+ "except, unguarded unwrap, or discarded Go error turns failures "
+ "into silent misbehavior — log and re-raise, narrow the caught "
+ "type, replace unwrap with the ? operator or a match, or check "
+ "the error you are currently discarding."
+ ),
"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/unit/health/test_error_handling.py b/tests/unit/health/test_error_handling.py
new file mode 100644
index 000000000..e8117c661
--- /dev/null
+++ b/tests/unit/health/test_error_handling.py
@@ -0,0 +1,207 @@
+"""Unit tests for the error-handling anti-pattern detection.
+
+The 24 fixtures below are ported verbatim from the bench-validated
+detector (11 languages, precision-first). Each asserts the per-kind hit
+counts the walker's whole-tree pass must produce. Like the other walker
+tests, language-pack availability is best-effort: a missing tree-sitter
+grammar skips rather than fails.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers.base import FileContext
+from repowise.core.analysis.health.biomarkers.error_handling import ErrorHandlingDetector
+from repowise.core.analysis.health.complexity import ErrorHandlingHit, walk_file
+from repowise.core.analysis.health.models import Severity
+
+# (language, source, expected per-kind counts, note)
+_FIXTURES = [
+ (
+ "python",
+ b"try:\n x()\nexcept Exception:\n pass\n",
+ {"swallowed_catch": 1, "bare_except": 1},
+ "empty Exception catch -> swallowed + bare",
+ ),
+ (
+ "python",
+ b"try:\n x()\nexcept ValueError:\n pass\n",
+ {"swallowed_catch": 1},
+ "empty specific catch -> swallowed, not bare",
+ ),
+ (
+ "python",
+ b"try:\n x()\nexcept:\n ...\n",
+ {"swallowed_catch": 1, "bare_except": 1},
+ "bare except + ellipsis body",
+ ),
+ (
+ "python",
+ b"try:\n x()\nexcept ValueError as e:\n logger.error(e)\n raise\n",
+ {},
+ "handled + re-raised -> clean",
+ ),
+ (
+ "python",
+ b"try:\n x()\nexcept ValueError:\n return None\n",
+ {},
+ "specific catch with real handling -> clean",
+ ),
+ ("python", b"def f():\n return 1\n", {}, "no try -> clean"),
+ ("javascript", b"try { go(); } catch (e) {}\n", {"swallowed_catch": 1}, "empty JS catch"),
+ (
+ "javascript",
+ b"try { go(); } catch (e) { console.error(e); }\n",
+ {},
+ "handled JS catch",
+ ),
+ (
+ "typescript",
+ b"try { go(); } catch (e) { /* ignore */ }\n",
+ {"swallowed_catch": 1},
+ "comment-only TS catch",
+ ),
+ (
+ "java",
+ b"class A { void m(){ try { go(); } catch (Exception e) {} } }\n",
+ {"swallowed_catch": 1},
+ "empty Java catch",
+ ),
+ (
+ "java",
+ b"class A { void m(){ try { go(); } catch (Exception e) { log(e); } } }\n",
+ {},
+ "handled Java catch",
+ ),
+ (
+ "kotlin",
+ b"fun f(){ try { go() } catch (e: Exception) {} }\n",
+ {"swallowed_catch": 1},
+ "empty Kotlin catch",
+ ),
+ (
+ "kotlin",
+ b"fun f(){ try { go() } catch (e: Exception) { log(e) } }\n",
+ {},
+ "handled Kotlin catch",
+ ),
+ (
+ "csharp",
+ b"class A{ void M(){ try { Go(); } catch (Exception e) {} } }\n",
+ {"swallowed_catch": 1},
+ "empty C# catch",
+ ),
+ (
+ "csharp",
+ b"class A{ void M(){ try { Go(); } catch (Exception e) { Log(e); } } }\n",
+ {},
+ "handled C# catch",
+ ),
+ (
+ "cpp",
+ b"void f(){ try { go(); } catch (std::exception& e) {} }\n",
+ {"swallowed_catch": 1},
+ "empty C++ catch",
+ ),
+ (
+ "cpp",
+ b"void f(){ try { go(); } catch (std::exception& e) { log(e); } }\n",
+ {},
+ "handled C++ catch",
+ ),
+ ("rust", b"fn f() { let x = g().unwrap(); }\n", {"unsafe_unwrap": 1}, "unwrap"),
+ (
+ "rust",
+ b'fn f() { let x = g().expect("boom"); panic!("x"); }\n',
+ {"unsafe_unwrap": 2},
+ "expect + panic!",
+ ),
+ (
+ "rust",
+ b"fn f() -> Result<i32,E> { let x = g()?; Ok(x) }\n",
+ {},
+ "? operator -> clean",
+ ),
+ (
+ "go",
+ b"func f() { v, _ := g(); _ = v }\n",
+ {"go_swallow": 1},
+ "blank discard of call return",
+ ),
+ ("go", b"func f() { if err != nil {} }\n", {"go_swallow": 1}, "empty if-err block"),
+ ("go", b"func f() { if err != nil { return err } }\n", {}, "handled if-err"),
+ (
+ "go",
+ b"func f() { x := g(); _ = x }\n",
+ {},
+ "single assign, no multi-return discard",
+ ),
+]
+
+
+def _grammar_available(language: str) -> bool:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ return False
+ try:
+ return _get_language(language) is not None
+ except Exception:
+ return False
+
+
+def _hits(language: str, source: bytes) -> list[ErrorHandlingHit]:
+ if not _grammar_available(language):
+ pytest.skip(f"tree-sitter language pack missing for {language}")
+ return walk_file("<fixture>", language, source).error_handling_hits
+
+
+ ("language", "source", "expected", "note"),
+ _FIXTURES,
+ ids=[f"{lang}-{note}" for lang, _, _, note in _FIXTURES],
+)
+def test_detector_fixture(language: str, source: bytes, expected: dict, note: str):
+ hits = _hits(language, source)
+ by_kind: dict[str, int] = {}
+ for h in hits:
+ by_kind[h.kind] = by_kind.get(h.kind, 0) + 1
+ assert by_kind == expected, f"{note}: expected {expected}, got {by_kind}"
+
+
+def test_hits_carry_line_anchors():
+ hits = _hits("python", b"x = 1\ntry:\n x()\nexcept Exception:\n pass\n")
+ assert hits, "expected hits on the swallowed bare-Exception catch"
+ assert all(h.line == 4 for h in hits)
+
+
+def test_biomarker_emits_one_low_finding_per_hit():
+ ctx = FileContext(
+ file_path="a.py",
+ language="python",
+ nloc=20,
+ has_test_file=False,
+ module=None,
+ error_handling_hits=[
+ ErrorHandlingHit("swallowed_catch", 4),
+ ErrorHandlingHit("bare_except", 4),
+ ],
+ )
+ findings = ErrorHandlingDetector().detect(ctx)
+ assert len(findings) == 2
+ assert all(f.biomarker_type == "error_handling" for f in findings)
+ assert all(f.severity == Severity.LOW for f in findings)
+ assert findings[0].line_start == findings[0].line_end == 4
+ assert {f.details["kind"] for f in findings} == {"swallowed_catch", "bare_except"}
+
+
+def test_biomarker_no_hits_no_findings():
+ ctx = FileContext(
+ file_path="a.py",
+ language="python",
+ nloc=20,
+ has_test_file=False,
+ module=None,
+ )
+ assert ErrorHandlingDetector().detect(ctx) == []
diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.py
index 2c53a4fd6..a1720252e 100644
--- a/tests/unit/health/test_scoring_snapshot.py
+++ b/tests/unit/health/test_scoring_snapshot.py
@@ -32,6 +32,9 @@ _EXPECTED_CATEGORY_CAPS = {
"size_and_complexity": 1.5,
"duplication": 1.0,
"test_quality": 0.5,
+ # Error-handling anti-patterns - advisory maintainability signal in its
+ # own bounded category (AUC-neutral on the T0 benchmark by design).
+ "error_handling": 0.5,
}
_EXPECTED_SEVERITY_DEDUCTION = {
@@ -72,6 +75,9 @@ _EXPECTED_BIOMARKER_WEIGHT_MULTIPLIER = {
"primitive_obsession": 0.5,
"dry_violation": 0.5,
"knowledge_loss": 0.4,
+ # Error-handling anti-patterns - maintainability flag excluded from the
+ # calibration roster; floored weight keeps LOW findings at 0.15 each.
+ "error_handling": 0.5,
# Governance biomarkers (informational - surfaced as findings, not fed back
# into the score pass, which has already run upstream).
"contradictory_decision": 1.0,
@@ -105,6 +111,7 @@ _EXPECTED_BIOMARKER_CATEGORY = {
"prior_defect": "organizational",
"large_assertion_block": "test_quality",
"duplicated_assertion_block": "test_quality",
+ "error_handling": "error_handling",
# Phase 4B governance biomarkers.
"ungoverned_hotspot": "organizational",
"stale_governance": "organizational",
@@ -204,6 +211,19 @@ def test_continuous_deduction_override_is_used_and_capped():
assert ded2 == [2.0]
+def test_error_handling_cap_bounds_stream():
+ """error_handling findings deduct 0.15 each (LOW 0.3 x 0.5 weight) in
+ their own advisory category, capped at 0.5/file regardless of count."""
+ two = [_result("error_handling", Severity.LOW) for _ in range(2)]
+ score, deductions = score_file(two)
+ assert score == 9.7 # 10 - 2 * 0.15
+ assert deductions == [0.15, 0.15]
+
+ many = [_result("error_handling", Severity.LOW) for _ in range(10)]
+ score2, _ = score_file(many)
+ assert score2 == 9.5 # 10 * 0.15 = 1.5 raw -> clamped to the 0.5 cap
+
+
def test_organizational_cap_bounds_stream():
"""The organizational cap (-3.5) bounds a high-volume finding stream. With
developer_congestion defect-calibrated down to 0.5 (it was a HEAD-leakage