Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: code health layer — biomarkers, refactoring targets, coverage, trends, AI prompts (#212)
Raghav Chamadiya7f6fc0aafc67
diff --git a/Makefile b/Makefileindex e6a3304fb..a2c5e924c 100644--- a/Makefile+++ b/Makefile@@ -53,6 +53,18 @@ check: lint format-check typecheck ## Run all checks (no modifications)fix: format lint ## Format + lint with auto-fix+# ---------------------------------------------------------------------------+# Code Health (Phase 4)+# ---------------------------------------------------------------------------++health-check: ## Run the code-health analyzer against this repo and fail on regressions+ uv run pytest tests/unit/health/ tests/unit/server/test_mcp.py -v+ uv run repowise health --format json > /tmp/repowise-health-report.json || true+ @echo "Health report → /tmp/repowise-health-report.json"++health-bench: ## Run the 3,000-file health analyzer perf benchmark+ uv run pytest tests/integration/test_health_perf_benchmark.py -v -m slow+# ---------------------------------------------------------------------------# Web UI# ---------------------------------------------------------------------------diff --git a/README.md b/README.mdindex 81300b97c..de53f8bf3 100644--- a/README.md+++ b/README.md@@ -3,7 +3,7 @@<img src=".github/assets/logo.png" width="280" alt="repowise" /><br />**The codebase intelligence layer for your AI coding agent.**-Four intelligence layers. Eight MCP tools. Multi-repo workspaces. Auto-sync hooks. One `pip install`.+Five intelligence layers. Nine MCP tools. Multi-repo workspaces. Auto-sync hooks. One `pip install`.[](https://pypi.org/project/repowise/)[](https://www.gnu.org/licenses/agpl-3.0)@@ -84,6 +84,21 @@ The layer nobody else has. Architectural decisions captured from git history, inThese become structured decision records, queryable by Claude Code via `get_why()`.+### ◈ Code Health Intelligence+Twelve deterministic biomarkers compute a 1–10 health score per file — McCabe complexity, deep nesting, brain methods, native Rabin–Karp duplication detection, untested hotspots, primitive obsession, developer congestion, knowledge loss, and more. **Zero LLM calls, zero new runtime dependencies** — pure Python over tree-sitter and git data, designed to finish in under 30 seconds on a 3 000-file repo.++Ingest LCOV, Cobertura, or Clover coverage reports to light up the test-coverage biomarkers. Rolling 50-row snapshot history powers `Declining Health` and `Predicted Decline` alerts. Deterministic, rule-based refactoring suggestions surface on the dashboard and via `get_health(include=["refactoring"])`. Per-file overrides via `.repowise/health-rules.json`.++```bash+repowise health # KPIs + lowest-scoring files+repowise health --coverage cov.lcov # ingest coverage, light up untested-hotspot+repowise health --refactoring-targets # ranked by impact / effort+repowise health --trend # last 10 snapshots + alerts+repowise status # one-line summary in the status report+```++See [`docs/CODE_HEALTH.md`](docs/CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](docs/architecture/code-health.md) for the internals.+---## Quickstart@@ -175,7 +190,7 @@ Full guide: [docs/WORKSPACES.md](docs/WORKSPACES.md)----## Eight MCP tools+## Nine MCP toolsMost tools are designed around data entities — one module, one file, one symbol — which forces AI agents into long chains of sequential calls. repowise tools are designed around **tasks**. Pass multiple targets in one call. Get complete context back. Every response carries an `_meta` envelope with `index_age_days`, `indexed_commit`, and a `stale_warning` that fires only when the indexed HEAD diverges from live `.git/HEAD` — silence means the index is current. Full reference: [docs/MCP_TOOLS.md](docs/MCP_TOOLS.md)@@ -189,6 +204,7 @@ Most tools are designed around data entities — one module, one file, one symbo| `get_risk(targets, changed_files?)` | Hotspot scores, dependents, co-change partners, ownership, test gaps, security signals. Pass `changed_files` for PR mode → response carries a `directive` block (`will_break`, `missing_cochanges`, `missing_tests`) for one-glance review plus cross-repo blast radius. | Before modifying files — understand what could break || `get_why(query?, targets?)` | Architectural decision records, their status (active / proposed / deprecated / superseded), and the commits that are evidence for them. Falls back to git archaeology when no ADRs exist for a file. | Before architectural changes — understand existing intent || `get_dead_code(min_confidence?, include_internals?)` | Unreachable code sorted by confidence tier with cleanup impact estimates. In workspace mode, cross-repo consumer detection lowers confidence on findings that other repos import. | Cleanup tasks |+| `get_health(targets?, include?)` | Twelve deterministic biomarker scores per file. Dashboard mode returns KPIs + the lowest-scoring files + a per-module NLOC-weighted rollup; targeted mode returns per-file findings. `include` flags layer richer data: `"coverage"`, `"refactoring"` (rule-based suggestions), `"trend"` (snapshot diff + declining/predicted-decline alerts). `module:foo` targets expand to a module's file set. | Before refactoring — find the worst-scoring files and what to fix first |### Tool call comparison — a real task@@ -197,7 +213,7 @@ Most tools are designed around data entities — one module, one file, one symbo| Approach | Tool calls | Time to first change | What it misses ||---|---|---|---|| Claude Code alone (no MCP) | grep + read ~30 files | ~8 min | Ownership, prior decisions, hidden coupling |-| **repowise (8 tools)** | **5 calls** | **~2 min** | **Nothing** |+| **repowise (9 tools)** | **5 calls** | **~2 min** | **Nothing** |The 5 calls for that task:@@ -457,11 +473,20 @@ The "why" usually walks out the door — when a teammate leaves, or when you reo| Auto-generated documentation | ✅ | ✅ Gemini | ✅ | ✅ PR2Doc | ❌ || Private repo — no cloud | ✅ | ❌ in development | ❌ OSS forks only | ✅ Enterprise tier | ✅ || Dead code detection | ✅ | ❌ | ❌ | ❌ | ❌ |+| Code health score (1–10) | ✅ 12 biomarkers | ❌ | ❌ | ❌ | ✅ 25–30 |+| Brain Method detection | ✅ | ❌ | ❌ | ❌ | ✅ |+| Complexity biomarkers | ✅ native tree-sitter | ❌ | ❌ | ❌ | ✅ |+| Test coverage intelligence | ✅ LCOV/Cobertura/Clover | ❌ | ❌ | ❌ | ❌ |+| Untested hotspot detection | ✅ coverage × hotspot | ❌ | ❌ | ❌ | ❌ |+| DRY violation detection | ✅ native (no npm) | ❌ | ❌ | ❌ | ✅ |+| Health trend tracking | ✅ rolling 50 snapshots | ❌ | ❌ | ❌ | ✅ |+| Declining health alerts | ✅ | ❌ | ❌ | ❌ | ✅ |+| Refactoring recommendations | ✅ deterministic | ❌ | ❌ | ❌ | ✅ || Git intelligence (hotspots, ownership, co-changes) | ✅ | ❌ | ❌ | ❌ | ✅ || Bus factor analysis | ✅ | ❌ | ❌ | ❌ | ✅ || Architectural decision records | ✅ | ❌ | ❌ | ❌ | ❌ || Multi-repo workspace intelligence | ✅ co-changes, contracts, federated MCP | ❌ | ❌ | ❌ | ❌ |-| MCP server for AI agents | ✅ 8 tools | ❌ | ✅ 3 tools | ✅ | ✅ |+| MCP server for AI agents | ✅ 9 tools | ❌ | ✅ 3 tools | ✅ | ✅ || Proactive agent hooks | ✅ PreToolUse + PostToolUse | ❌ | ❌ | ❌ | ❌ || Auto-generated CLAUDE.md | ✅ | ❌ | ❌ | ❌ | ❌ || Doc freshness scoring | ✅ | ❌ | ❌ | ⚠️ staleness only | ❌ |diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.mdindex 1c50dcac9..e3e083b16 100644--- a/docs/CLI_REFERENCE.md+++ b/docs/CLI_REFERENCE.md@@ -257,6 +257,41 @@ repowise dead-code resolve <id> # mark resolved / false positive---+### `repowise health [PATH]`++Compute per-file code-health scores from twelve deterministic biomarkers (CCN, nesting, brain methods, duplication, untested hotspots, organizational risk). Zero LLM calls — pure Python over tree-sitter + git data. See [`docs/CODE_HEALTH.md`](./CODE_HEALTH.md) for the user guide and [`docs/architecture/code-health.md`](./architecture/code-health.md) for the internals.++**Options:**++| Flag | Description |+|------|-------------|+| `--file <path>` | Deep-dive a single file (relative path) |+| `--module <prefix>` | Restrict the report to files whose path starts with this prefix |+| `--refactoring-targets` | Print top refactoring candidates ranked by impact / effort |+| `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) |+| `--coverage <path>` | Ingest a coverage report (LCOV / Cobertura / Clover). Repeat for multiple files |+| `--coverage-format` | Override coverage-format auto-detection: `lcov`, `cobertura`, `clover` |+| `--format` | Output: `table` (default), `json`, `md` |+| `--safe-only` | Confidence ≥ 0.8 only (placeholder for v1 biomarkers) |+| `--repo` | In workspace mode, target a specific repo (defaults to primary) |+| `--no-workspace` | Force single-repo mode |++```bash+repowise health # KPIs + lowest-scoring files+repowise health --file packages/server/.../app.py # one file in detail+repowise health --module packages/server # restrict to a directory+repowise health --refactoring-targets # ranked by impact / effort+repowise health --trend # snapshot history + alerts+repowise health --coverage coverage.lcov # ingest coverage+repowise health --format json | jq .kpis # machine-readable+```++`repowise init` and `repowise update` populate the health tables automatically —+no separate command needed. `repowise status` shows a one-line summary+(`Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: <path>)`).++---+### `repowise decision`Manage architectural decision records.diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.mdnew file mode 100644index 000000000..c30fcbc55--- /dev/null+++ b/docs/CODE_HEALTH.md@@ -0,0 +1,189 @@+# Code Health++Repowise computes a 1–10 health score for every file in your repo from twelve+deterministic biomarkers — McCabe complexity, deep nesting, brain methods,+clone detection, untested hotspots, organizational risk, and more. **No LLM+calls, no cloud requirement.** Pure Python over tree-sitter + git data,+designed to finish in under 30 seconds on a 3 000-file repo.++## Quick start++```bash+repowise init # full index — populates health tables+repowise health # KPIs + 20 worst-scoring files + top findings+repowise update # re-score only changed files on each subsequent run+```++Open `http://localhost:7777/repos/<id>/health` for the dashboard once the+local server is running (`repowise serve`).++## The score++Each file starts at 10.0. Biomarker findings deduct from the score; deductions+are capped per category so any one category can drive the score down by at+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 |+| Test coverage | −2.0 | untested_hotspot, coverage_gap |+| Organizational | −1.0 | developer_congestion, knowledge_loss |++The final score is clamped to `[1.0, 10.0]`. The three repo-level KPIs:++- **Hotspot Health** — NLOC-weighted average over the top-25 % hotspot files.+- **Average Health** — NLOC-weighted average over all files.+- **Worst Performer** — single lowest-scoring file.++## The 12 biomarkers++**brain_method** — A single function that is simultaneously long, deeply+nested, highly complex, and central to the dependency graph. The strongest+single signal of fragile code.++**nested_complexity** — Functions with control-flow nesting ≥ 4 levels.+Hard to read, hard to test, hard to refactor.++**bumpy_road** — Multiple branches stacked at the same depth — usually a+sign the function is doing several jobs that should be split.++**complex_method** — Cyclomatic complexity ≥ 9. Each branch is a path the+test suite has to cover.++**large_method** — Functions that exceed the NLOC threshold. Length on its+own is not always a bug, so this is a milder signal.++**primitive_obsession** — Many primitive parameters in one signature. A+dataclass or parameter object would name the inputs.++**dry_violation** — Cross-file code clones, detected by a native Rabin–Karp+rolling hash over tree-sitter tokens (variable renames don't hide a clone).+Pairs are ranked by co-change so dormant duplicates rank lower than active+ones.++**untested_hotspot** — A hotspot file with low or zero coverage and many+dependents. The textbook "write tests before refactoring" case.++**coverage_gap** — Non-test files with meaningful uncovered surface.+Severity grades along coverage depth.++**developer_congestion** — Too many active authors touching the same file.+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.++## Test coverage++Pass coverage reports straight into the analyzer:++```bash+pytest --cov --cov-report=lcov:coverage.lcov+repowise health --coverage coverage.lcov++# Cobertura, Clover, or multiple sources also work:+repowise health \+ --coverage backend/coverage.xml --coverage-format cobertura \+ --coverage frontend/lcov.info+```++Coverage data feeds into `untested_hotspot` and `coverage_gap`, and shows up+on the `/repos/<id>/health/coverage` dashboard.++## Refactoring targets++```bash+repowise health --refactoring-targets+```++Ranks candidates by `total_impact / effort_bucket` so the biggest wins for+the least work surface first. Each row carries a deterministic, rule-based+suggestion (`"Split this function. It carries high cyclomatic complexity..."`).++For agentic workflows, the same data is one MCP call away:++```python+get_health(include=["refactoring"]) # dashboard + suggestions+get_health(targets=["src/api/server.py"]) # one file in detail+get_health(targets=["module:src.api"]) # everything in a module+```++## Trends++Every health run writes a `HealthSnapshot` row (rolling 50 entries per repo).+Two alerts run over the history:++- **Declining Health** — current `hotspot_health` is ≥ 0.5 below the+ snapshot 5 runs ago.+- **Predicted Decline** — the three most recent snapshots are each+ strictly below the one before.++Inspect from the CLI:++```bash+repowise health --trend+```++Or from MCP:++```python+get_health(include=["trend"])+```++## Configuration++Per-file overrides live in `.repowise/health-rules.json`:++```json+{+ "disabled_biomarkers": ["primitive_obsession"],+ "rules": [+ {+ "glob": "tests/**/*.py",+ "disabled_biomarkers": ["large_method", "complex_method"]+ },+ {+ "glob": "src/legacy/**",+ "disabled_biomarkers": ["dry_violation"]+ }+ ]+}+```++## Incremental updates++`repowise update` only re-scores the changed files. Findings and metrics for+unchanged files stay put — no nightly full re-index needed.++## Status one-liner++`repowise status` includes a single-line health summary:++```+Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)+```++## Comparison++| Feature | Repowise | CodeScene | DeepSource | Sourcery |+|----------------------------------|:--:|:--:|:--:|:--:|+| Code health score (1–10) | ✅ 12 biomarkers | ✅ 25–30 | ❌ | ❌ |+| Brain Method detection | ✅ | ✅ | ❌ | ❌ |+| Test coverage intelligence | ✅ LCOV/Cobertura/Clover | ❌ | ❌ | ❌ |+| Untested hotspot detection | ✅ coverage × hotspot | ❌ | ❌ | ❌ |+| DRY violation detection | ✅ native (no npm) | ✅ | ❌ | ❌ |+| Health trend tracking | ✅ | ✅ | ❌ | ❌ |+| Declining health alerts | ✅ | ✅ | ❌ | ❌ |+| Refactoring recommendations | ✅ deterministic | ✅ | ❌ | ❌ |+| Free for internal use | ✅ AGPL-3.0 | ❌ $15–30/author | ✅ public repos | ❌ |++## See also++- [`packages/core/src/repowise/core/analysis/health/README.md`][hr] —+ developer overview of the layer.+- Sub-package READMEs: `complexity/`, `coverage/`, `duplication/`,+ `biomarkers/`.++[hr]: ../packages/core/src/repowise/core/analysis/health/README.mddiff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdnew file mode 100644index 000000000..7ee2c5483--- /dev/null+++ b/docs/architecture/code-health.md@@ -0,0 +1,751 @@+# Code Health — Architecture & Internals++Companion to the user-facing [`docs/CODE_HEALTH.md`](../CODE_HEALTH.md). This+document is for contributors: where every piece lives, how data flows from+parsed source to the dashboard, and the extension points for adding+biomarkers, languages, coverage formats, or alerts.++> **TL;DR.** Health analysis is a deterministic, zero-LLM Python pipeline:+> tree-sitter walks every file once → biomarkers vote → scores aggregate per+> category → results land in four SQLAlchemy tables. The MCP server, CLI,+> and Next.js dashboard all read from those tables — no JSON cache, no+> intermediate files, no LLM in the loop.++---++## 1. Layer overview++Code Health is the **fifth intelligence layer** in Repowise, alongside Graph,+Git, Docs, and Decisions. It reads from Graph and Git but never modifies+them. Its only writes are to its own four tables.++```+┌─────────────┐ parsed_files ┌──────────────────┐+│ Ingestion │ ────────────────► │ │+│ (AST + git) │ git_meta_map │ HealthAnalyzer │ ──► HealthReport+│ │ ────────────────► │ (engine.py) │ │+│ │ community_labels │ │ │+└─────────────┘ └──────────────────┘ │+ │ delete/upsert+ ▼+ ┌─────────────────────────────┐+ │ SQLite via SQLAlchemy │+ │ • health_findings │+ │ • health_file_metrics │+ │ • health_snapshots │+ │ • coverage_files │+ └──────────────┬──────────────┘+ │+ ┌────────────────────────────────┼────────────────────────────────┐+ ▼ ▼ ▼+ CLI (rich) MCP tools (FastMCP) Web dashboard+ health, status, get_health, get_risk, /repos/[id]/health{,+ health --trend get_context, get_overview /coverage,/refactoring-targets}+```++Three architectural rules govern the whole layer:++1. **Zero LLM.** Every biomarker is AST, git, or coverage math.+2. **No JSON caches.** SQLite is the single source of truth; everything+ else reads from it.+3. **No new runtime dependencies.** Pure Python over tree-sitter (already+ in tree). No lizard, no jscpd, no Node.++---++## 2. Where things live++### Python — `packages/core/src/repowise/core/`++```+analysis/health/+├── README.md # developer overview (this layer)+├── __init__.py # public API: HealthAnalyzer, HealthReport+├── engine.py # orchestrator: walker → biomarkers → scorer+├── scoring.py # weighted aggregation, category caps, KPIs+├── trends.py # snapshot diff, Declining/Predicted alerts+├── suggestions.py # deterministic refactoring text per biomarker+├── config.py # HealthConfig + .repowise/health-rules.json+├── models.py # HealthFindingData, HealthFileMetricData, HealthReport+│+├── complexity/ # tree-sitter AST walker+│ ├── README.md+│ ├── walker.py # CCN, nesting, cognitive, bumps, params, NLOC+│ └── languages.py # per-language control-flow node-type maps+│+├── coverage/ # coverage report ingestion+│ ├── README.md+│ ├── model.py # CoverageReport, FileCoverage+│ ├── detector.py # format auto-detect + test-file heuristic+│ ├── lcov.py # LCOV parser (stdlib only)+│ ├── cobertura.py # Cobertura XML parser+│ └── clover.py # Clover XML parser+│+├── duplication/ # native Rabin-Karp clone detection+│ ├── README.md+│ ├── tokenizer.py # tree-sitter token stream (ID/LIT normalized)+│ ├── rabin_karp.py # 64-bit rolling polynomial hash+│ └── detector.py # clone-pair build + co-change weighting+│+└── biomarkers/ # one detector per file+ ├── README.md+ ├── base.py # Biomarker Protocol + FileContext + BiomarkerResult+ ├── registry.py # detector list + detect_all()+ ├── brain_method.py+ ├── nested_complexity.py+ ├── bumpy_road.py+ ├── complex_method.py+ ├── large_method.py+ ├── primitive_obsession.py+ ├── dry_violation.py+ ├── untested_hotspot.py+ ├── coverage_gap.py+ ├── developer_congestion.py+ └── knowledge_loss.py+```++### Persistence++```+core/persistence/+├── models.py # HealthFinding, HealthFileMetric, HealthSnapshot, CoverageFile+└── crud.py # save_/upsert_/get_ health functions+core/alembic/versions/+└── 000X_health_tables.py # migration that created the four tables+```++### Pipeline wiring++```+core/pipeline/+├── orchestrator.py # _run_health_analysis() — builds module_map, runs analyzer+└── persist.py # persist_pipeline_result() — writes findings/metrics/snapshot+```++### CLI++```+cli/src/repowise/cli/commands/+├── health_cmd.py # repowise health [--trend|--coverage|--refactoring-targets|--module]+├── status_cmd.py # `Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: ...)`+└── update_cmd.py # incremental path: HealthAnalyzer.analyze(changed_files=...)+```++### Server — MCP + REST++```+server/src/repowise/server/+├── mcp_server/+│ ├── tool_health.py # @mcp.tool get_health(targets, include, repo, limit)+│ ├── tool_risk.py # enriched: health_score, top_biomarkers, coverage_pct+│ ├── tool_context.py # include=["health"]: score, top 2 biomarkers, suggestion+│ └── tool_overview.py # code_health block with KPIs+└── routers/+ └── code_health.py # /api/repos/{id}/health/{overview,files,coverage,+ # refactoring-targets,modules,findings}+```++### Web dashboard++```+packages/ui/src/health/ # shared React components (used by web + future hosted frontend)+├── kpi-cards.tsx+├── file-table.tsx+├── biomarker-list.tsx+├── coverage-bar.tsx+├── module-coverage-list.tsx+├── untested-hotspot-warning.tsx+├── refactoring-card.tsx+├── refactoring-target-list.tsx+├── health-badge.tsx+└── module-rollup-list.tsx++packages/web/src/app/repos/[id]/health/+├── page.tsx # KPIs + lowest-scoring files + per-module rollup+├── coverage/page.tsx # /health/coverage view+└── refactoring-targets/page.tsx # /health/refactoring-targets view++packages/web/src/components/health/+└── health-risks-panel.tsx # sidecar panel on Hotspots/Ownership/Graph pages+```++### Tests++```+tests/unit/health/ # 99+ tests+├── test_complexity_walker.py # per-language CCN/nesting assertions+├── test_biomarkers.py+├── test_structural_biomarkers.py # bumpy_road, large_method, primitive_obsession+├── test_coverage_biomarkers.py # untested_hotspot, coverage_gap+├── test_organizational_biomarkers.py+├── test_dry_violation.py+├── test_duplication.py # tokenizer, hash, detector+├── test_coverage_parsers.py # LCOV/Cobertura/Clover+├── test_scoring.py # category caps, clamping+├── test_scoring_snapshot.py # stability snapshot — locks caps + deductions+├── test_health_config.py # .repowise/health-rules.json+├── test_trends.py # diff_snapshots, declining/predicted alerts+└── test_suggestions.py++tests/integration/+├── test_health_coverage_integration.py+└── test_health_perf_benchmark.py # 30 s budget on 3,000-file synthetic repo (slow)+```++---++## 3. The pipeline (init path)++`repowise init` runs `run_pipeline()` in `core/pipeline/orchestrator.py`.+Health analysis is a phase in that orchestrator, called between+`_run_dead_code_analysis()` and `_run_decision_extraction()`:++```python+# orchestrator.py — simplified+async def _run_health_analysis(graph_builder, git_meta_map, parsed_files, *, repo_path, progress):+ # 1. Build a {file_path → community label} map from the graph.+ # Used to populate HealthFileMetric.module so module rollups+ # aren't NULL.+ cd = graph_builder.community_detection()+ ci = graph_builder.community_info()+ module_map = {nid: ci[cid].label for nid, cid in cd.items() if ci.get(cid)}++ # 2. Load per-file override rules from .repowise/health-rules.json+ # (empty / no-op when the file doesn't exist).+ cfg = HealthConfig.load(repo_path)+ analyzer_config = cfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])++ # 3. Construct the analyzer with all inputs it needs.+ analyzer = HealthAnalyzer(+ graph_builder.graph(), # NetworkX DiGraph for dependents+ git_meta_map=git_meta_map, # hotspot bit, owners, co-change, bus factor+ parsed_files=parsed_files, # ParsedFile objects from the AST phase+ module_map=module_map, # community labels+ )++ # 4. Pick sync vs parallel based on repo size. Tree-sitter releases the+ # GIL during parsing, so asyncio.gather + asyncio.to_thread gives+ # real wall-clock speedup on large repos.+ if len(parsed_files) >= 500:+ report = await analyzer.analyze_async(analyzer_config)+ else:+ report = await asyncio.to_thread(analyzer.analyze, analyzer_config)++ return report # carried on PipelineResult.health_report+```++Then `core/pipeline/persist.py` writes everything in one session:++```python+# persist.py — simplified+if result.health_report:+ hr = result.health_report+ await save_health_metrics(session, repo_id, hr.metrics)+ if hr.findings:+ await save_health_findings(session, repo_id, hr.findings)+ # Snapshot for trend tracking — rolling 50-row window per repo.+ await save_health_snapshot(+ session,+ repo_id,+ hotspot_health=hr.kpis["hotspot_health"],+ average_health=hr.kpis["average_health"],+ worst_performer_path=hr.kpis["worst_performer_path"],+ worst_performer_score=hr.kpis["worst_performer_score"],+ per_file_scores={m.file_path: round(m.score, 2) for m in hr.metrics},+ )+```++---++## 4. Inside `HealthAnalyzer.analyze()`++Single pass over the parsed file list. For each file:++```python+# engine.py — pseudocode+1. _walk(pf):+ source = read_bytes(pf.file_info.abs_path)+ walk_file_complexity(language, source) → list[FunctionComplexity]+ # Each FunctionComplexity carries: name, line range, nloc, ccn,+ # max_nesting, cognitive, bumps, param_count.++2. _populate_symbol_complexity(pf, fc_list):+ # Side effect: write max(ccn) into Symbol.complexity_estimate so+ # the ContextAssembler symbol ranker benefits even when callers+ # don't query the health tables directly.++3. _evaluate_file(pf, fc_list, ...):+ # Build a FileContext with:+ # - nloc, has_test_file, module+ # - function_metrics: dict[symbol_name → FunctionComplexity]+ # - git_meta: per-file dict (hotspot, owners, bus factor, ...)+ # - dependents_count: in_degree on the graph+ # - line_coverage_pct, branch_coverage_pct, covered_lines (when ingested)+ # - clones, duplication_pct (from cross-file detect_clones())+ results = detect_all(ctx, disabled=file_disabled)+ score, deductions = score_file(results)+ findings = attach_impacts(results, deductions)+ metric = HealthFileMetricData(...)+```++After the loop:++```python+hotspot_paths = {p for p, meta in git_meta_map.items() if meta.get("is_hotspot")}+kpis = compute_kpis(metrics, hotspot_paths)+return HealthReport(findings=..., metrics=..., kpis=kpis)+```++Duplication runs **once up-front** (cross-file by nature). Each `FileContext`+gets a slice of the global clone report. The `dry_violation` biomarker+reads `ctx.clones` to rank pairs by co-change frequency from+`git_meta_map[path]["co_change_partners_json"]` — active clones rank+higher than dormant ones.++---++## 5. The 12 biomarkers and their categories++Each biomarker is a stateless class implementing the `Biomarker` Protocol+from `biomarkers/base.py`:++```python+class Biomarker(Protocol):+ name: str # "brain_method", "nested_complexity", ...+ category: str # see scoring.CATEGORY_CAPS+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...+```++| 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 |+| Test coverage | −2.0 | untested_hotspot, coverage_gap |+| Organizational | −1.0 | developer_congestion, knowledge_loss |++`biomarkers/registry.py` is an **explicit list**, not auto-discovery —+keeps the registration order deterministic and lets tests inject extras+via `registered_biomarkers(extra=...)`.++---++## 6. Scoring (`scoring.py`)++Every file starts at **10.0**. Each finding contributes a per-severity+deduction (`low=0.3, medium=0.7, high=1.2, critical=2.0`). Deductions are+**capped per category** — so even ten critical structural findings can+drive structural complexity down by at most 3.5 points, not 20.++```python+# scoring.py — score_file()+1. Group findings by category.+2. Sum raw deductions per category.+3. If sum ≤ cap, accept; else scale every per-finding deduction+ proportionally so the total equals the cap. This keeps the UI+ "this finding cost you X points" honest after capping.+4. Clamp the final score to [1.0, 10.0].+```++The per-finding scaled deduction lands on `HealthFinding.health_impact`+via `attach_impacts()` — that's what the dashboard's "−2.0" badge shows.++Snapshot tests in `tests/unit/health/test_scoring_snapshot.py` lock the+category caps, severity deductions, biomarker→category mapping, and two+known-fixture scores. A retune intentionally requires updating the+snapshot in the same PR.++---++## 7. KPIs++Three repo-level numbers, computed in `compute_kpis()`:++- **Hotspot Health** — NLOC-weighted average over files where+ `git_meta_map[path]["is_hotspot"]` is true.+- **Average Health** — NLOC-weighted average over all files.+- **Worst Performer** — lowest-scoring file + its score.++These flow into `HealthSnapshot` rows (rolling 50 per repo) and feed the+CLI status one-liner, the `get_overview()` MCP block, and the dashboard+KPI cards.++---++## 8. Trends (`trends.py`)++State-free — callers pass an oldest-first list of snapshot rows. Two+alerts:++- **Declining Health** — current is ≥ `DECLINE_THRESHOLD` (default 0.5)+ below the snapshot `DECLINE_LOOKBACK` (5) positions back. Fires on the+ 6th+ snapshot.+- **Predicted Decline** — the three most recent snapshots are each+ strictly below the one before. Magnitude is not required; direction is+ the signal.++`recent_kpis(history, limit=10)` returns a newest-first serialised view+for the CLI table and MCP `get_health(include=["trend"])` response.++---++## 9. Incremental analysis — the `repowise update` path++Full re-analysis would be wasteful on commit-sized diffs. `HealthAnalyzer`+accepts `changed_files`:++```python+# engine.py+def analyze(self, config=None, *, changed_files=None):+ # 1. Duplication still runs full-repo (a changed file's clone+ # partner may be unchanged).+ # 2. The per-file loop skips files not in changed_files.+ # 3. KPIs are NOT recomputed on incremental runs — they'd be biased+ # by the subset. The dashboard recomputes from the merged DB rows.+```++`update_cmd.py` builds the changed-files set from+`change_detector.get_changed_files()`, runs the analyzer, and calls a+helper that uses the **upsert** variants (`upsert_health_findings`,+`upsert_health_metrics`) so unchanged files keep their existing rows:++```python+async def _persist_partial_health(session, repo_id, report):+ changed_paths = sorted({m.file_path for m in report.metrics})+ await upsert_health_metrics(session, repo_id, report.metrics)+ await upsert_health_findings(session, repo_id, report.findings, file_paths=changed_paths)+```++The full-init writers (`save_health_findings`, `save_health_metrics`)+still use delete-then-insert — simpler, and the cost is amortised across+the whole `repowise init`.++---++## 10. Persistence schema++Four tables, all in the repo's `.repowise/wiki.db`. Foreign-keyed to+`repositories.id` with `ON DELETE CASCADE`.++### `health_findings`++One row per biomarker hit. Lifecycle: `open → acknowledged | resolved |+false_positive` (matches Dead Code). Bulk-deleted-and-rewritten on full+init; selectively upserted on `repowise update`.++| Column | Notes |+|---|---|+| `id` | UUID PK |+| `repository_id` | FK |+| `file_path` | indexed |+| `biomarker_type` | `brain_method`, `nested_complexity`, ... |+| `severity` | `low` / `medium` / `high` / `critical` |+| `function_name` | nullable for file-level findings |+| `line_start`, `line_end` | nullable |+| `details_json` | per-biomarker evidence (CCN values, clone span, etc.) |+| `health_impact` | per-finding scaled deduction |+| `reason` | one-line summary string |+| `status` | lifecycle |+| `created_at`, `updated_at` | datetime |++### `health_file_metrics`++One row per file (unique on `(repository_id, file_path)`). Read directly+by the dashboard's file table.++| Column | Notes |+|---|---|+| `score` | 1.0–10.0 final |+| `max_ccn`, `max_nesting`, `nloc` | aggregate function metrics |+| `duplication_pct` | percent of NLOC covered by clones; nullable |+| `has_test_file` | paired or heuristic |+| `line_coverage_pct`, `branch_coverage_pct` | nullable |+| `module` | community label from graph; falls back to top-level dir |+| `updated_at` | datetime |++### `health_snapshots`++KPI + per-file score history. Rolling delete on insert keeps the latest+50 per repo (`HEALTH_SNAPSHOT_RETENTION` in `crud.py`).++### `coverage_files`++Per-file coverage, overwritten on every `--coverage` run. Carries the+explicit `covered_lines_json` array so the `coverage_gap` biomarker can+flag the exact uncovered surface, not just the percent.++---++## 11. CLI surface++`packages/cli/src/repowise/cli/commands/health_cmd.py`. Mirrors the+dead-code command's Click structure.++```bash+repowise health # KPIs + lowest-scoring files + findings+repowise health --file path/to/x.py # deep-dive one file+repowise health --module packages/server # restrict to a directory prefix+repowise health --refactoring-targets # ranked by impact / effort+repowise health --trend # last 10 snapshots + active alerts+repowise health --coverage coverage.lcov # ingest coverage; can repeat+repowise health --coverage-format cobertura+repowise health --format json | jq ...+repowise health --safe-only # confidence ≥ 0.8 only (placeholder)+```++`repowise status` queries the same tables for a one-line summary:++```+Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: packages/server/.../app.py)+```++`repowise update` is unchanged from the user's perspective — health is+silently re-scored for changed files only.++---++## 12. MCP surface++### `get_health(targets?, include?, repo?, limit?)`++Defined in `tool_health.py`. Modes:++- **Dashboard mode** (`targets=None`) — returns repo-level KPIs ++ `worst_files` (top N lowest-scoring) + `top_findings` + a per-module+ `modules` rollup.+- **Targeted mode** (`targets=[...]`) — returns full `metrics` ++ `findings` for the listed paths. Targets prefixed `module:foo` expand+ to the file set in that module.++`include` flags layer richer data:++| Flag | Adds |+|---|---|+| `"biomarkers"` | full findings list (already present in target mode) |+| `"coverage"` | per-file coverage rows + summary |+| `"refactoring"` | deterministic `suggestion` text on every finding |+| `"trend"` | snapshot diff + alerts + last 10 KPI rows |++### Enrichments on existing tools++- `get_risk(targets)` — each per-target row carries `health_score`,+ `top_biomarkers`, `coverage_pct`, `branch_coverage_pct`.+- `get_context(targets, include=["health"])` — per-file `score`,+ `max_ccn`, `max_nesting`, `nloc`, `module`, `duplication_pct`, top+ 2 biomarkers (each with a `suggestion` string), and coverage block.+- `get_overview()` — adds a `code_health` block: avg, hotspot, worst+ performer, open finding count.++Every response carries the standard `_meta` envelope via `build_meta()`.++---++## 13. REST surface++`packages/server/src/repowise/server/routers/code_health.py`. All under+`/api/repos/{repo_id}/health/`:++| Route | Returns |+|---|---|+| `GET /overview` | summary + lowest-scoring files + top findings + module rollup |+| `GET /files` | per-file metrics |+| `GET /findings` | findings list (filterable by biomarker_type, severity, file_path) |+| `GET /coverage` | coverage summary + per-file rows |+| `POST /coverage` | ingest a coverage report (used by some CI integrations) |+| `GET /refactoring-targets` | ranked by `total_impact / effort_bucket` |+| `GET /modules` | NLOC-weighted module rollup table |++Auth is the standard `verify_api_key` dependency from+`server/deps.py`.++---++## 14. Web dashboard++Three routes under `/repos/[id]/health/`:++| Route | What it shows |+|---|---|+| `/health` | KPI cards, lowest-scoring file table, top findings, **per-module rollup** (added in Phase 4) |+| `/health/coverage` | Coverage summary, untested-hotspot warnings, module-level bars, per-file drill-down |+| `/health/refactoring-targets` | Cards sorted by impact-per-effort, each with severity, biomarker, score, NLOC, effort bucket, **deterministic suggestion** |++Plus a sidecar `HealthRisksPanel` on the Hotspots, Ownership, and Graph+pages — surfaces the lowest-scoring files inline without touching the+shared table/graph components.++All visual primitives live in `packages/ui/src/health/` so the hosted+`frontend/` repo (separate git checkout) can reuse them — port is mostly+data fetching + auth.++---++## 15. CLAUDE.md integration++The auto-generated `CLAUDE.md` includes a `## Code health` section when+the health tables are populated. The block is intentionally short —+filter rules in `core/generation/editor_files/data.py`:++- Score ≤ 5.0 **and** file is a hotspot+- Any Brain Method in a file with > 10 dependents+- Any Untested Hotspot+- DRY violations > 70 % similarity+- Declining trend (> 1.0 drop in last 5 snapshots)++Everything else is filtered out so the CLAUDE.md doesn't drown a fresh+agent in noise. The Jinja stanza lives in+`core/generation/templates/claude_md.j2`.++---++## 16. Configuration — `.repowise/health-rules.json`++User-authored (the **only** JSON file in the layer). Loaded by+`HealthConfig.load(repo_path)`:++```json+{+ "disabled_biomarkers": ["primitive_obsession"],+ "rules": [+ {+ "glob": "tests/**/*.py",+ "disabled_biomarkers": ["large_method", "complex_method"]+ },+ {+ "glob": "src/legacy/**",+ "disabled_biomarkers": ["dry_violation"]+ }+ ]+}+```++`to_analyzer_config(file_paths)` resolves globs to per-file disabled+sets, which the engine honors in `_evaluate_file()`.++---++## 17. Performance++Plan §4 P4.6 targets **< 30 s on a 3,000-file synthetic repo**. The+parallel path in `HealthAnalyzer.analyze_async()` parallelises tree-sitter+parsing across worker threads (`asyncio.gather` + `asyncio.to_thread`).+tree-sitter releases the GIL on parse, so this scales on single-process+CPython.++The orchestrator chooses the parallel path automatically when+`len(parsed_files) >= 500`. The benchmark lives at+`tests/integration/test_health_perf_benchmark.py` and is marked `slow`+(opt-in via `pytest -m slow` or `make health-bench`).++Other perf notes:++- **Duplication is O(total_tokens).** Bucket walk is near-linear on+ repos with low duplication.+- **Walker re-parses files** because `ParsedFile` doesn't retain a+ tree-sitter `Tree` across the ingestion boundary. Acceptable (~1 ms+ per file); switching to a shared parse cache is a Phase 5 stretch.+- **No N² loops in scoring.** Category aggregation is O(findings).++---++## 18. Testing++| Suite | What it locks |+|---|---|+| `tests/unit/health/test_complexity_walker.py` | Per-language CCN, nesting, cognitive assertions on handcrafted fixtures |+| `tests/unit/health/test_<biomarker>.py` | Each biomarker — positive in two languages + one negative |+| `tests/unit/health/test_duplication.py` | Tokenizer normalization, rolling-hash determinism, co-change weighting |+| `tests/unit/health/test_coverage_parsers.py` | LCOV / Cobertura / Clover happy paths + edge cases |+| `tests/unit/health/test_scoring.py` | Deduction caps, clamping, KPI math |+| `tests/unit/health/test_scoring_snapshot.py` | **Stability guard** — caps, severity table, biomarker→category mapping, two known fixture scores |+| `tests/unit/health/test_trends.py` | Declining + predicted alerts, ordering |+| `tests/unit/health/test_suggestions.py` | Suggestion strings keyed correctly |+| `tests/unit/health/test_health_config.py` | `.repowise/health-rules.json` parsing + glob matching |+| `tests/integration/test_health_coverage_integration.py` | End-to-end LCOV → analyzer → coverage_gap fires |+| `tests/integration/test_health_perf_benchmark.py` | 30 s budget on 3,000 synthetic files (`-m slow`) |++99 unit tests + 2 integration tests at time of writing. Run with+`make health-check`.++---++## 19. Extension points++### Add a biomarker++1. New file under `biomarkers/` implementing the `Biomarker` Protocol.+2. Append to `_DETECTOR_FACTORIES` in `biomarkers/registry.py`.+3. Add the biomarker→category mapping in+ `scoring._BIOMARKER_CATEGORY`.+4. Add a suggestion template in `suggestions._TEMPLATES`.+5. Add at least three test cases (two positive in different languages,+ one negative).+6. Update `biomarkers/README.md`'s "Registered v1 detectors" list.++### Add a language to the complexity walker++Add one `LanguageNodeMap` entry to `complexity/languages.py` mapping the+language's tree-sitter control-flow node-type names to abstract `BRANCH`+/ `LOOP` / `TRY` / `BOOLEAN_OP` categories. Add a fixture under+`tests/fixtures/lang_samples/<lang>/`. **No `.scm` files needed** — those+are owned by the ingestion parser.++### Add a coverage format++Drop a parser under `coverage/` returning a `CoverageReport`. Route to it+from `coverage/detector.parse`. Stdlib-only (no extra XML libraries).++### Add a per-file override++Users — not contributors — author `.repowise/health-rules.json`. To add+a new override key (beyond `disabled_biomarkers`), extend+`HealthConfig` and thread it through `to_analyzer_config()` →+`engine._evaluate_file()`.++---++## 20. Where the layer deliberately stops++A short list of things the v1 layer **does not** do, by design. Future+phases may revisit; the constraints kept v1 shippable.++- **No LLM-generated suggestions.** `suggestions.py` is static+ templates. An optional LLM mode is Phase 5, gated behind an explicit+ flag.+- **No symbol-level scoring.** Score lives at the file granularity to+ match how engineers think about refactor units. Symbol-level CCN+ still feeds the file score via `function_metrics`.+- **No `complexity_estimate` propagation backfill.** The walker writes+ the field as a side effect during the current run; old indexes don't+ get touched until a re-index.+- **No PR-mode delta in v1.** `get_risk(changed_files=...)` returns the+ current health score, not before/after. Phase 5.+- **No predictive ML.** `Predicted Decline` is a 3-snapshot direction+ check, not a model. Phase 5.++---++## 21. Quick lookup — where do I edit X?++| I want to... | Edit... |+|---|---|+| Tweak a category cap | `scoring.CATEGORY_CAPS` (snapshot test will fail — update it) |+| Tweak a severity deduction | `scoring._SEVERITY_DEDUCTION` (ditto) |+| Add a new biomarker | `biomarkers/*.py`, `registry.py`, `scoring.py`, `suggestions.py` |+| Change the suggestion text for a biomarker | `suggestions._TEMPLATES` |+| Adjust the trend-alert threshold | `trends.DECLINE_THRESHOLD` / `DECLINE_LOOKBACK` |+| Change snapshot retention | `crud.HEALTH_SNAPSHOT_RETENTION` |+| Add a new MCP `include` flag | `tool_health.py` — append handling near the existing `"coverage"` / `"refactoring"` branches |+| Add a new REST route | `routers/code_health.py` — auth is wired at the router level |+| Add a new dashboard view | new file under `packages/web/src/app/repos/[id]/health/`, primitives under `packages/ui/src/health/` |+| Add a CLI flag | `packages/cli/src/repowise/cli/commands/health_cmd.py` |+| Wire the analyzer into a new entry point | call `HealthAnalyzer.analyze()` directly; persist via the upsert variants if your caller is incremental |++---++## See also++- [`docs/CODE_HEALTH.md`](../CODE_HEALTH.md) — user-facing guide.+- [`packages/core/src/repowise/core/analysis/health/README.md`](../../packages/core/src/repowise/core/analysis/health/README.md) — developer overview at the layer root.+- Sub-package READMEs under `complexity/`, `coverage/`, `duplication/`, `biomarkers/`.+- [`docs/architecture/graph-algorithms.md`](./graph-algorithms.md) — the graph layer health depends on.diff --git a/packages/cli/src/repowise/cli/commands/health_cmd.py b/packages/cli/src/repowise/cli/commands/health_cmd.pynew file mode 100644index 000000000..557867fa2--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/health_cmd.py@@ -0,0 +1,589 @@+"""``repowise health`` — code-health biomarker report.++Mirrors the dead-code CLI: ingest → analyze → render. Reads from+``HealthFileMetric`` / ``HealthFinding`` if a fresh index exists, falls+back to a live in-process analysis when run outside an indexed repo.+"""++from __future__ import annotations++import json++import click+from rich.table import Table++from repowise.cli.helpers import (+ console,+ err_console,+ resolve_command_target,+ run_async,+)++[email protected]("health")[email protected]("path", required=False, type=click.Path(exists=True))+ "--file",+ "file_filter",+ default=None,+ help="Deep-dive a single file (relative path).",+)+ "--format",+ "fmt",+ default="table",+ type=click.Choice(["table", "json", "md"]),+ help="Output format.",+)+ "--safe-only",+ is_flag=True,+ default=False,+ help="Phase-3 placeholder — currently a no-op for v1 biomarkers.",+)+ "--repo",+ "repo_alias",+ default=None,+ help="Workspace repo alias to analyze.",+)+ "--no-workspace",+ is_flag=True,+ default=False,+ help="Force single-repo mode.",+)+ "--coverage",+ "coverage_paths",+ multiple=True,+ type=click.Path(exists=True),+ help="Ingest a coverage report (LCOV/Cobertura/Clover). May be repeated.",+)+ "--coverage-format",+ "coverage_format",+ default=None,+ type=click.Choice(["lcov", "cobertura", "clover"]),+ help="Override coverage-format auto-detection.",+)+ "--refactoring-targets",+ "refactoring_targets",+ is_flag=True,+ default=False,+ help="Print top refactoring candidates (impact/effort ratio).",+)+ "--module",+ "module_filter",+ default=None,+ help="Restrict the report to files whose path starts with this prefix.",+)+ "--trend",+ "trend_view",+ is_flag=True,+ default=False,+ help="Print the last 10 health snapshots from the SQLite history.",+)+def health_command(+ path: str | None,+ file_filter: str | None,+ fmt: str,+ safe_only: bool,+ repo_alias: str | None,+ no_workspace: bool,+ coverage_paths: tuple[str, ...],+ coverage_format: str | None,+ refactoring_targets: bool,+ module_filter: str | None,+ trend_view: bool,+) -> None:+ """Compute code-health scores from biomarkers (CCN, nesting, brain-method).++ Runs in-process — no LLM, no network. Re-uses the repowise ingestion+ parser, graph builder, and git indexer.+ """+ from pathlib import Path as PathlibPath++ from repowise.core.analysis.health import HealthAnalyzer+ from repowise.core.analysis.health.coverage import parse as parse_coverage+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++ # Status output goes to stderr when the user asked for a machine-readable+ # format — otherwise rich's banner pollutes stdout and breaks+ # `repowise health --format json | jq …` (and the CI smoke test).+ status = err_console if fmt != "table" else console++ target = resolve_command_target(+ path=path, no_workspace_flag=no_workspace, repo_alias=repo_alias+ )+ target.notice(status, command="health")++ if target.is_workspace:+ if target.repo_filter is not None:+ picked = target.resolve_repo_alias(target.repo_filter)+ if picked is None:+ raise click.ClickException(f"Unknown repo alias: {target.repo_filter}")+ repo_path = picked+ else:+ primary = target.primary_path()+ if primary is None:+ raise click.ClickException("Workspace has no primary repo configured.")+ repo_path = primary+ else:+ assert target.repo_path is not None+ repo_path = target.repo_path++ status.print(f"[bold]repowise health[/bold] — {repo_path}")++ if trend_view:+ _render_trend(repo_path, fmt=fmt)+ return++ traverser = FileTraverser(repo_path)+ file_infos = list(traverser.traverse())+ parser = ASTParser()+ graph_builder = GraphBuilder(repo_path)++ parsed_files = []+ for fi in file_infos:+ try:+ source = PathlibPath(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ graph_builder.add_file(parsed)+ parsed_files.append(parsed)+ except Exception:+ continue+ graph_builder.build()++ git_meta_map: dict = {}+ try:+ from repowise.core.ingestion.git_indexer import GitIndexer++ git_indexer = GitIndexer(repo_path)+ _, metadata_list = run_async(git_indexer.index_repo(""))+ git_meta_map = {m["file_path"]: m for m in metadata_list}+ except Exception:+ pass++ coverage_map: dict[str, dict] = {}+ coverage_persist_files: list = []+ coverage_persist_format: str | None = None+ if coverage_paths:+ for cov_path in coverage_paths:+ try:+ text = PathlibPath(cov_path).read_text(encoding="utf-8")+ except OSError as exc:+ status.print(f"[red]Could not read coverage file {cov_path}: {exc}[/red]")+ continue+ report_cov = parse_coverage(text, format=coverage_format)+ if not report_cov.files:+ status.print(+ f"[yellow]No coverage entries parsed from {cov_path} "+ f"(detected={report_cov.source_format}).[/yellow]"+ )+ continue+ for fc in report_cov.files:+ coverage_map[fc.file_path] = {+ "line_coverage_pct": fc.line_coverage_pct,+ "branch_coverage_pct": fc.branch_coverage_pct,+ "covered_lines": list(fc.covered_lines),+ "total_coverable_lines": fc.total_coverable_lines,+ "source_format": report_cov.source_format,+ }+ # Accumulate for DB persistence. Last format wins when multiple+ # reports are passed — they should all be the same format in+ # practice, but the CLI doesn't enforce it.+ coverage_persist_files.extend(report_cov.files)+ coverage_persist_format = report_cov.source_format+ status.print(+ f"[green]Ingested {len(report_cov.files)} files "+ f"from {cov_path} ({report_cov.source_format}).[/green]"+ )++ analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ coverage_map=coverage_map,+ )+ # Load any .repowise/health-rules.json the user keeps in the repo.+ from repowise.core.analysis.health.config import HealthConfig++ health_cfg = HealthConfig.load(repo_path)+ analyzer_cfg = (+ health_cfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])+ if (health_cfg.disabled_biomarkers or health_cfg.rules)+ else None+ )+ report = analyzer.analyze(analyzer_cfg)++ # Persist health + coverage to the repo's wiki.db so the dashboard,+ # MCP tools, and `repowise status` see the same numbers as this CLI+ # run. Without this step, `--coverage` was effectively a stdout-only+ # toy — biomarkers got recomputed in memory but nothing reached the+ # tables that drive the Coverage page / get_health.+ #+ # Skip when fmt != "table" (json/md are read by scripts and CI; side+ # effects are unwelcome) or when the run is filtered to a single+ # file/module (those are inspection runs that shouldn't overwrite+ # repo-level state).+ if fmt == "table" and not file_filter and not module_filter:+ _persist_health(+ repo_path,+ report=report,+ coverage_files=coverage_persist_files,+ coverage_format=coverage_persist_format,+ )++ metrics = report.metrics+ if file_filter:+ metrics = [m for m in metrics if m.file_path == file_filter]+ if module_filter:+ metrics = [m for m in metrics if m.file_path.startswith(module_filter)]+ metrics_sorted = sorted(metrics, key=lambda m: m.score)++ findings = report.findings+ if file_filter:+ findings = [f for f in findings if f.file_path == file_filter]+ if module_filter:+ findings = [f for f in findings if f.file_path.startswith(module_filter)]++ if refactoring_targets:+ _render_refactoring_targets(metrics_sorted, findings, fmt=fmt)+ return++ if fmt == "json":+ click.echo(+ json.dumps(+ {+ "kpis": report.kpis,+ "metrics": [+ {+ "file_path": m.file_path,+ "score": m.score,+ "max_ccn": m.max_ccn,+ "max_nesting": m.max_nesting,+ "nloc": m.nloc,+ "has_test_file": m.has_test_file,+ }+ for m in metrics_sorted+ ],+ "findings": [+ {+ "biomarker_type": f.biomarker_type,+ "severity": str(f.severity),+ "file_path": f.file_path,+ "function_name": f.function_name,+ "health_impact": f.health_impact,+ "details": f.details,+ "reason": f.reason,+ }+ for f in findings+ ],+ },+ indent=2,+ )+ )+ return++ if fmt == "md":+ click.echo("# Code Health Report\n")+ for k, v in report.kpis.items():+ click.echo(f"- **{k}**: {v}")+ click.echo("\n## Findings\n")+ for f in findings:+ click.echo(+ f"- [{f.severity}] `{f.file_path}` {f.function_name or ''} "+ f"- {f.reason} (impact -{f.health_impact:.2f})"+ )+ return++ # Table format+ kpis = report.kpis+ console.print(+ f"\nHotspot: [bold]{kpis.get('hotspot_health', '?')}[/bold]/10 · "+ f"Average: [bold]{kpis.get('average_health', '?')}[/bold]/10 · "+ f"Worst: [bold]{kpis.get('worst_performer_score', '?')}[/bold]/10 "+ f"({kpis.get('worst_performer_path', 'n/a')})\n"+ )++ table = Table(title=f"Lowest-scoring files ({min(len(metrics_sorted), 20)})")+ table.add_column("File", style="cyan")+ table.add_column("Score", justify="right")+ table.add_column("CCN", justify="right")+ table.add_column("Nest", justify="right")+ table.add_column("NLOC", justify="right")+ table.add_column("Test?", justify="center")+ for m in metrics_sorted[:20]:+ score_color = "red" if m.score < 4 else "yellow" if m.score < 7 else "green"+ table.add_row(+ m.file_path,+ f"[{score_color}]{m.score:.1f}[/{score_color}]",+ str(m.max_ccn),+ str(m.max_nesting),+ str(m.nloc),+ "✓" if m.has_test_file else "—",+ )+ console.print(table)++ if findings:+ console.print(f"\n[bold]{len(findings)}[/bold] biomarker findings:")+ f_table = Table()+ f_table.add_column("Severity", style="magenta")+ f_table.add_column("Biomarker", style="cyan")+ f_table.add_column("File")+ f_table.add_column("Function")+ f_table.add_column("Impact", justify="right")+ for f in findings[:30]:+ f_table.add_row(+ str(f.severity),+ f.biomarker_type,+ f.file_path,+ f.function_name or "-",+ f"-{f.health_impact:.2f}",+ )+ console.print(f_table)+++def _effort_bucket(nloc: int) -> tuple[str, int]:+ if nloc <= 40:+ return "S", 1+ if nloc <= 150:+ return "M", 2+ if nloc <= 400:+ return "L", 3+ return "XL", 5+++def _render_refactoring_targets(+ metrics: list, findings: list, *, fmt: str, limit: int = 20+) -> None:+ """Aggregate findings per file, rank by impact/effort, render."""+ by_file: dict[str, list] = {}+ for f in findings:+ by_file.setdefault(f.file_path, []).append(f)++ metric_by_path = {m.file_path: m for m in metrics}+ targets: list[dict] = []+ for path, fs in by_file.items():+ m = metric_by_path.get(path)+ nloc = m.nloc if m is not None else 0+ score = m.score if m is not None else 10.0+ primary = max(fs, key=lambda x: x.health_impact)+ total_impact = round(sum(x.health_impact for x in fs), 3)+ bucket, weight = _effort_bucket(nloc)+ targets.append(+ {+ "file_path": path,+ "score": round(score, 2),+ "nloc": nloc,+ "primary_biomarker": primary.biomarker_type,+ "primary_severity": str(primary.severity),+ "primary_reason": primary.reason,+ "total_impact": total_impact,+ "effort_bucket": bucket,+ "impact_per_effort": round(total_impact / weight, 3),+ "finding_count": len(fs),+ }+ )+ targets.sort(key=lambda t: (-t["impact_per_effort"], -t["total_impact"]))+ targets = targets[:limit]++ if fmt == "json":+ click.echo(json.dumps({"targets": targets}, indent=2))+ return+ if fmt == "md":+ click.echo("# Refactoring targets\n")+ for t in targets:+ click.echo(+ f"- **{t['file_path']}** ({t['effort_bucket']}, "+ f"score {t['score']:.1f}/10, -{t['total_impact']:.2f}) "+ f"— {t['primary_biomarker']}: {t['primary_reason']}"+ )+ return++ table = Table(title=f"Refactoring targets ({len(targets)})")+ table.add_column("File", style="cyan")+ table.add_column("Score", justify="right")+ table.add_column("Impact", justify="right")+ table.add_column("Effort", justify="center")+ table.add_column("Ratio", justify="right")+ table.add_column("Primary biomarker")+ for t in targets:+ table.add_row(+ t["file_path"],+ f"{t['score']:.1f}",+ f"-{t['total_impact']:.2f}",+ t["effort_bucket"],+ f"{t['impact_per_effort']:.2f}",+ t["primary_biomarker"],+ )+ console.print(table)+++def _render_trend(repo_path: object, *, fmt: str) -> None:+ """Print the last 10 health snapshots straight from SQLite history.++ Reads through the existing CLI db-url helper so this works on+ workspace and single-repo indexes alike. When no snapshots exist+ (e.g. health was never run), prints a friendly hint.+ """+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_repository_by_path,+ list_health_snapshots,+ )++ async def _fetch() -> tuple[list[dict], object]:+ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return [], None+ snaps = await list_health_snapshots(session, repo.id)+ return recent_kpis(snaps, limit=10), diff_snapshots(snaps)++ rows, summary = run_async(_fetch())+ if not rows:+ console.print(+ "[yellow]No health snapshots yet. Run `repowise init` or `repowise health` "+ "to populate history.[/yellow]"+ )+ return++ if fmt == "json":+ click.echo(+ json.dumps(+ {+ "recent": rows,+ "alerts": [+ {+ "kind": a.kind,+ "metric": a.metric,+ "current": a.current,+ "baseline": a.baseline,+ "delta": a.delta,+ "message": a.message,+ }+ for a in (summary.alerts if summary else [])+ ],+ },+ indent=2,+ )+ )+ return++ table = Table(title="Code-health snapshots (newest first)")+ table.add_column("Taken at")+ table.add_column("Hotspot", justify="right")+ table.add_column("Average", justify="right")+ table.add_column("Worst", justify="right")+ table.add_column("Worst file", style="dim")+ for r in rows:+ table.add_row(+ (r["taken_at"] or "—")[:19],+ f"{r['hotspot_health']:.2f}",+ f"{r['average_health']:.2f}",+ f"{r['worst_performer_score']:.2f}" if r["worst_performer_score"] is not None else "—",+ r["worst_performer_path"] or "—",+ )+ console.print(table)++ if summary and summary.alerts:+ console.print()+ for a in summary.alerts:+ color = "red" if a.kind == "declining" else "yellow"+ console.print(f"[{color}]⚠ {a.kind}[/{color}]: {a.message}")+++def _persist_health(+ repo_path: object,+ *,+ report: object,+ coverage_files: list,+ coverage_format: str | None,+) -> None:+ """Write the analyzer's output to the repo's wiki.db.++ Mirrors what ``pipeline/persist.py`` does for ``repowise init``:+ overwrite the four health tables for this repo with the freshly+ computed values. Best-effort — a missing repo row or a DB error+ logs to stderr and returns rather than crashing the CLI.+ """+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_repository_by_path,+ save_coverage_files,+ save_health_findings,+ save_health_metrics,+ save_health_snapshot,+ )++ async def _do() -> None:+ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ console.print(+ "[yellow]No repository row yet — run `repowise init` once "+ "before persisting health updates.[/yellow]"+ )+ return+ repo_id = repo.id+ head_sha = getattr(repo, "head_commit", None)++ if coverage_files:+ await save_coverage_files(+ session,+ repo_id,+ coverage_files,+ source_format=coverage_format or "lcov",+ ingested_commit_sha=head_sha,+ )++ await save_health_metrics(session, repo_id, list(getattr(report, "metrics", []) or []))+ findings = list(getattr(report, "findings", []) or [])+ if findings:+ await save_health_findings(session, repo_id, findings)++ kpis = getattr(report, "kpis", {}) or {}+ metrics = getattr(report, "metrics", []) or []+ try:+ await save_health_snapshot(+ session,+ repo_id,+ hotspot_health=float(kpis.get("hotspot_health", 10.0)),+ average_health=float(kpis.get("average_health", 10.0)),+ worst_performer_path=kpis.get("worst_performer_path"),+ worst_performer_score=kpis.get("worst_performer_score"),+ per_file_scores={+ m.file_path: round(float(m.score), 2) for m in metrics+ },+ )+ except Exception as exc:+ console.print(f"[yellow]Snapshot write skipped: {exc}[/yellow]")++ await session.commit()++ try:+ run_async(_do())+ except Exception as exc:+ console.print(f"[red]Could not persist health to DB: {exc}[/red]")diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.pyindex 85abdc7b9..f5cf88899 100644--- a/packages/cli/src/repowise/cli/commands/status_cmd.py+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py@@ -2,8 +2,8 @@from __future__ import annotations+from datetime import UTCfrom pathlib import Path-from typing import Anyimport clickfrom rich.table import Table@@ -11,16 +11,13 @@ from rich.table import Tablefrom repowise.cli.helpers import (CommandTarget,console,- find_workspace_root,get_db_url_for_repo,get_repowise_dir,load_state,resolve_command_target,- resolve_repo_path,run_async,)-# ---------------------------------------------------------------------------# Workspace status# ---------------------------------------------------------------------------@@ -129,17 +126,85 @@ def _query_page_count(repo_path: Path) -> int:return 0+def _query_health_line(repo_path: Path) -> str | None:+ """One-line health summary for ``repowise status``.++ Returns ``None`` when no health data exists yet so the caller can+ skip the line silently. Format matches plan §4 P4.10:++ Health: 7.4 (avg) · 6.2 (hotspots) · 2.1 (worst: payments/processor.ts)+ """+ db_path = get_repowise_dir(repo_path) / "wiki.db"+ if not db_path.exists():+ return None++ async def _q() -> dict | None:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ )+ from repowise.core.persistence.crud import (+ get_health_metrics,+ get_health_summary,+ get_repository_by_path,+ )++ url = get_db_url_for_repo(repo_path)+ engine = create_engine(url)+ sf = create_session_factory(engine)+ try:+ async with get_session(sf) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ return None+ summary = await get_health_summary(session, repo.id)+ if summary["file_count"] == 0:+ return None+ metrics = await get_health_metrics(session, repo.id)+ # Hotspot health: NLOC-weighted avg of top-25% files by NLOC.+ if metrics:+ by_nloc = sorted(metrics, key=lambda m: m.nloc or 0, reverse=True)+ top = by_nloc[: max(1, len(by_nloc) // 4)]+ tot = sum(max(m.nloc, 1) for m in top)+ hotspot = (+ sum(m.score * max(m.nloc, 1) for m in top) / tot+ if tot+ else summary["average_health"]+ )+ else:+ hotspot = summary["average_health"]+ return {**summary, "hotspot_health": round(hotspot, 2)}+ finally:+ await engine.dispose()++ try:+ data = run_async(_q())+ except Exception:+ return None+ if not data:+ return None+ worst_path = data["worst_performer_path"] or "n/a"+ worst_score = data["worst_performer_score"]+ worst_repr = f"{worst_score:.1f}" if worst_score is not None else "—"+ return (+ f"[bold]Health:[/bold] {data['average_health']:.1f} (avg) · "+ f"{data['hotspot_health']:.1f} (hotspots) · "+ f"{worst_repr} (worst: {worst_path})"+ )++def _format_relative_time(iso_timestamp: str | None) -> str:"""Format an ISO 8601 timestamp as a relative time string."""if not iso_timestamp:return "-"try:- from datetime import datetime, timezone+ from datetime import datetimedt = datetime.fromisoformat(iso_timestamp)if dt.tzinfo is None:- dt = dt.replace(tzinfo=timezone.utc)- now = datetime.now(timezone.utc)+ dt = dt.replace(tzinfo=UTC)+ now = datetime.now(UTC)delta = now - dtseconds = int(delta.total_seconds())if seconds < 60:@@ -153,7 +218,7 @@ def _format_relative_time(iso_timestamp: str | None) -> str:return iso_timestamp[:10] if len(iso_timestamp) >= 10 else iso_timestamp-def _workspace_status(target: "CommandTarget") -> None:+def _workspace_status(target: CommandTarget) -> None:"""Show status for all repos in a workspace."""from repowise.core.workspace import check_repo_staleness@@ -361,3 +426,8 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool) -> Nonpages_table.add_row("[bold]Total[/bold]", f"[bold]{sum(counts.values())}[/bold]")pages_table.add_row("Total tokens", f"{total_db_tokens:,}")console.print(pages_table)++ health_line = _query_health_line(repo_path)+ if health_line:+ console.print()+ console.print(health_line)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.pyindex a295bff35..a97cc62c5 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py@@ -3,6 +3,7 @@from __future__ import annotationsimport time+from typing import Anyimport clickfrom rich.table import Table@@ -78,6 +79,28 @@ def _resolve_index_only_mode(return _infer_legacy_docs_enabled(state) is False+async def _persist_partial_health(session: Any, repo_id: str, report: Any) -> None:+ """Upsert health findings + metrics for the changed-files subset.++ Unlike ``persist_pipeline_result`` (which delete-then-inserts the+ whole repo), this writer only touches rows whose ``file_path`` is in+ the partial report — so unchanged files keep their existing findings+ and metrics across an incremental ``repowise update``.+ """+ from repowise.core.persistence.crud import (+ upsert_health_findings,+ upsert_health_metrics,+ )++ changed_paths = sorted({m.file_path for m in report.metrics or []})+ if not changed_paths:+ return+ await upsert_health_metrics(session, repo_id, report.metrics or [])+ await upsert_health_findings(+ session, repo_id, list(report.findings or []), file_paths=changed_paths+ )++# ---------------------------------------------------------------------------# Workspace update flow# ---------------------------------------------------------------------------@@ -114,7 +137,9 @@ def _workspace_update(abs_path = (ws_root / entry.path).resolve()stored = entry.last_commit_at_indexis_stale, head, behind = check_repo_staleness(abs_path, stored)- status = f"[yellow]{behind} new commit(s)[/yellow]" if is_stale else "[green]up to date[/green]"+ status = (+ f"[yellow]{behind} new commit(s)[/yellow]" if is_stale else "[green]up to date[/green]"+ )if not (abs_path / ".repowise").is_dir():status = "[dim]not indexed[/dim]"console.print(f" {entry.alias:<20} {status}")@@ -312,8 +337,7 @@ def update_command()raise click.ClickException(f"No previous sync found for {repo_path}. "- "Run 'repowise init' there first, or pass --since <ref>."- + hint+ "Run 'repowise init' there first, or pass --since <ref>." + hint)if head and head == base_ref:@@ -364,9 +388,7 @@ def update_command(save_state(repo_path, state)# --- Resolve effective mode (index-only vs full LLM regen) ---- index_only = _resolve_index_only_mode(- index_only=index_only, docs_flag=docs_flag, state=state- )+ index_only = _resolve_index_only_mode(index_only=index_only, docs_flag=docs_flag, state=state)# --- Acquire update lock so the augment hook can suppress its# stale-wiki warning while this run is in flight (typical case: the@@ -492,6 +514,38 @@ def update_command(console.print("[yellow]Dry run — no pages regenerated.[/yellow]")return+ # Run partial code-health analysis up front so both the index-only+ # and full paths can upsert findings/metrics for changed files only.+ # The full file-list is needed because duplication is cross-file —+ # but only files in ``changed_paths`` produce new findings/metrics.+ partial_health_report = None+ try:+ from repowise.core.analysis.health import HealthAnalyzer+ from repowise.core.analysis.health.config import HealthConfig++ _health_analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ )+ _health_changed = {fd.path for fd in file_diffs if fd.status in ("added", "modified")}+ if _health_changed:+ _hcfg = HealthConfig.load(repo_path)+ _analyzer_config = (+ _hcfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])+ if (_hcfg.disabled_biomarkers or _hcfg.rules)+ else None+ )+ partial_health_report = _health_analyzer.analyze(+ _analyzer_config, changed_files=_health_changed+ )+ console.print(+ f"Health analysis (partial): [cyan]{len(_health_changed)} files[/cyan], "+ f"[yellow]{len(partial_health_report.findings)} findings[/yellow]"+ )+ except Exception as exc:+ console.print(f"[yellow]Health analysis skipped: {exc}[/yellow]")+# Run partial dead-code analysis up front so both branches can# persist its results. Previously this sat below the ``if index_only``# short-circuit, which left the closure's reference to@@ -555,13 +609,15 @@ def update_command(save_dead_code_findings,)- await save_dead_code_findings(- session, repo_id, dead_code_report.findings- )+ await save_dead_code_findings(session, repo_id, dead_code_report.findings)except Exception as exc:- console.print(- f"[yellow]Dead-code persist skipped: {exc}[/yellow]"- )+ console.print(f"[yellow]Dead-code persist skipped: {exc}[/yellow]")++ if partial_health_report is not None:+ try:+ await _persist_partial_health(session, repo_id, partial_health_report)+ except Exception as exc:+ console.print(f"[yellow]Health persist skipped: {exc}[/yellow]")# Re-persist graph_nodes so symbol-level PageRank /# betweenness / community ids stay in sync with the@@ -574,9 +630,7 @@ def update_command(await persist_graph_nodes(session, repo_id, graph_builder)except Exception as exc:- console.print(- f"[yellow]Graph nodes persist skipped: {exc}[/yellow]"- )+ console.print(f"[yellow]Graph nodes persist skipped: {exc}[/yellow]")run_async(_persist_index_only())save_state(repo_path, {**state, "last_sync_commit": head})@@ -665,9 +719,7 @@ def update_command(engine = create_engine(url)sf = create_session_factory(engine)async with get_session(sf) as session:- repo = await upsert_repository(- session, name=repo_path.name, local_path=str(repo_path)- )+ repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))return await load_prior_pages(session, repo.id)try:@@ -757,6 +809,14 @@ def update_command(except Exception:pass # never fail update due to decision processing+ # Persist code-health findings + metrics (partial — upsert only)+ if partial_health_report is not None:+ try:+ async with get_session(sf) as session:+ await _persist_partial_health(session, repo_id, partial_health_report)+ except Exception:+ pass # health persistence is best-effort+# Persist dead code findings (partial)if dead_code_report and dead_code_report.findings:try:@@ -851,6 +911,7 @@ def update_command(ws_config = WorkspaceConfig.load(ws_root)# Find this repo's alias in the workspace configfrom pathlib import Path as _P+repo_abs = repo_path.resolve()alias = Nonefor entry in ws_config.repos:diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 036297aed..59e7152e0 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -13,6 +13,7 @@ from repowise.cli.commands.decision_cmd import decision_groupfrom repowise.cli.commands.delete_cmd import delete_commandfrom repowise.cli.commands.doctor_cmd import doctor_commandfrom repowise.cli.commands.export_cmd import export_command+from repowise.cli.commands.health_cmd import health_commandfrom repowise.cli.commands.hook_cmd import hook_groupfrom repowise.cli.commands.init_cmd import init_commandfrom repowise.cli.commands.mcp_cmd import mcp_command@@ -51,6 +52,7 @@ cli.add_command(claude_md_command)cli.add_command(costs_command)cli.add_command(update_command)cli.add_command(dead_code_command)+cli.add_command(health_command)cli.add_command(decision_group)cli.add_command(search_command)cli.add_command(export_command)diff --git a/packages/core/alembic/versions/0019_code_health.py b/packages/core/alembic/versions/0019_code_health.pynew file mode 100644index 000000000..9a373fc05--- /dev/null+++ b/packages/core/alembic/versions/0019_code_health.py@@ -0,0 +1,172 @@+"""Add code-health tables: findings, file metrics, snapshots, coverage.++Revision ID: 0019+Revises: 0018+Create Date: 2026-05-18+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++revision: str = "0019"+down_revision: str | None = "0018"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ # ------------------------------------------------------------------+ # health_findings — one row per biomarker hit+ # ------------------------------------------------------------------+ op.create_table(+ "health_findings",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("biomarker_type", sa.String(64), nullable=False),+ sa.Column("severity", sa.String(16), nullable=False),+ sa.Column("function_name", sa.String(255), nullable=True),+ sa.Column("line_start", sa.Integer, nullable=True),+ sa.Column("line_end", sa.Integer, nullable=True),+ sa.Column("details_json", sa.Text, nullable=False, server_default="{}"),+ sa.Column("health_impact", sa.Float, nullable=False, server_default="0.0"),+ sa.Column("reason", sa.Text, nullable=False, server_default=""),+ sa.Column("status", sa.String(32), nullable=False, server_default="open"),+ sa.Column(+ "created_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ )+ op.create_index(+ "ix_health_findings_repository_id",+ "health_findings",+ ["repository_id"],+ )+ op.create_index(+ "ix_health_findings_repo_file",+ "health_findings",+ ["repository_id", "file_path"],+ )++ # ------------------------------------------------------------------+ # health_file_metrics — one row per file (unique on repo + path)+ # ------------------------------------------------------------------+ op.create_table(+ "health_file_metrics",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("score", sa.Float, nullable=False, server_default="10.0"),+ sa.Column("max_ccn", sa.Integer, nullable=False, server_default="0"),+ sa.Column("max_nesting", sa.Integer, nullable=False, server_default="0"),+ sa.Column("nloc", sa.Integer, nullable=False, server_default="0"),+ sa.Column("duplication_pct", sa.Float, nullable=True),+ sa.Column("has_test_file", sa.Boolean, nullable=False, server_default="0"),+ sa.Column("line_coverage_pct", sa.Float, nullable=True),+ sa.Column("branch_coverage_pct", sa.Float, nullable=True),+ sa.Column("module", sa.String(255), nullable=True),+ sa.Column(+ "updated_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.UniqueConstraint("repository_id", "file_path", name="uq_health_file_metrics"),+ )+ op.create_index(+ "ix_health_file_metrics_repo",+ "health_file_metrics",+ ["repository_id"],+ )++ # ------------------------------------------------------------------+ # health_snapshots — KPI history + compact per-file score map+ # ------------------------------------------------------------------+ op.create_table(+ "health_snapshots",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column(+ "taken_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column("hotspot_health", sa.Float, nullable=False, server_default="10.0"),+ sa.Column("average_health", sa.Float, nullable=False, server_default="10.0"),+ sa.Column("worst_performer_path", sa.Text, nullable=True),+ sa.Column("worst_performer_score", sa.Float, nullable=True),+ sa.Column("per_file_scores_json", sa.Text, nullable=False, server_default="{}"),+ )+ op.create_index(+ "ix_health_snapshots_repo",+ "health_snapshots",+ ["repository_id"],+ )++ # ------------------------------------------------------------------+ # coverage_files — last-ingestion coverage per file+ # ------------------------------------------------------------------+ op.create_table(+ "coverage_files",+ sa.Column("id", sa.String(32), primary_key=True),+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("file_path", sa.Text, nullable=False),+ sa.Column("source_format", sa.String(32), nullable=False),+ sa.Column("line_coverage_pct", sa.Float, nullable=False, server_default="0.0"),+ sa.Column("branch_coverage_pct", sa.Float, nullable=True),+ sa.Column("covered_lines_json", sa.Text, nullable=False, server_default="[]"),+ sa.Column("total_coverable_lines", sa.Integer, nullable=False, server_default="0"),+ sa.Column(+ "ingested_at",+ sa.DateTime(timezone=True),+ nullable=False,+ server_default=sa.func.now(),+ ),+ sa.Column("ingested_commit_sha", sa.String(40), nullable=True),+ sa.UniqueConstraint("repository_id", "file_path", name="uq_coverage_files"),+ )+ op.create_index(+ "ix_coverage_files_repo",+ "coverage_files",+ ["repository_id"],+ )+++def downgrade() -> None:+ op.drop_table("coverage_files")+ op.drop_table("health_snapshots")+ op.drop_table("health_file_metrics")+ op.drop_table("health_findings")diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.mdnew file mode 100644index 000000000..9c0204cbe--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/README.md@@ -0,0 +1,124 @@+# Code Health analysis layer++Fifth intelligence layer alongside Graph, Git, Docs, and Decisions. Computes a+per-file health score (1.0–10.0) from twelve deterministic biomarkers, ingests+test-coverage data, tracks repo-level KPIs over time, and surfaces refactoring+targets ranked by impact-per-effort.++**Zero LLM calls.** Pure Python over tree-sitter + git data. Designed to finish+in under 30 s on a 3 000-file repo (see `tests/integration/test_health_perf_benchmark.py`).++## Public API++```python+from repowise.core.analysis.health import HealthAnalyzer, HealthReport++analyzer = HealthAnalyzer(+ graph,+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ coverage_map=coverage_map, # optional, see coverage/README.md+ module_map=module_map, # optional, file_path → community label+)++report = analyzer.analyze(config=None)+# or, for repos large enough to benefit from parallel parsing:+report = await analyzer.analyze_async()++# Incremental — only the files in `changed_files` produce findings/metrics.+# Duplication still runs cross-file so unchanged clone partners are honoured.+report = analyzer.analyze(changed_files={"a.py", "b.py"})+```++### Returned shapes++- `report.findings` — `list[HealthFindingData]`. One row per biomarker hit.+- `report.metrics` — `list[HealthFileMetricData]`. One row per analyzed file.+- `report.kpis` — `{"hotspot_health", "average_health", "worst_performer_path",+ "worst_performer_score", "file_count"}`. Skipped on incremental runs.++## Persistence++Three SQLAlchemy tables back the layer (Alembic-managed, no JSON files):++| Table | Purpose | Writer |+|-------|---------|--------|+| `health_findings` | One row per biomarker hit. Lifecycle: `open` → `acknowledged` / `resolved` / `false_positive`. | `save_health_findings` / `upsert_health_findings` |+| `health_file_metrics` | Per-file aggregate + final score. | `save_health_metrics` / `upsert_health_metrics` |+| `health_snapshots` | KPI history (50-row rolling window). | `save_health_snapshot` |+| `coverage_files` | Per-file coverage (line + branch). | `save_coverage_files` |++`save_*` variants replace the whole repo (init path). `upsert_*` variants only+touch the rows for a given file-path set — used by `repowise update` so+unchanged files keep their findings across incremental runs.++## Trends++`trends.py` is pure logic over an in-memory snapshot list:++- **Declining Health** alert: current is ≥ 0.5 points below the snapshot+ N-5 entries back (constants `DECLINE_THRESHOLD`, `DECLINE_LOOKBACK`).+- **Predicted Decline** alert: the three most recent snapshots are each+ strictly below the one before.++Use `diff_snapshots(history)` for a `TrendSummary`, or `recent_kpis(history,+limit=10)` for the CLI / dashboard table.++## Refactoring suggestions++`suggestions.suggestion_for(biomarker_type)` returns the canonical, static+text used by both the MCP `get_health(include=["refactoring"])` response and+the dashboard's `RefactoringCard`. Templates live in `suggestions.py` —+adding a new biomarker means adding a new `_TEMPLATES` entry.++## Module rollups++`HealthFileMetric.module` is populated from graph community labels by the+orchestrator (falls back to the top-level directory). The MCP tool+(`tool_health.py`) and the API endpoint (`routers/code_health.py`) both+expose NLOC-weighted module aggregates and accept `module:foo` targets.++## Sub-packages++- `complexity/` — tree-sitter AST walker. CCN, max nesting, cognitive,+ parameter count, bumps. Single AST pass per file. Writes+ `Symbol.complexity_estimate` as a side effect.+- `coverage/` — LCOV / Cobertura / Clover parsers + test-file heuristic.+- `duplication/` — Rabin–Karp over tree-sitter tokens. Co-change correlation+ via `git_meta_map[path]["co_change_partners_json"]`.+- `biomarkers/` — one detector per file. Implements the `Biomarker`+ Protocol from `biomarkers/base.py`. Twelve total in v1.++Each sub-package has its own `README.md` covering inputs, outputs, and+extension points.++## Extension points++- **New biomarker.** Drop a file under `biomarkers/`, implement+ `Biomarker.detect(ctx) -> list[BiomarkerResult]`, register in+ `biomarkers/registry.py`, add a suggestion in `suggestions.py`, add the+ category mapping in `scoring._BIOMARKER_CATEGORY`.+- **New complexity language.** Add a `LanguageNodeMap` entry to+ `complexity/languages.py`. No new `.scm` files needed.+- **New coverage format.** Drop a parser under `coverage/` and register it+ with `coverage/detector.py`.+- **Per-file overrides.** Users write `.repowise/health-rules.json`. See+ `config.HealthConfig` and `tests/unit/health/test_health_config.py`.++## Performance++`HealthAnalyzer.analyze_async()` parallelises the per-file work via+`asyncio.gather` + `asyncio.to_thread`. Tree-sitter releases the GIL during+parsing, so this scales on single-process Python. The orchestrator picks the+parallel path automatically when `len(parsed_files) >= 500`.++## Where to look in the codebase++- CLI: `packages/cli/src/repowise/cli/commands/health_cmd.py`,+ `status_cmd.py`, `update_cmd.py`.+- MCP tools: `packages/server/src/repowise/server/mcp_server/tool_health.py`+ + enrichments in `tool_risk.py`, `tool_context.py`, `tool_overview.py`.+- API: `packages/server/src/repowise/server/routers/code_health.py`.+- UI primitives: `packages/ui/src/health/`. Web routes:+ `packages/web/src/app/repos/[id]/health/`.+- CLAUDE.md template stanza: `packages/core/src/repowise/core/generation/templates/claude_md.j2`.diff --git a/packages/core/src/repowise/core/analysis/health/__init__.py b/packages/core/src/repowise/core/analysis/health/__init__.pynew file mode 100644index 000000000..e1ab4ae63--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/__init__.py@@ -0,0 +1,24 @@+"""Code Health analysis layer.++Public surface kept minimal. Engine + report types only — sub-packages+are accessed directly by their owners (pipeline orchestrator, MCP tool,+tests).+"""++from __future__ import annotations++from .engine import HealthAnalyzer+from .models import (+ HealthFileMetricData,+ HealthFindingData,+ HealthReport,+ Severity,+)++__all__ = [+ "HealthAnalyzer",+ "HealthFileMetricData",+ "HealthFindingData",+ "HealthReport",+ "Severity",+]diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/README.md b/packages/core/src/repowise/core/analysis/health/biomarkers/README.mdnew file mode 100644index 000000000..d55d4bcb3--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/README.md@@ -0,0 +1,74 @@+# biomarkers/++One detector per file. Each implements the `Biomarker` Protocol:++```python+class Biomarker(Protocol):+ name: str # snake_case identifier, e.g. "brain_method"+ category: str # scoring category (see scoring.CATEGORY_CAPS)+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...+```++## Registered v1 detectors (12)++Structural complexity (cap −3.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.++Size & complexity (cap −2.0):+- `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):+- `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):+- `developer_congestion` — too many active authors competing on a file.+- `knowledge_loss` — primary authors no longer active.++## Inputs++`FileContext` (see `base.py`) carries:++- `file_path`, `language`, `nloc`, `module`, `has_test_file`.+- `function_metrics` — `dict[symbol_name → FunctionComplexity]`.+- `git_meta` — per-file git metadata (commits, owners, bus factor,+ co-change partners).+- `dependents_count` — file-level in-edge count from the graph.+- `pagerank_score` — graph centrality (0.0 when symbol-only).+- `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.++## Outputs++`BiomarkerResult` carries severity, function name, line span, a `details`+dict (JSON-serialised into `HealthFinding.details_json` for the UI), and a+`reason` string. `health_impact` is filled in by the scorer.++## Performance characteristics++- Each detector is pure and stateless — safe to share across threads.+- The registry instantiates one fresh detector list per `detect_all`+ call. Cheap (constructors take no args).+- All detectors are O(symbols in file). No detector walks the whole+ parsed_file set on its own — cross-file signals (clones, co-change) are+ pre-aggregated by the engine.++## Extension points++To add a 13th biomarker:++1. New file `biomarkers/my_marker.py` with a class implementing the+ `Biomarker` protocol.+2. Append to `_DETECTOR_FACTORIES` in `registry.py`.+3. Add the biomarker → category mapping in `scoring._BIOMARKER_CATEGORY`.+4. Add a suggestion template in `suggestions._TEMPLATES`.+5. Add a unit test under `tests/unit/health/`.+6. Update this README's "Registered v1 detectors" list.diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py b/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.pynew file mode 100644index 000000000..aac4ed3e3--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/__init__.py@@ -0,0 +1,14 @@+"""Biomarker detectors — see ``README.md``."""++from __future__ import annotations++from .base import Biomarker, BiomarkerResult, FileContext+from .registry import detect_all, registered_biomarkers++__all__ = [+ "Biomarker",+ "BiomarkerResult",+ "FileContext",+ "detect_all",+ "registered_biomarkers",+]diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.pynew file mode 100644index 000000000..2d08015a4--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py@@ -0,0 +1,69 @@+"""Biomarker contract: Protocol + ``BiomarkerResult`` + ``FileContext``."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Protocol++from ..complexity import FunctionComplexity+from ..duplication import ClonePair+from ..models import Severity+++@dataclass+class FileContext:+ """All inputs a biomarker may need to evaluate a file.++ Populated by ``engine.py`` once per file. Biomarkers are pure+ functions over this context — they don't open files or talk to the+ DB themselves.+ """++ file_path: str+ language: str+ nloc: int+ has_test_file: bool+ module: str | None+ # Map symbol-name → complexity metrics for functions/methods in this+ # file. Symbols without a complexity row default to CCN=1, nesting=0.+ function_metrics: dict[str, FunctionComplexity] = field(default_factory=dict)+ # Per-file git metadata (may be empty when git indexing skipped).+ git_meta: dict[str, Any] = field(default_factory=dict)+ # Graph-derived signals.+ dependents_count: int = 0+ pagerank_score: float = 0.0+ # Coverage signals (populated when --coverage was ingested). When no+ # coverage is available these stay ``None`` and coverage-aware+ # biomarkers return no findings.+ line_coverage_pct: float | None = None+ branch_coverage_pct: float | None = None+ covered_lines: set[int] = field(default_factory=set)+ total_coverable_lines: int = 0+ # Duplication signals (populated when the engine ran the+ # duplication detector for this analyze() call). ``clones`` is the+ # list of clone pairs this file participates in; ``duplication_pct``+ # is the percent of NLOC covered by clones.+ clones: list[ClonePair] = field(default_factory=list)+ duplication_pct: float | None = None+++@dataclass+class BiomarkerResult:+ """One biomarker hit before scoring deductions are applied."""++ biomarker_type: str+ severity: Severity+ function_name: str | None+ line_start: int | None+ line_end: int | None+ details: dict[str, Any]+ reason: str = ""+++class Biomarker(Protocol):+ """Detector contract. Each concrete biomarker is a stateless object."""++ name: str+ category: str # one of the scoring categories in ``scoring.CATEGORY_CAPS``.++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]: ...diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.pynew file mode 100644index 000000000..ef897b624--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/brain_method.py@@ -0,0 +1,73 @@+"""Brain Method — long, complex, and central in one symbol.++CodeScene's signature biomarker: a function that does too much. We flag+when **all three** conditions hold:++- NLOC ≥ 70 (the function is long)+- CCN ≥ 9 (it has many decision paths)+- enclosing file has ≥ 8 dependents OR pagerank_score in the top decile+ (it sits at a hub, so refactoring carries leverage)++The file-level centrality check matches the plan's intent ("Brain Method+detection uses graph centrality"). We approximate the per-symbol+in-degree with the per-file dependents count because symbol-level+PageRank is not currently exposed via a simple synchronous API; the+file-level proxy is conservative.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext+++class BrainMethodDetector:+ name = "brain_method"+ category = "structural_complexity"++ # Thresholds (locked for v1 — see plan §5).+ _NLOC_THRESHOLD = 70+ _CCN_THRESHOLD = 9+ _DEPENDENTS_THRESHOLD = 8++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ if ctx.dependents_count < self._DEPENDENTS_THRESHOLD:+ return []++ out: list[BiomarkerResult] = []+ for fn in ctx.function_metrics.values():+ if fn.nloc < self._NLOC_THRESHOLD:+ continue+ if fn.ccn < self._CCN_THRESHOLD:+ continue++ severity = (+ Severity.CRITICAL+ if fn.ccn >= 20 and fn.nloc >= 150+ else Severity.HIGH+ if fn.ccn >= 14 or fn.nloc >= 120+ else Severity.MEDIUM+ )+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={+ "ccn": fn.ccn,+ "nloc": fn.nloc,+ "max_nesting": fn.max_nesting,+ "dependents_count": ctx.dependents_count,+ },+ reason=(+ f"Brain Method: {fn.name} is {fn.nloc} lines, CCN {fn.ccn}, "+ f"in a file imported by {ctx.dependents_count} others"+ ),+ )+ )+ return out+++BIOMARKER = BrainMethodDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py b/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.pynew file mode 100644index 000000000..d7d64ab8a--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/bumpy_road.py@@ -0,0 +1,61 @@+"""Bumpy Road — many independent regions of nested control flow.++A "bumpy road" function is one with several distinct nesting humps —+not one deep block (that's `nested_complexity`) and not one big linear+list of branches (that's `complex_method`) but multiple medium-depth+blocks sitting side by side. SonarSource's terminology.++We use the walker's ``bumps`` metric — the count of top-level body+statements that reach nesting depth ≥ 2 — and fire when it crosses a+configurable threshold while CCN is also non-trivial. Threshold pair+matches CodeScene's documented defaults.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext+++class BumpyRoadDetector:+ name = "bumpy_road"+ category = "structural_complexity"++ _BUMP_THRESHOLD = 3+ _CCN_THRESHOLD = 5++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ out: list[BiomarkerResult] = []+ for fn in ctx.function_metrics.values():+ if fn.bumps < self._BUMP_THRESHOLD:+ continue+ if fn.ccn < self._CCN_THRESHOLD:+ continue+ severity = (+ Severity.HIGH+ if fn.bumps >= 5+ else Severity.MEDIUM+ if fn.bumps >= 4+ else Severity.LOW+ )+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={+ "bumps": fn.bumps,+ "ccn": fn.ccn,+ "max_nesting": fn.max_nesting,+ },+ reason=(+ f"{fn.name} has {fn.bumps} nested blocks at the same level (bumpy road)"+ ),+ )+ )+ return out+++BIOMARKER = BumpyRoadDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.pynew file mode 100644index 000000000..92988bab4--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/complex_method.py@@ -0,0 +1,49 @@+"""Complex Method — high cyclomatic complexity.++Flags functions with CCN ≥ 9. Conservative threshold; CodeScene defaults+to 9 as the boundary between "ok" and "complex".+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext+++class ComplexMethodDetector:+ name = "complex_method"+ category = "size_and_complexity"++ _CCN_THRESHOLD = 9++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ out: list[BiomarkerResult] = []+ for fn in ctx.function_metrics.values():+ if fn.ccn < self._CCN_THRESHOLD:+ continue+ severity = (+ Severity.CRITICAL+ if fn.ccn >= 25+ else Severity.HIGH+ if fn.ccn >= 15+ else Severity.MEDIUM+ )+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={+ "ccn": fn.ccn,+ "cognitive": fn.cognitive,+ "nloc": fn.nloc,+ },+ reason=f"{fn.name} has cyclomatic complexity {fn.ccn}",+ )+ )+ return out+++BIOMARKER = ComplexMethodDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.pynew file mode 100644index 000000000..52238fe77--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py@@ -0,0 +1,88 @@+"""Coverage Gap — significant uncovered surface in a non-trivial file.++Fires when a file has coverage data and:++- line_coverage_pct < 60 **and** uncovered lines ≥ 25, OR+- line_coverage_pct < 30 **and** total_coverable_lines ≥ 50.++Test files themselves are exempt (we don't care that+``test_foo.py`` has no coverage). Without coverage data the biomarker+does nothing — the absence-of-coverage case is the+``untested_hotspot`` biomarker's territory.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext++_LINE_COVERAGE_GAP = 60.0+_LINE_COVERAGE_DEEP_GAP = 30.0+_MIN_UNCOVERED_LINES = 25+_MIN_FILE_SIZE = 50+++class CoverageGapDetector:+ name = "coverage_gap"+ category = "test_coverage"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ if ctx.line_coverage_pct is None:+ return []+ if ctx.total_coverable_lines <= 0:+ return []+ if _looks_like_test_path(ctx.file_path):+ return []++ cov = ctx.line_coverage_pct+ total = ctx.total_coverable_lines+ uncovered = total - len(ctx.covered_lines or ())+ # Some parsers don't emit a per-line set; fall back to math.+ if uncovered <= 0:+ uncovered = round(total * (100.0 - cov) / 100.0)++ deep_gap = cov < _LINE_COVERAGE_DEEP_GAP and total >= _MIN_FILE_SIZE+ regular_gap = cov < _LINE_COVERAGE_GAP and uncovered >= _MIN_UNCOVERED_LINES+ if not (deep_gap or regular_gap):+ return []++ if deep_gap and uncovered >= 100:+ severity = Severity.HIGH+ elif deep_gap:+ severity = Severity.MEDIUM+ else:+ severity = Severity.LOW++ return [+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=None,+ line_start=None,+ line_end=None,+ details={+ "line_coverage_pct": cov,+ "branch_coverage_pct": ctx.branch_coverage_pct,+ "uncovered_lines": uncovered,+ "total_coverable_lines": total,+ },+ reason=(f"{uncovered}/{total} lines uncovered ({cov:.0f}% line coverage)"),+ )+ ]+++def _looks_like_test_path(path: str) -> bool:+ p = path.replace("\\", "/").lower()+ return (+ "/test/" in p+ or "/tests/" in p+ or "/__tests__/" in p+ or p.startswith(("test/", "tests/", "__tests__/"))+ or p.endswith(+ ("_test.py", "_test.go", ".test.ts", ".test.tsx", ".test.js", ".spec.ts", ".spec.js")+ )+ or p.rsplit("/", 1)[-1].startswith("test_")+ )+++BIOMARKER = CoverageGapDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/developer_congestion.py b/packages/core/src/repowise/core/analysis/health/biomarkers/developer_congestion.pynew file mode 100644index 000000000..3943ebacd--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/developer_congestion.py@@ -0,0 +1,89 @@+"""Developer Congestion — too many hands on a single file.++When a file has a large contributor count over a 90-day window and is+also a hotspot, coordination cost explodes. CodeScene calls this+"Developer Congestion" — strongly correlated with regression rates in+their published industry studies.++Fires when ALL of:++- ``contributor_count`` ≥ 5+- ``commit_count_90d`` ≥ 6 (the file is genuinely active)+- the primary owner's share is below 50% (no clear DRI)++Reads ``ctx.git_meta`` only; no AST work needed.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext++_CONTRIB_THRESHOLD = 5+_RECENT_COMMITS_THRESHOLD = 6+_OWNER_SHARE_THRESHOLD = 0.5+++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 _as_float(value: object, default: float = 0.0) -> float:+ try:+ return float(value or 0.0) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return default+++class DeveloperCongestionDetector:+ name = "developer_congestion"+ category = "organizational"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ meta = ctx.git_meta or {}+ contributors = _as_int(meta.get("contributor_count"))+ commits_90d = _as_int(meta.get("commit_count_90d"))+ primary_pct = _as_float(meta.get("primary_owner_commit_pct"))++ if contributors < _CONTRIB_THRESHOLD:+ return []+ if commits_90d < _RECENT_COMMITS_THRESHOLD:+ return []+ # primary_owner_commit_pct may be stored as a 0-1 fraction or+ # 0-100 percentage depending on the source - normalize.+ share = primary_pct / 100.0 if primary_pct > 1.0 else primary_pct+ if share >= _OWNER_SHARE_THRESHOLD:+ return []++ if contributors >= 10 and commits_90d >= 20:+ severity = Severity.HIGH+ elif contributors >= 7 or commits_90d >= 12:+ severity = Severity.MEDIUM+ else:+ severity = Severity.LOW++ return [+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=None,+ line_start=None,+ line_end=None,+ details={+ "contributor_count": contributors,+ "commit_count_90d": commits_90d,+ "primary_owner_share": round(share, 3),+ "primary_owner": meta.get("primary_owner_name"),+ },+ reason=(+ f"{contributors} contributors touched this file "+ f"({commits_90d} commits in last 90 days, no clear primary owner)"+ ),+ )+ ]+++BIOMARKER = DeveloperCongestionDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py b/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.pynew file mode 100644index 000000000..1884c7c90--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/dry_violation.py@@ -0,0 +1,82 @@+"""DRY Violation — significant duplication, weighted by co-change.++Fires when a file contains clone pairs that pass a minimum-size gate.+Severity grades on:++- how much of the file is duplicated (``duplication_pct``)+- the maximum co-change count across the file's clone pairs — actively+ co-modified duplication is a far stronger smell than dormant clones+ that haven't been touched together in months.++The detector reads from ``ctx.clones`` / ``ctx.duplication_pct``, which+the engine populates from ``duplication.detect_clones`` once per+analyze() call.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext++_MIN_DUP_PCT = 8.0+_MIN_CLONE_LINES = 6+_ACTIVE_CO_CHANGE = 3+++class DryViolationDetector:+ name = "dry_violation"+ category = "duplication"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ if not ctx.clones:+ return []+ dup_pct = ctx.duplication_pct or 0.0+ if dup_pct < _MIN_DUP_PCT:+ return []++ # Pick the worst clone — biggest active region wins over a+ # slightly larger dormant clone.+ worst = max(+ ctx.clones,+ key=lambda p: (p.co_change_count, max(p.a_line_count, p.b_line_count)),+ )+ worst_lines = max(worst.a_line_count, worst.b_line_count)+ if worst_lines < _MIN_CLONE_LINES:+ return []++ partner = worst.file_b if worst.file_a == ctx.file_path else worst.file_a++ active = worst.co_change_count >= _ACTIVE_CO_CHANGE+ if active and dup_pct >= 25.0:+ severity = Severity.HIGH+ elif active or dup_pct >= 25.0:+ severity = Severity.MEDIUM+ else:+ severity = Severity.LOW++ return [+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=None,+ line_start=worst.a_start_line+ if worst.file_a == ctx.file_path+ else worst.b_start_line,+ line_end=worst.a_end_line if worst.file_a == ctx.file_path else worst.b_end_line,+ details={+ "duplication_pct": dup_pct,+ "clone_pair_count": len(ctx.clones),+ "worst_clone_lines": worst_lines,+ "worst_clone_partner": partner,+ "worst_clone_co_change": worst.co_change_count,+ },+ reason=(+ f"{dup_pct:.0f}% of file duplicated; worst clone shares "+ f"{worst_lines} lines with {partner}"+ + (f" (co-changed {worst.co_change_count}x)" if worst.co_change_count else "")+ ),+ )+ ]+++BIOMARKER = DryViolationDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py b/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.pynew file mode 100644index 000000000..551f7b3af--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/knowledge_loss.py@@ -0,0 +1,102 @@+"""Knowledge Loss — the primary owner is gone or barely present.++Bus-factor risk: the person who wrote most of this file no longer+contributes. When the primary owner of a hotspot is also the only deep+contributor (bus_factor 1) and we can't find them in the recent commit+window, the team has effectively lost the institutional knowledge for+this code.++Fires when:++- ``bus_factor`` ≤ 1 (the file has one true author)+- AND ``primary_owner_name`` differs from ``recent_owner_name`` OR the+ recent owner contributes < 20% of recent commits++Severity grades on whether the file is also a hotspot.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext++_BUS_FACTOR_THRESHOLD = 1+_RECENT_SHARE_THRESHOLD = 0.2+++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 _as_float(value: object, default: float = 0.0) -> float:+ try:+ return float(value or 0.0) # type: ignore[arg-type]+ except (TypeError, ValueError):+ return default+++def _is_hotspot(meta: dict) -> bool:+ if meta.get("is_hotspot"):+ return True+ return _as_int(meta.get("commit_count_90d")) >= 8+++class KnowledgeLossDetector:+ name = "knowledge_loss"+ category = "organizational"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ meta = ctx.git_meta or {}+ bus = _as_int(meta.get("bus_factor"))+ if bus > _BUS_FACTOR_THRESHOLD or bus == 0:+ # bus_factor 0 means git indexing was skipped or the file+ # has no contributor data — don't fire blind.+ return []++ primary = (meta.get("primary_owner_name") or "").strip()+ recent = (meta.get("recent_owner_name") or "").strip()+ if not primary:+ return []++ recent_share = _as_float(meta.get("recent_owner_commit_pct"))+ share = recent_share / 100.0 if recent_share > 1.0 else recent_share++ primary_gone = primary != recent and recent != ""+ recent_quiet = share < _RECENT_SHARE_THRESHOLD+ if not (primary_gone or recent_quiet):+ return []++ if _is_hotspot(meta):+ severity = Severity.HIGH+ elif primary_gone and recent_quiet:+ severity = Severity.MEDIUM+ else:+ severity = Severity.LOW++ return [+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=None,+ line_start=None,+ line_end=None,+ details={+ "bus_factor": bus,+ "primary_owner": primary,+ "recent_owner": recent or None,+ "recent_owner_share": round(share, 3),+ "is_hotspot": _is_hotspot(meta),+ },+ reason=(+ f"Primary owner {primary} no longer the recent owner"+ if primary_gone+ else f"Primary owner {primary} barely active (recent share {share:.0%})"+ ),+ )+ ]+++BIOMARKER = KnowledgeLossDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.pynew file mode 100644index 000000000..c92ea5425--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/large_method.py@@ -0,0 +1,52 @@+"""Large Method — function bodies that exceed a healthy line budget.++Fires on raw NLOC, independent of complexity. A 200-line function with+CCN 2 still hurts readability and tests; a 60-line function with CCN 12+is the `complex_method` case. Both can fire on the same function — the+scorer caps the size_and_complexity category so they don't double-count.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext+++class LargeMethodDetector:+ name = "large_method"+ category = "size_and_complexity"++ _NLOC_THRESHOLD = 60++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ out: list[BiomarkerResult] = []+ for fn in ctx.function_metrics.values():+ if fn.nloc < self._NLOC_THRESHOLD:+ continue+ severity = (+ Severity.CRITICAL+ if fn.nloc >= 200+ else Severity.HIGH+ if fn.nloc >= 120+ else Severity.MEDIUM+ if fn.nloc >= 90+ else Severity.LOW+ )+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={+ "nloc": fn.nloc,+ "ccn": fn.ccn,+ },+ reason=f"{fn.name} is {fn.nloc} lines long",+ )+ )+ return out+++BIOMARKER = LargeMethodDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.pynew file mode 100644index 000000000..59e0cab17--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_complexity.py@@ -0,0 +1,50 @@+"""Nested Complexity — deeply indented control flow.++Flags functions whose maximum nesting depth exceeds 4. Inspired by+CodeScene's "Deep, Nested Complexity" — strongly correlated with+defect density in their published studies.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext+++class NestedComplexityDetector:+ name = "nested_complexity"+ category = "structural_complexity"++ _NESTING_THRESHOLD = 4++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ out: list[BiomarkerResult] = []+ for fn in ctx.function_metrics.values():+ if fn.max_nesting < self._NESTING_THRESHOLD:+ continue+ severity = (+ Severity.CRITICAL+ if fn.max_nesting >= 7+ else Severity.HIGH+ if fn.max_nesting >= 5+ else Severity.MEDIUM+ )+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={+ "max_nesting": fn.max_nesting,+ "ccn": fn.ccn,+ "cognitive": fn.cognitive,+ },+ reason=f"{fn.name} nests {fn.max_nesting} levels deep",+ )+ )+ return out+++BIOMARKER = NestedComplexityDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.pynew file mode 100644index 000000000..62e23e60d--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py@@ -0,0 +1,59 @@+"""Primitive Obsession — long parameter lists of unstructured values.++A proxy for the OOP smell: when a function signature carries 5+ raw+parameters, the call sites usually pass strings/ints/bools that *should*+be a value object. We don't try to inspect parameter *types* (too much+language-specific machinery) — the raw count is a strong-enough+correlation in practice and matches CodeScene's "Primitive Obsession"+default.++Constructors (`__init__`, `init`) get a small grace allowance — wide+dataclass-style ctors are an idiomatic pattern, not a smell.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext++_PARAM_THRESHOLD = 5+_CTOR_GRACE = 2 # constructors get +2 free params before the smell trips+_CTOR_NAMES = frozenset({"__init__", "init", "constructor"})+++class PrimitiveObsessionDetector:+ name = "primitive_obsession"+ category = "size_and_complexity"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ out: list[BiomarkerResult] = []+ for fn in ctx.function_metrics.values():+ threshold = _PARAM_THRESHOLD+ if fn.name in _CTOR_NAMES:+ threshold += _CTOR_GRACE+ if fn.param_count < threshold:+ continue+ severity = (+ Severity.HIGH+ if fn.param_count >= threshold + 4+ else Severity.MEDIUM+ if fn.param_count >= threshold + 2+ else Severity.LOW+ )+ out.append(+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=fn.name,+ line_start=fn.start_line,+ line_end=fn.end_line,+ details={+ "param_count": fn.param_count,+ },+ reason=f"{fn.name} takes {fn.param_count} parameters",+ )+ )+ return out+++BIOMARKER = PrimitiveObsessionDetector()diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.pynew file mode 100644index 000000000..547ac6a89--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py@@ -0,0 +1,67 @@+"""Biomarker registry.++Explicit factory list rather than module auto-discovery — keeps the+registration order deterministic and lets tests inject custom detectors+via ``registered_biomarkers(extra=...)``.++Adding a biomarker: append to ``_DETECTOR_FACTORIES``.+"""++from __future__ import annotations++from collections.abc import Sequence++from .base import Biomarker, BiomarkerResult, FileContext+from .brain_method import BrainMethodDetector+from .bumpy_road import BumpyRoadDetector+from .complex_method import ComplexMethodDetector+from .coverage_gap import CoverageGapDetector+from .developer_congestion import DeveloperCongestionDetector+from .dry_violation import DryViolationDetector+from .knowledge_loss import KnowledgeLossDetector+from .large_method import LargeMethodDetector+from .nested_complexity import NestedComplexityDetector+from .primitive_obsession import PrimitiveObsessionDetector+from .untested_hotspot import UntestedHotspotDetector++_DETECTOR_FACTORIES: list[type[Biomarker]] = [+ BrainMethodDetector, # type: ignore[list-item]+ NestedComplexityDetector, # type: ignore[list-item]+ ComplexMethodDetector, # type: ignore[list-item]+ BumpyRoadDetector, # type: ignore[list-item]+ LargeMethodDetector, # type: ignore[list-item]+ PrimitiveObsessionDetector, # type: ignore[list-item]+ DryViolationDetector, # type: ignore[list-item]+ UntestedHotspotDetector, # type: ignore[list-item]+ CoverageGapDetector, # type: ignore[list-item]+ DeveloperCongestionDetector, # type: ignore[list-item]+ KnowledgeLossDetector, # type: ignore[list-item]+]+++def registered_biomarkers(+ *, disabled: Sequence[str] = (), extra: Sequence[Biomarker] = ()+) -> list[Biomarker]:+ """Return the active biomarker list.++ Phase 3 will read ``disabled`` from ``.repowise/health-rules.json``.+ """+ instances: list[Biomarker] = [cls() for cls in _DETECTOR_FACTORIES] # type: ignore[call-arg]+ instances.extend(extra)+ return [b for b in instances if b.name not in disabled]+++def detect_all(+ ctx: FileContext,+ *,+ disabled: Sequence[str] = (),+ extra: Sequence[Biomarker] = (),+) -> list[BiomarkerResult]:+ """Run every registered biomarker against *ctx* and return the union."""+ findings: list[BiomarkerResult] = []+ for b in registered_biomarkers(disabled=disabled, extra=extra):+ try:+ findings.extend(b.detect(ctx))+ except Exception:+ continue+ return findingsdiff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/untested_hotspot.py b/packages/core/src/repowise/core/analysis/health/biomarkers/untested_hotspot.pynew file mode 100644index 000000000..fe6450daa--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/untested_hotspot.py@@ -0,0 +1,103 @@+"""Untested Hotspot — a churning, central file with no test coverage.++Fires when a file is **all three** of:++- a *hotspot* (``git_meta['is_hotspot']`` true OR commit_count_90d ≥ 8)+- under-tested (``line_coverage_pct`` < 40 when coverage is available,+ OR no paired test file when coverage isn't)+- centrally depended on (``dependents_count`` ≥ 4 OR temporal_hotspot+ in the top decile)++Severity grades on how bad the coverage is and how many dependents the+file has.++When no coverage report has been ingested the biomarker still fires for+hotspots without a paired test file — this is the conservative fallback+mode and matches the Phase 1 "has_test_file" heuristic.+"""++from __future__ import annotations++from ..models import Severity+from .base import BiomarkerResult, FileContext++_COVERAGE_LOW = 40.0+_COVERAGE_VERY_LOW = 15.0+_DEPENDENTS_THRESHOLD = 4+_COMMITS_90D_THRESHOLD = 8+++def _is_hotspot(ctx: FileContext) -> bool:+ meta = ctx.git_meta or {}+ if bool(meta.get("is_hotspot")):+ return True+ try:+ if int(meta.get("commit_count_90d", 0) or 0) >= _COMMITS_90D_THRESHOLD:+ return True+ except (TypeError, ValueError):+ pass+ try:+ if float(meta.get("temporal_hotspot_score", 0.0) or 0.0) >= 0.8:+ return True+ except (TypeError, ValueError):+ pass+ return False+++class UntestedHotspotDetector:+ name = "untested_hotspot"+ category = "test_coverage"++ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:+ if not _is_hotspot(ctx):+ return []+ if ctx.dependents_count < _DEPENDENTS_THRESHOLD:+ # Not enough leverage to flag — would over-trigger on+ # leaf files churned by one author.+ return []++ cov = ctx.line_coverage_pct+ if cov is None:+ # Fallback: no coverage data. Flag only when there's also+ # no paired test file, to avoid noise.+ if ctx.has_test_file:+ return []+ cov_for_severity = 0.0+ reason = (+ f"Hotspot with no paired test file and no coverage data — "+ f"{ctx.dependents_count} dependents"+ )+ else:+ if cov >= _COVERAGE_LOW:+ return []+ cov_for_severity = cov+ reason = f"Hotspot with {cov:.0f}% line coverage and {ctx.dependents_count} dependents"++ if cov_for_severity <= _COVERAGE_VERY_LOW and ctx.dependents_count >= 10:+ severity = Severity.CRITICAL+ elif cov_for_severity <= _COVERAGE_VERY_LOW or ctx.dependents_count >= 10:+ severity = Severity.HIGH+ else:+ severity = Severity.MEDIUM++ meta = ctx.git_meta or {}+ return [+ BiomarkerResult(+ biomarker_type=self.name,+ severity=severity,+ function_name=None,+ line_start=None,+ line_end=None,+ details={+ "line_coverage_pct": cov,+ "branch_coverage_pct": ctx.branch_coverage_pct,+ "dependents_count": ctx.dependents_count,+ "commit_count_90d": meta.get("commit_count_90d"),+ "has_test_file": ctx.has_test_file,+ },+ reason=reason,+ )+ ]+++BIOMARKER = UntestedHotspotDetector()diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.mdnew file mode 100644index 000000000..00be07ca1--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md@@ -0,0 +1,56 @@+# complexity/++Tree-sitter AST walker. Single AST pass per file computes:++- **CCN** — McCabe cyclomatic complexity. Counts branching constructs+ (`if`, `for`, `while`, `case`, `catch`) plus boolean operators+ (`&&`, `||`).+- **max nesting depth** — deepest nested control-flow block per function.+- **cognitive complexity** — SonarSource-style weighted nesting cost+ (each level adds an incrementing penalty, plus +1 for each break in+ control flow).+- **bumps** — count of branches at the same nesting depth as their+ sibling branches. Feeds `bumpy_road`.+- **param_count** — formal parameter count. Feeds `primitive_obsession`.+- **nloc** — non-comment lines of code per function.++## Performance characteristics++One parser instance per process (lazy-loaded via the ingestion registry).+Single pass per file — no AST re-traversal. The walker re-parses the file+because `ParsedFile` does not carry the tree-sitter `Node` across the+ingestion boundary; cost is acceptable (≲ 1 ms for typical files).++## Public API++```python+from repowise.core.analysis.health.complexity import (+ FunctionComplexity, walk_file_complexity,+)++results: list[FunctionComplexity] = walk_file_complexity(+ abs_path, language, source_bytes+)+```++## Inputs++`abs_path` (filesystem path), `language` (e.g. `"python"`), `source_bytes`+(file content as bytes — `tree_sitter` requires bytes).++## Outputs++One `FunctionComplexity` per function/method symbol detected. Caller maps+back to ingestion `Symbol` objects by overlapping line ranges.++## Extension points++`languages.py` maps each language's tree-sitter **control-flow node-type+names** (e.g. `if_statement`, `for_expression`, `try_block`) to the+walker's abstract `BRANCH` / `LOOP` / `TRY` / `BOOLEAN_OP` categories.++Add a new language → one new `LanguageNodeMap` dict (~20 lines). No+`.scm` file edits required — those are owned by the ingestion parser.++Phase 1 ships mappings for Python, TypeScript, JavaScript, Go, Java, Rust.+Phase 5 adds C, C++, C#, Kotlin, Ruby, PHP, Swift, Scala.diff --git a/packages/core/src/repowise/core/analysis/health/complexity/__init__.py b/packages/core/src/repowise/core/analysis/health/complexity/__init__.pynew file mode 100644index 000000000..3e2bcb527--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/__init__.py@@ -0,0 +1,7 @@+"""Tree-sitter complexity walker — see ``README.md``."""++from __future__ import annotations++from .walker import FunctionComplexity, walk_file_complexity++__all__ = ["FunctionComplexity", "walk_file_complexity"]diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pynew file mode 100644index 000000000..d7d996d51--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -0,0 +1,153 @@+"""Per-language tree-sitter control-flow node-type maps.++The walker is language-agnostic — language differences live entirely in+the dicts below. Each entry maps that language's tree-sitter node-type+names to the walker's abstract categories:++- ``BRANCH`` — adds 1 to CCN, 1 to nesting, 1 + nesting to cognitive.+- ``LOOP`` — same as BRANCH.+- ``TRY`` — adds 1 to CCN per ``catch``/``except`` clause; the+ ``TRY`` block itself only opens a nesting level.+- ``CATCH`` — adds 1 to CCN, 1 to nesting; the catch clause.+- ``SWITCH`` — case dispatch root; counts each case as a branch.+- ``CASE`` — adds 1 to CCN, 1 to nesting per case.+- ``BOOLEAN_OP``— adds 1 to CCN for each ``&&``/``||`` operator. Does+ not affect nesting.+- ``FUNCTION`` — function/method definition (walker entry point).+- ``LAMBDA`` — anonymous function. Treated as ``FUNCTION`` for+ nested-walker recursion but does not emit its own+ ``FunctionComplexity``.++Phase 1 covers Python, TypeScript, JavaScript, Go, Java, Rust.+Phase 5 will add C, C++, C#, Kotlin, Ruby, PHP, Swift, Scala.+"""++from __future__ import annotations++from dataclasses import dataclass+++@dataclass(frozen=True)+class LanguageNodeMap:+ function_kinds: frozenset[str]+ lambda_kinds: frozenset[str]+ branch_kinds: frozenset[str]+ loop_kinds: frozenset[str]+ try_kinds: frozenset[str]+ catch_kinds: frozenset[str]+ switch_kinds: frozenset[str]+ case_kinds: frozenset[str]+ boolean_operator_kinds: frozenset[str]+ # Some languages place && / || as the *type* of the binary operator+ # node itself (Rust: ``&&`` is the operator text inside a+ # ``binary_expression``). For those, ``boolean_operator_kinds`` is+ # empty and we sniff operator text via this set of node types whose+ # text content equals ``&&`` or ``||``.+ boolean_operator_text_kinds: frozenset[str] = frozenset()+++_PY = LanguageNodeMap(+ function_kinds=frozenset({"function_definition", "async_function_definition"}),+ lambda_kinds=frozenset({"lambda"}),+ branch_kinds=frozenset({"if_statement", "elif_clause", "conditional_expression"}),+ loop_kinds=frozenset({"for_statement", "while_statement"}),+ try_kinds=frozenset({"try_statement"}),+ catch_kinds=frozenset({"except_clause"}),+ switch_kinds=frozenset({"match_statement"}),+ case_kinds=frozenset({"case_clause"}),+ boolean_operator_kinds=frozenset({"boolean_operator"}),+)++_TS = LanguageNodeMap(+ function_kinds=frozenset(+ {+ "function_declaration",+ "method_definition",+ "function_expression",+ "generator_function_declaration",+ "generator_function",+ }+ ),+ lambda_kinds=frozenset({"arrow_function"}),+ branch_kinds=frozenset({"if_statement", "ternary_expression"}),+ loop_kinds=frozenset(+ {+ "for_statement",+ "for_in_statement",+ "for_of_statement",+ "while_statement",+ "do_statement",+ }+ ),+ try_kinds=frozenset({"try_statement"}),+ catch_kinds=frozenset({"catch_clause"}),+ switch_kinds=frozenset({"switch_statement"}),+ case_kinds=frozenset({"switch_case"}),+ boolean_operator_kinds=frozenset(),+ boolean_operator_text_kinds=frozenset({"binary_expression"}),+)++_JS = _TS # identical control-flow nodes; tree-sitter-javascript shares shape.++_GO = LanguageNodeMap(+ function_kinds=frozenset({"function_declaration", "method_declaration"}),+ lambda_kinds=frozenset({"func_literal"}),+ branch_kinds=frozenset({"if_statement"}),+ loop_kinds=frozenset({"for_statement"}),+ try_kinds=frozenset(),+ catch_kinds=frozenset(),+ switch_kinds=frozenset({"expression_switch_statement", "type_switch_statement"}),+ case_kinds=frozenset({"expression_case", "type_case", "default_case"}),+ boolean_operator_kinds=frozenset(),+ boolean_operator_text_kinds=frozenset({"binary_expression"}),+)++_JAVA = LanguageNodeMap(+ function_kinds=frozenset({"method_declaration", "constructor_declaration"}),+ lambda_kinds=frozenset({"lambda_expression"}),+ branch_kinds=frozenset({"if_statement", "ternary_expression"}),+ loop_kinds=frozenset(+ {+ "for_statement",+ "enhanced_for_statement",+ "while_statement",+ "do_statement",+ }+ ),+ try_kinds=frozenset({"try_statement", "try_with_resources_statement"}),+ catch_kinds=frozenset({"catch_clause"}),+ switch_kinds=frozenset({"switch_expression", "switch_statement"}),+ case_kinds=frozenset({"switch_block_statement_group", "switch_rule"}),+ boolean_operator_kinds=frozenset(),+ boolean_operator_text_kinds=frozenset({"binary_expression"}),+)++_RUST = LanguageNodeMap(+ function_kinds=frozenset({"function_item"}),+ lambda_kinds=frozenset({"closure_expression"}),+ branch_kinds=frozenset({"if_expression", "if_let_expression"}),+ loop_kinds=frozenset({"for_expression", "while_expression", "loop_expression"}),+ try_kinds=frozenset(),+ catch_kinds=frozenset(),+ switch_kinds=frozenset({"match_expression"}),+ case_kinds=frozenset({"match_arm"}),+ boolean_operator_kinds=frozenset(),+ boolean_operator_text_kinds=frozenset({"binary_expression"}),+)+++LANGUAGE_MAPS: dict[str, LanguageNodeMap] = {+ "python": _PY,+ "typescript": _TS,+ "tsx": _TS,+ "javascript": _JS,+ "jsx": _JS,+ "go": _GO,+ "java": _JAVA,+ "rust": _RUST,+}+++def get_language_map(language: str) -> LanguageNodeMap | None:+ """Return the node-type map for *language* or None when unsupported."""+ return LANGUAGE_MAPS.get(language)diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pynew file mode 100644index 000000000..c7ed69621--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -0,0 +1,280 @@+"""Tree-sitter walker → CCN, max nesting, cognitive complexity.++One AST pass per file. For each function/method discovered at the top+level (or nested directly inside a class body / impl block) we recurse+through its body, accumulating:++- **CCN** — McCabe cyclomatic complexity. Start at 1; +1 per branch /+ loop / case / catch / boolean operator.+- **max_nesting** — deepest stack of nesting-contributing nodes within+ the function body.+- **cognitive** — SonarSource-style weighted score: each nesting node+ adds ``1 + current_depth`` (so deeper nesting hurts more); boolean+ operators add a flat +1; jumps (``return``/``break``/``continue``)+ do not contribute (kept simple in v1).++Anonymous functions (lambdas, arrow functions, closures) recurse for+their containing function's metrics — they do not produce their own+``FunctionComplexity`` row.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING++import structlog++from .languages import LanguageNodeMap, get_language_map++if TYPE_CHECKING:+ from tree_sitter import Node++log = structlog.get_logger(__name__)+++@dataclass+class FunctionComplexity:+ """Per-function metrics produced by the walker."""++ name: str+ start_line: int # 1-indexed+ end_line: int # 1-indexed+ ccn: int+ max_nesting: int+ cognitive: int+ nloc: int # non-blank lines inside the body+ # Number of top-level body sub-blocks whose internal nesting reached+ # ≥ 2 — used by ``bumpy_road``. A flat function has 0 bumps.+ bumps: int = 0+ # Number of declared parameters on the function signature — used by+ # ``primitive_obsession``. Counted via the tree-sitter ``parameters``+ # field; 0 when the language lacks an explicit list or extraction fails.+ param_count: int = 0+++def _find_name(node: Node) -> str:+ """Best-effort: return the text of the first identifier child."""+ # Search a couple of common field names first.+ for field_name in ("name", "identifier"):+ child = node.child_by_field_name(field_name)+ if child is not None and child.text is not None:+ return child.text.decode("utf-8", errors="replace")+ for child in node.children:+ if (+ child.type in ("identifier", "property_identifier", "field_identifier")+ and child.text is not None+ ):+ return child.text.decode("utf-8", errors="replace")+ return "<anonymous>"+++def _count_nloc(node: Node, source: bytes) -> int:+ """Return the count of non-blank lines spanned by *node*."""+ start = node.start_point[0]+ end = node.end_point[0]+ if end < start:+ return 0+ try:+ snippet = source[node.start_byte : node.end_byte].decode("utf-8", errors="replace")+ except Exception:+ return end - start + 1+ return sum(1 for line in snippet.splitlines() if line.strip())+++def _is_boolean_operator(node: Node, lmap: LanguageNodeMap) -> bool:+ """True if this node represents a logical ``&&`` / ``||`` operator."""+ if node.type in lmap.boolean_operator_kinds:+ return True+ if node.type in lmap.boolean_operator_text_kinds:+ # The operator child carries the literal token text.+ for child in node.children:+ if child.text is None:+ continue+ tok = child.text+ if tok in (b"&&", b"||", b"and", b"or"):+ return True+ return False+++def _walk_function_body(+ body_node: Node,+ lmap: LanguageNodeMap,+) -> tuple[int, int, int, int]:+ """Recursive AST walk. Returns (ccn, max_nesting, cognitive, bumps).++ Starts CCN at 1 (the entry path). Nested function bodies are+ skipped — they will (or already did) produce their own+ ``FunctionComplexity``.++ ``bumps`` counts how many *direct* children of the 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.+ """++ ccn = 1+ max_nesting = 0+ cognitive = 0+ bumps = 0++ def _recurse(node: Node, depth: int) -> None:+ nonlocal ccn, max_nesting, cognitive++ # Don't descend into nested function bodies — they're walked+ # separately at the top level. Lambdas / arrow functions DO+ # contribute to the enclosing function's complexity.+ if node.type in lmap.function_kinds:+ return++ nesting_increment = 0+ ccn_increment = 0++ if (+ node.type in lmap.branch_kinds+ or node.type in lmap.loop_kinds+ or node.type in lmap.case_kinds+ or node.type in lmap.catch_kinds+ ):+ ccn_increment = 1+ nesting_increment = 1+ elif node.type in lmap.try_kinds:+ # TRY opens a nesting level but does not branch on its own.+ nesting_increment = 1+ elif node.type in lmap.switch_kinds:+ # Switch opens nesting; each case contributes its own +1.+ nesting_increment = 1+ elif _is_boolean_operator(node, lmap):+ ccn_increment = 1++ ccn += ccn_increment+ new_depth = depth + nesting_increment+ if nesting_increment:+ # SonarSource cognitive: each nesting node adds (1 + depth).+ cognitive += 1 + depth+ elif ccn_increment:+ # Flat +1 for boolean operators (no nesting impact).+ cognitive += 1++ if new_depth > max_nesting:+ max_nesting = new_depth++ for child in node.children:+ _recurse(child, new_depth)++ for child in body_node.children:+ # Per-child peak depth: temporarily swap max_nesting out so we+ # can read just this child's contribution, then restore.+ outer_max = max_nesting+ max_nesting = 0+ _recurse(child, 0)+ child_peak = max_nesting+ max_nesting = max(outer_max, child_peak)+ if child_peak >= 2:+ bumps += 1++ return ccn, max_nesting, cognitive, bumps+++def _collect_function_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:+ """All function / method definition nodes in the file.++ Iterative pre-order traversal. We descend into class / module+ bodies but do **not** recurse below a function — nested defs are+ rare and treated as their own top-level entry. Lambda kinds are+ skipped (they're walked inline as part of their enclosing fn).+ """+ out: list[Node] = []+ stack: list[Node] = [root]+ while stack:+ node = stack.pop()+ if node.type in lmap.function_kinds:+ out.append(node)+ # Don't descend further — nested defs roll up into the+ # enclosing fn's complexity via _walk_function_body+ # (which skips nested function_kinds).+ continue+ for child in node.children:+ stack.append(child)+ return out+++def walk_file_complexity(+ abs_path: str,+ language: str,+ source: bytes,+) -> list[FunctionComplexity]:+ """Walk one file's AST. Returns one ``FunctionComplexity`` per fn.++ Returns an empty list when:+ - the language is unsupported (no entry in ``LANGUAGE_MAPS``)+ - the tree-sitter language package isn't installed+ - parsing fails+ """+ lmap = get_language_map(language)+ if lmap is None:+ return []++ try:+ from tree_sitter import Parser++ # Reuse the ingestion parser's language registry. Importing+ # lazily avoids pulling tree-sitter at module load time when+ # health is run from a context where it isn't installed.+ from repowise.core.ingestion.parser import _get_language+ except Exception as exc:+ log.debug("complexity_walker_import_failed", error=str(exc))+ return []++ grammar = _get_language(language)+ if grammar is None:+ return []++ try:+ parser = Parser(grammar)+ tree = parser.parse(source)+ except Exception as exc:+ log.debug("complexity_walker_parse_failed", path=abs_path, error=str(exc))+ return []++ 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)+ results.append(+ FunctionComplexity(+ name=_find_name(fn_node),+ start_line=fn_node.start_point[0] + 1,+ end_line=fn_node.end_point[0] + 1,+ ccn=ccn,+ max_nesting=max_nest,+ cognitive=cognitive,+ nloc=_count_nloc(body, source),+ bumps=bumps,+ param_count=_count_parameters(fn_node),+ )+ )+ return results+++def _count_parameters(fn_node: Node) -> int:+ """Best-effort parameter-list size for *fn_node*.++ Looks at tree-sitter ``parameters`` / ``parameter_list`` / ``parameters_list`` fields and counts non-punctuation+ children. Returns 0 when no parameter list is found.+ """+ params = fn_node.child_by_field_name("parameters")+ if params is None:+ for child in fn_node.children:+ if child.type in ("parameters", "parameter_list", "formal_parameters"):+ params = child+ break+ if params is None:+ return 0+ count = 0+ for child in params.children:+ if child.type in ("(", ")", ",", "self", "cls", ":", "*", "**"):+ continue+ if child.is_named:+ count += 1+ return countdiff --git a/packages/core/src/repowise/core/analysis/health/config.py b/packages/core/src/repowise/core/analysis/health/config.pynew file mode 100644index 000000000..5f9fc0462--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/config.py@@ -0,0 +1,117 @@+"""HealthConfig — loads `.repowise/health-rules.json` per-file overrides.++The file is **user-authored** (it isn't generated by Repowise). It lets+teams silence specific biomarkers on legacy paths, or globally tune the+detector list. Decisions deliberately kept narrow in v1:++- Repo-wide ``disabled_biomarkers``: detectors that never fire.+- Per-path ``rules``: a list of glob → ``disabled_biomarkers`` entries.+ First matching glob wins. Patterns use ``fnmatch`` semantics over the+ repo-relative POSIX path (``src/legacy/**.py``).++Schema (validated on load, errors logged but never raised):++ {+ "disabled_biomarkers": ["dry_violation"],+ "rules": [+ {"path": "src/legacy/**", "disabled_biomarkers": ["complex_method"]},+ {"path": "**/*.generated.ts", "disabled_biomarkers": ["large_method"]}+ ]+ }+"""++from __future__ import annotations++import fnmatch+import json+from dataclasses import dataclass, field+from pathlib import Path++import structlog++from repowise.core.repo_config import get_repowise_dir++log = structlog.get_logger(__name__)+++HEALTH_RULES_FILENAME = "health-rules.json"+++@dataclass+class HealthRule:+ """One per-path override entry."""++ path_glob: str+ disabled_biomarkers: list[str] = field(default_factory=list)+++@dataclass+class HealthConfig:+ """Loaded health configuration. Empty when no rules file exists."""++ disabled_biomarkers: list[str] = field(default_factory=list)+ rules: list[HealthRule] = field(default_factory=list)++ @classmethod+ def load(cls, repo_path: Path | str) -> HealthConfig:+ """Load `.repowise/health-rules.json` for *repo_path*.++ Missing file → empty config. Malformed file → empty config + a+ single warning log. Never raises.+ """+ rules_path = get_repowise_dir(repo_path) / HEALTH_RULES_FILENAME+ if not rules_path.exists():+ return cls()+ try:+ raw = json.loads(rules_path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ log.warning("health_rules_load_failed", path=str(rules_path), error=str(exc))+ return cls()+ return cls.from_dict(raw)++ @classmethod+ def from_dict(cls, raw: object) -> HealthConfig:+ if not isinstance(raw, dict):+ return cls()+ disabled: list[str] = [+ str(b) for b in (raw.get("disabled_biomarkers") or []) if isinstance(b, str)+ ]+ rules: list[HealthRule] = []+ for entry in raw.get("rules") or []:+ if not isinstance(entry, dict):+ continue+ glob = entry.get("path") or entry.get("path_glob")+ if not isinstance(glob, str) or not glob:+ continue+ disabled_for = [+ str(b) for b in (entry.get("disabled_biomarkers") or []) if isinstance(b, str)+ ]+ rules.append(HealthRule(path_glob=glob, disabled_biomarkers=disabled_for))+ return cls(disabled_biomarkers=disabled, rules=rules)++ def per_file_disabled(self, file_paths: list[str]) -> dict[str, set[str]]:+ """Materialize per-path overrides.++ Walks *file_paths*, matches each path against this config's+ rules, and returns a `{path: {biomarker, ...}}` map suitable+ for the ``HealthAnalyzer.analyze`` ``config`` dict.+ """+ if not self.rules:+ return {}+ out: dict[str, set[str]] = {}+ for path in file_paths:+ norm = path.replace("\\", "/")+ disabled: set[str] = set()+ for rule in self.rules:+ if fnmatch.fnmatchcase(norm, rule.path_glob):+ disabled.update(rule.disabled_biomarkers)+ if disabled:+ out[path] = disabled+ return out++ def to_analyzer_config(self, file_paths: list[str]) -> dict[str, object]:+ """Return the dict accepted by ``HealthAnalyzer.analyze``."""+ return {+ "disabled_biomarkers": list(self.disabled_biomarkers),+ "per_file_disabled": self.per_file_disabled(file_paths),+ }diff --git a/packages/core/src/repowise/core/analysis/health/coverage/README.md b/packages/core/src/repowise/core/analysis/health/coverage/README.mdnew file mode 100644index 000000000..03c63077b--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/README.md@@ -0,0 +1,48 @@+# coverage/++Coverage report ingestion + test-file heuristics for the code-health layer.++## Public API++```python+from repowise.core.analysis.health.coverage import (+ CoverageReport, FileCoverage,+ parse, detect_format,+ is_test_file, paired_test_file,+)+```++- `parse(text, format=None)` → `CoverageReport`. Auto-detects format+ when `format` is ``None``; pass an explicit ``"lcov" | "cobertura" |+ "clover"`` to override.+- `parse_lcov(text)`, `parse_cobertura(text)`, `parse_clover(text)` —+ format-specific entry points (used by tests / programmatic callers).+- `detect_format(text)` — returns the sniffed format or ``None``.+- `is_test_file(path, source=None)` — path + optional content heuristic.+- `paired_test_file(path, all_paths)` — find the conventional test+ partner for a source path.++## Inputs++- A raw coverage report (the contents of `coverage.lcov`, a Cobertura+ `coverage.xml`, or a Clover `clover.xml`).+- For the test-file heuristic: a POSIX-style relative path and optionally+ the file contents (used to detect framework imports for files that+ don't follow naming conventions).++## Outputs++- `CoverageReport(source_format, files: list[FileCoverage], commit_sha)`.+- Each `FileCoverage` carries `file_path` (POSIX-normalized), line/branch+ coverage percentages, the explicit covered-line set, and the total+ coverable line count.++## Extension points++- Add a parser: drop a new file (e.g. `jacoco.py`), return a+ `CoverageReport`, and route to it from `detector.parse`.+- Tune the test-file heuristic: edit the module-level `_TEST_*` tuples in+ `detector.py`. Keep the rule deterministic (no globs that require+ recursion).+- The parsers depend only on the Python stdlib — no XML schema, no+ external XML library.diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.pynew file mode 100644index 000000000..137b08532--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py@@ -0,0 +1,21 @@+"""Coverage parsers + test-file heuristics for the health layer."""++from __future__ import annotations++from .clover import parse_clover+from .cobertura import parse_cobertura+from .detector import detect_format, is_test_file, paired_test_file, parse+from .lcov import parse_lcov+from .model import CoverageReport, FileCoverage++__all__ = [+ "CoverageReport",+ "FileCoverage",+ "detect_format",+ "is_test_file",+ "paired_test_file",+ "parse",+ "parse_clover",+ "parse_cobertura",+ "parse_lcov",+]diff --git a/packages/core/src/repowise/core/analysis/health/coverage/clover.py b/packages/core/src/repowise/core/analysis/health/coverage/clover.pynew file mode 100644index 000000000..2c79583f9--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/clover.py@@ -0,0 +1,94 @@+"""Clover XML parser (stdlib ``xml.etree``).++Clover layout (abbreviated):++ <coverage generated="...">+ <project>+ <package name="...">+ <file path="/abs/or/rel/path/file.ts">+ <metrics statements="10" coveredstatements="7"+ conditionals="4" coveredconditionals="2" ... />+ <line num="1" count="3" type="stmt"/>+ <line num="2" count="0" type="stmt"/>+ <line num="3" count="2" type="cond" truecount="1" falsecount="1"/>+ </file>+ </package>+ </project>+ </coverage>++We trust the per-line elements over the ``<metrics>`` summary so coverage+percentages match what gets highlighted in the dashboard. Branch coverage+is derived from ``type="cond"`` lines (truecount + falsecount).+"""++from __future__ import annotations++from pathlib import Path+from xml.etree import ElementTree as ET++from .model import CoverageReport, FileCoverage+++def parse_clover(text: str) -> CoverageReport:+ try:+ root = ET.fromstring(text)+ except ET.ParseError:+ return CoverageReport(source_format="clover", files=[])++ files: list[FileCoverage] = []+ for file_el in root.iter("file"):+ path = file_el.get("path") or file_el.get("name") or ""+ if not path:+ continue+ norm = Path(path).as_posix()++ covered: set[int] = set()+ total: set[int] = set()+ branches_found = 0+ branches_hit = 0+ has_branches = False++ for line in file_el.iter("line"):+ try:+ line_no = int(line.get("num", "0"))+ except ValueError:+ continue+ if line_no <= 0:+ continue+ ltype = line.get("type", "stmt")+ try:+ count = int(line.get("count", "0"))+ except ValueError:+ count = 0+ total.add(line_no)+ if count > 0:+ covered.add(line_no)+ if ltype == "cond":+ has_branches = True+ try:+ tc = int(line.get("truecount", "0"))+ fc = int(line.get("falsecount", "0"))+ except ValueError:+ tc, fc = 0, 0+ branches_found += 2+ branches_hit += (1 if tc > 0 else 0) + (1 if fc > 0 else 0)++ total_n = len(total)+ line_pct = (len(covered) / total_n * 100.0) if total_n else 0.0+ branch_pct: float | None+ if has_branches and branches_found:+ branch_pct = branches_hit / branches_found * 100.0+ else:+ branch_pct = None++ files.append(+ FileCoverage(+ file_path=norm,+ line_coverage_pct=round(line_pct, 2),+ branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,+ covered_lines=sorted(covered),+ total_coverable_lines=total_n,+ )+ )++ return CoverageReport(source_format="clover", files=files)diff --git a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.pynew file mode 100644index 000000000..08e3d1f79--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py@@ -0,0 +1,111 @@+"""Cobertura XML parser (stdlib ``xml.etree`` only).++Cobertura layout (abbreviated):++ <coverage line-rate="0.83" branch-rate="0.5" ...>+ <sources><source>/abs/path</source></sources>+ <packages>+ <package name="pkg" line-rate="..." branch-rate="...">+ <classes>+ <class filename="pkg/file.py" line-rate="..." branch-rate="...">+ <lines>+ <line number="3" hits="2" branch="false"/>+ <line number="5" hits="0" branch="true"+ condition-coverage="50% (1/2)"/>+ </lines>+ </class>+ </classes>+ </package>+ </packages>+ </coverage>++We aggregate per ``filename`` because some Cobertura producers (notably+``coverage.py``'s XML output) emit multiple ``<class>`` rows for the+same file (one per top-level class).+"""++from __future__ import annotations++import re+from pathlib import Path+from xml.etree import ElementTree as ET++from .model import CoverageReport, FileCoverage++_CONDITION_RE = re.compile(r"\((\d+)\s*/\s*(\d+)\)")+++def parse_cobertura(text: str) -> CoverageReport:+ try:+ root = ET.fromstring(text)+ except ET.ParseError:+ return CoverageReport(source_format="cobertura", files=[])++ # Aggregate by filename.+ per_file: dict[str, dict[str, object]] = {}++ for cls in root.iter("class"):+ filename = cls.get("filename") or ""+ if not filename:+ continue+ norm = Path(filename).as_posix()+ bucket = per_file.setdefault(+ norm,+ {+ "covered_lines": set(),+ "total_lines": set(),+ "branches_found": 0,+ "branches_hit": 0,+ "has_branches": False,+ },+ )+ for line in cls.iter("line"):+ try:+ line_no = int(line.get("number", "0"))+ hits = int(line.get("hits", "0"))+ except ValueError:+ continue+ if line_no <= 0:+ continue+ assert isinstance(bucket["total_lines"], set)+ assert isinstance(bucket["covered_lines"], set)+ bucket["total_lines"].add(line_no)+ if hits > 0:+ bucket["covered_lines"].add(line_no)++ if line.get("branch") == "true":+ bucket["has_branches"] = True+ cc = line.get("condition-coverage", "")+ m = _CONDITION_RE.search(cc)+ if m:+ hit, total = int(m.group(1)), int(m.group(2))+ bucket["branches_found"] = int(bucket["branches_found"]) + total+ bucket["branches_hit"] = int(bucket["branches_hit"]) + hit+ else:+ bucket["branches_found"] = int(bucket["branches_found"]) + 2+ bucket["branches_hit"] = int(bucket["branches_hit"]) + (2 if hits > 0 else 0)++ files: list[FileCoverage] = []+ for path, bucket in per_file.items():+ covered = bucket["covered_lines"]+ total_set = bucket["total_lines"]+ assert isinstance(covered, set)+ assert isinstance(total_set, set)+ total = len(total_set)+ hit = len(covered)+ line_pct = (hit / total * 100.0) if total else 0.0+ branch_pct: float | None+ bf = int(bucket["branches_found"])+ bh = int(bucket["branches_hit"])+ branch_pct = bh / bf * 100.0 if bucket["has_branches"] and bf else None+ files.append(+ FileCoverage(+ file_path=path,+ line_coverage_pct=round(line_pct, 2),+ branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,+ covered_lines=sorted(covered),+ total_coverable_lines=total,+ )+ )++ return CoverageReport(source_format="cobertura", files=files)diff --git a/packages/core/src/repowise/core/analysis/health/coverage/detector.py b/packages/core/src/repowise/core/analysis/health/coverage/detector.pynew file mode 100644index 000000000..824c3b577--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/detector.py@@ -0,0 +1,150 @@+"""Format auto-detection + test-file heuristic.++The CLI accepts ``--coverage <path>`` without a format flag in the common+case. We sniff the content to decide which parser to dispatch to.++Sniffing rules (cheap, deterministic):++- LCOV files start with ``TN:`` or ``SF:`` on the first non-blank line+ (and the format is line-oriented).+- Cobertura XML has a ``<coverage`` root and a ``<packages>`` child (or+ is referenced by the ``coverage`` DTD).+- Clover XML has a ``<coverage generated=`` root with a ``<project>``+ child.++If detection is ambiguous, callers can pass ``--coverage-format`` to+override.+"""++from __future__ import annotations++import re+from pathlib import Path++from .clover import parse_clover+from .cobertura import parse_cobertura+from .lcov import parse_lcov+from .model import CoverageReport++# Test-file globs / suffixes — checked against POSIX-normalized paths.+_TEST_PATH_FRAGMENTS = (+ "/test/",+ "/tests/",+ "/__tests__/",+ "/spec/",+ "/specs/",+)+_TEST_FILE_SUFFIXES = (+ "_test.py",+ "_test.go",+ ".test.ts",+ ".test.tsx",+ ".test.js",+ ".test.jsx",+ ".spec.ts",+ ".spec.tsx",+ ".spec.js",+ ".spec.jsx",+ "_spec.rb",+ "Test.java",+ "Tests.java",+ "Spec.scala",+)+_TEST_FILE_PREFIXES = ("test_",)++# Test framework import patterns — used when the path heuristic is+# inconclusive. Detected via cheap substring scan (no tree-sitter pass).+_FRAMEWORK_IMPORTS = (+ "import pytest",+ "from pytest",+ "import unittest",+ "from unittest",+ "from django.test",+ "import jest",+ 'from "vitest"',+ "from 'vitest'",+ 'from "@testing-library/',+ "from '@jest/",+ "testing.T", # Go testing pkg signature+)+++def detect_format(text: str) -> str | None:+ """Return ``"lcov" | "cobertura" | "clover"`` or ``None``."""+ sample = text.lstrip()[:2048]+ if not sample:+ return None+ if sample.startswith(("TN:", "SF:")) or _LCOV_LINE_RE.match(sample):+ return "lcov"+ if sample.startswith("<?xml") or sample.startswith("<"):+ if "<coverage" in sample and "<project" in sample[:4096]:+ return "clover"+ if "<coverage" in sample and ("<packages" in sample[:4096] or "line-rate" in sample[:4096]):+ return "cobertura"+ return None+++_LCOV_LINE_RE = re.compile(r"^(TN|SF|DA|BRDA|LF|LH|BRF|BRH):", re.MULTILINE)+++def parse(text: str, *, format: str | None = None) -> CoverageReport:+ """Parse coverage text, auto-detecting format when not provided."""+ fmt = format or detect_format(text)+ if fmt == "lcov":+ return parse_lcov(text)+ if fmt == "cobertura":+ return parse_cobertura(text)+ if fmt == "clover":+ return parse_clover(text)+ return CoverageReport(source_format="unknown")+++def is_test_file(rel_path: str, source: str | None = None) -> bool:+ """Heuristic — does *rel_path* look like a test file?++ *source* is an optional file body; when supplied we additionally+ check for test-framework imports for files whose paths don't match+ obvious conventions.+ """+ p = rel_path.replace("\\", "/")+ lower = p.lower()+ base = p.rsplit("/", 1)[-1]+ if any(frag in lower for frag in _TEST_PATH_FRAGMENTS):+ return True+ if any(lower.startswith(frag.lstrip("/")) for frag in _TEST_PATH_FRAGMENTS):+ return True+ if base.startswith(_TEST_FILE_PREFIXES):+ return True+ if any(base.endswith(sfx) for sfx in _TEST_FILE_SUFFIXES):+ return True+ if source:+ head = source[:4096]+ if any(token in head for token in _FRAMEWORK_IMPORTS):+ return True+ return False+++def paired_test_file(rel_path: str, all_paths: set[str]) -> str | None:+ """Return a candidate test-file path for *rel_path*, or ``None``."""+ p = Path(rel_path.replace("\\", "/"))+ stem = p.stem+ candidates = {+ f"test_{stem}.py",+ f"{stem}_test.py",+ f"{stem}.test.ts",+ f"{stem}.test.tsx",+ f"{stem}.test.js",+ f"{stem}.test.jsx",+ f"{stem}.spec.ts",+ f"{stem}.spec.js",+ f"{stem}_test.go",+ f"{stem}_spec.rb",+ f"{stem}Test.java",+ f"{stem}Tests.java",+ }+ for other in all_paths:+ norm = other.replace("\\", "/")+ base = norm.rsplit("/", 1)[-1]+ if base in candidates:+ return other+ return Nonediff --git a/packages/core/src/repowise/core/analysis/health/coverage/lcov.py b/packages/core/src/repowise/core/analysis/health/coverage/lcov.pynew file mode 100644index 000000000..eaf8116c9--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/lcov.py@@ -0,0 +1,125 @@+"""LCOV ``.info`` parser.++LCOV is a flat, line-oriented format:++ TN:<test name>+ SF:<source file>+ DA:<line>,<hits>[,<checksum>]+ BRDA:<line>,<block>,<branch>,<taken>+ LF:<lines found>+ LH:<lines hit>+ BRF:<branches found>+ BRH:<branches hit>+ end_of_record++We do not depend on LF/LH/BRF/BRH being present — they are derived from+DA/BRDA when missing so partial reports still parse cleanly.+"""++from __future__ import annotations++import contextlib+from pathlib import Path++from .model import CoverageReport, FileCoverage+++def parse_lcov(text: str) -> CoverageReport:+ files: list[FileCoverage] = []++ current_path: str | None = None+ covered_lines: set[int] = set()+ total_lines: set[int] = set()+ branches_found = 0+ branches_hit = 0+ has_branches = False+ explicit_lf: int | None = None+ explicit_lh: int | None = None++ def flush() -> None:+ nonlocal current_path, covered_lines, total_lines+ nonlocal branches_found, branches_hit, has_branches, explicit_lf, explicit_lh+ if current_path is None:+ return+ total = explicit_lf if explicit_lf is not None else len(total_lines)+ hit = explicit_lh if explicit_lh is not None else len(covered_lines)+ line_pct = (hit / total * 100.0) if total else 0.0+ branch_pct: float | None+ if has_branches and branches_found:+ branch_pct = branches_hit / branches_found * 100.0+ else:+ branch_pct = None+ files.append(+ FileCoverage(+ file_path=current_path,+ line_coverage_pct=round(line_pct, 2),+ branch_coverage_pct=round(branch_pct, 2) if branch_pct is not None else None,+ covered_lines=sorted(covered_lines),+ total_coverable_lines=total,+ )+ )+ current_path = None+ covered_lines = set()+ total_lines = set()+ branches_found = 0+ branches_hit = 0+ has_branches = False+ explicit_lf = None+ explicit_lh = None++ for raw_line in text.splitlines():+ line = raw_line.strip()+ if not line:+ continue+ if line == "end_of_record":+ flush()+ continue+ if ":" not in line:+ continue+ tag, _, rest = line.partition(":")+ if tag == "SF":+ current_path = _normalize_path(rest)+ elif tag == "DA":+ parts = rest.split(",")+ if len(parts) >= 2:+ try:+ line_no = int(parts[0])+ hits = int(parts[1])+ except ValueError:+ continue+ total_lines.add(line_no)+ if hits > 0:+ covered_lines.add(line_no)+ elif tag == "BRDA":+ parts = rest.split(",")+ if len(parts) == 4:+ has_branches = True+ branches_found += 1+ if parts[3] not in ("-", "0"):+ branches_hit += 1+ elif tag == "LF":+ with contextlib.suppress(ValueError):+ explicit_lf = int(rest)+ elif tag == "LH":+ with contextlib.suppress(ValueError):+ explicit_lh = int(rest)+ elif tag == "BRF":+ try:+ branches_found = max(branches_found, int(rest))+ has_branches = True+ except ValueError:+ pass+ elif tag == "BRH":+ try:+ branches_hit = max(branches_hit, int(rest))+ has_branches = True+ except ValueError:+ pass++ # Some reports omit the final end_of_record.+ flush()+ return CoverageReport(source_format="lcov", files=files)+++def _normalize_path(path: str) -> str:+ return Path(path.strip()).as_posix()diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.pynew file mode 100644index 000000000..eb7da4cc0--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py@@ -0,0 +1,37 @@+"""Dataclasses produced by coverage parsers.++Parsers return a :class:`CoverageReport` containing one+:class:`FileCoverage` per source file referenced in the report. The+engine and persistence layer consume these dataclasses; the ORM+``CoverageFile`` row is written from them in+``persistence.crud.save_coverage_files``.+"""++from __future__ import annotations++from dataclasses import dataclass, field+++@dataclass+class FileCoverage:+ """Per-file coverage extracted from a single report."""++ file_path: str+ line_coverage_pct: float+ branch_coverage_pct: float | None+ covered_lines: list[int] = field(default_factory=list)+ total_coverable_lines: int = 0+++@dataclass+class CoverageReport:+ """Whole-report bundle returned by every parser.++ ``source_format`` is one of ``lcov`` / ``cobertura`` / ``clover``.+ ``commit_sha`` is best-effort: parsers leave it ``None``; the CLI+ fills it in from ``git rev-parse HEAD`` when available.+ """++ source_format: str+ files: list[FileCoverage] = field(default_factory=list)+ commit_sha: str | None = Nonediff --git a/packages/core/src/repowise/core/analysis/health/duplication/README.md b/packages/core/src/repowise/core/analysis/health/duplication/README.mdnew file mode 100644index 000000000..38733afa7--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/duplication/README.md@@ -0,0 +1,72 @@+# duplication/++Native Rabin-Karp clone detection over tree-sitter tokens. No `jscpd`,+no Node.js, no extra Python runtime deps.++## Public API++```python+from repowise.core.analysis.health.duplication import detect_clones++report = detect_clones(parsed_files, git_meta_map)+# report.pairs : list[ClonePair]+# report.duplication_pct : dict[file_path -> percent duplicated]+# report.pairs_by_file : dict[file_path -> list[ClonePair]]+```++## Pipeline++1. **Tokenize** — `tokenizer.tokenize_file(language, source_bytes)` walks+ the tree-sitter AST, drops whitespace and comments, and yields a+ normalized token stream (identifiers collapse to `ID`, literals to+ `LIT`, operators/keywords pass through). Renaming a variable does+ not break a match; restructuring control flow does.+2. **Hash windows** — `rabin_karp.rolling_hashes` produces a 64-bit+ polynomial hash for every sliding window of `window_tokens` (default+ 50). Constants are pinned so hashes are reproducible across+ processes.+3. **Bucket + verify** — equal hashes inside a bucket are candidate+ matches. `detector._tokens_equal` walks the two token kind sequences+ to rule out hash collisions before emitting a `ClonePair`.+4. **Merge adjacent windows** — adjacent or overlapping clone windows+ between the same `(file_a, file_b)` collapse into one contiguous+ region.+5. **Co-change correlation** — for each surviving pair we look up+ `git_meta_map[file_a]['co_change_partners_json']` (and the reverse+ direction). The max count attaches to `ClonePair.co_change_count`+ so the `dry_violation` biomarker can rank *active* duplicates+ higher than dormant ones — the Phase-3 hard constraint.++## Inputs++- `parsed_files`: `list[ParsedFile]` from the ingestion phase. The+ detector reads source from each file's `abs_path`.+- `git_meta_map`: optional per-file metadata. When present, the+ detector parses `co_change_partners_json` to weight clone pairs.++## Outputs++- `DuplicationReport`:+ - `pairs`: every verified, merged clone region.+ - `duplication_pct`: per-file duplicate-line percentage, capped at+ 100% to handle overlapping clones.+ - `pairs_by_file`: lookup map used by the `dry_violation` biomarker.++## Extension points++- **Tunables** — `DEFAULT_WINDOW_TOKENS` (sensitivity) and+ `DEFAULT_MIN_LINES` (output filter) are arguments to `detect_clones`.+ Future `HealthConfig` knobs can be threaded through here without+ touching biomarker code.+- **Tokenizer** — to support a new language with different identifier+ / literal node types, extend the kind sets in `tokenizer.py`. The+ rolling hash is language-agnostic.++## Performance notes++- Hashing is `O(total_tokens)`; bucket walk is `O(sum_of_collisions)`.+ For repos with low duplication the bucket walk is near-linear.+- The tokenizer re-parses every file independently of the complexity+ walker because the ingestion `ParsedFile` does not retain a+ tree-sitter `Tree`. Tradeoff is documented; switching to a shared+ parse cache is a Phase 5 optimization.diff --git a/packages/core/src/repowise/core/analysis/health/duplication/__init__.py b/packages/core/src/repowise/core/analysis/health/duplication/__init__.pynew file mode 100644index 000000000..6621d5d8f--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/duplication/__init__.py@@ -0,0 +1,21 @@+"""Native Rabin-Karp duplication detection over tree-sitter tokens."""++from .detector import (+ DEFAULT_MIN_LINES,+ DEFAULT_WINDOW_TOKENS,+ ClonePair,+ DuplicationReport,+ detect_clones,+)+from .tokenizer import Token, tokenize_file, tokenize_tree++__all__ = [+ "DEFAULT_MIN_LINES",+ "DEFAULT_WINDOW_TOKENS",+ "ClonePair",+ "DuplicationReport",+ "Token",+ "detect_clones",+ "tokenize_file",+ "tokenize_tree",+]diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.pynew file mode 100644index 000000000..aedbf1e44--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py@@ -0,0 +1,305 @@+"""Native clone-pair detection over tree-sitter tokens.++Pipeline:++1. Tokenize every parsed file with the duplication ``tokenizer``.+2. Rolling-hash each token stream into fixed-size windows.+3. Bucket windows by hash; for each multi-window bucket, verify token+ equality (hash collision-proof) and emit a ``ClonePair``.+4. Merge adjacent windows in the same (file_a, file_b) pair into a+ single contiguous clone region.+5. Weight active vs dormant clone pairs using+ ``git_meta_map[path]['co_change_partners_json']`` — when two files+ that contain a clone also frequently change together, the clone is+ *actively maintained duplication* and should be rated higher.++The Phase-3 plan calls for co-change correlation from day one so that+the ``dry_violation`` biomarker can rank clones by activity, not just+size.+"""++from __future__ import annotations++import json+from collections import defaultdict+from collections.abc import Iterable+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import structlog++from .rabin_karp import WindowHash, index_by_hash, rolling_hashes+from .tokenizer import Token, tokenize_file++log = structlog.get_logger(__name__)+++# Tunables — locked in for v1, may move to ``HealthConfig`` later.+DEFAULT_WINDOW_TOKENS = 50+DEFAULT_MIN_LINES = 6+++@dataclass+class ClonePair:+ """One verified clone region between two files (or two regions in+ the same file)."""++ file_a: str+ file_b: str+ a_start_line: int+ a_end_line: int+ b_start_line: int+ b_end_line: int+ token_count: int+ co_change_count: int = 0 # 0 when files don't share co-change history++ @property+ def is_intra_file(self) -> bool:+ return self.file_a == self.file_b++ @property+ def a_line_count(self) -> int:+ return self.a_end_line - self.a_start_line + 1++ @property+ def b_line_count(self) -> int:+ return self.b_end_line - self.b_start_line + 1+++@dataclass+class DuplicationReport:+ pairs: list[ClonePair] = field(default_factory=list)+ # Per-file duplication percent: ratio of duplicated lines vs file's+ # total non-blank line count. Used by the dry_violation biomarker+ # and surfaced on HealthFileMetric.duplication_pct.+ duplication_pct: dict[str, float] = field(default_factory=dict)+ # Per-file pair index for fast lookups by biomarker.+ pairs_by_file: dict[str, list[ClonePair]] = field(default_factory=dict)+++def _read_source(abs_path: str) -> bytes | None:+ try:+ return Path(abs_path).read_bytes()+ except OSError:+ return None+++def _parse_co_change_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 _co_change_score(+ file_a: str,+ file_b: str,+ git_meta_map: dict[str, dict[str, Any]],+) -> int:+ """Bidirectional max — co-change matrices are stored per file, but+ the same pair shows up from both sides, sometimes with slightly+ different counts depending on the window. Take the max."""+ a_meta = git_meta_map.get(file_a, {}) or {}+ b_meta = git_meta_map.get(file_b, {}) or {}+ from_a = _parse_co_change_partners(a_meta).get(file_b, 0)+ from_b = _parse_co_change_partners(b_meta).get(file_a, 0)+ return max(from_a, from_b)+++def _tokens_equal(+ a_tokens: list[Token],+ b_tokens: list[Token],+ a_start: int,+ b_start: int,+ window: int,+) -> bool:+ """Verify hash-collision by comparing token ``kind`` sequences."""+ if a_start + window > len(a_tokens) or b_start + window > len(b_tokens):+ return False+ for offset in range(window):+ if a_tokens[a_start + offset].kind != b_tokens[b_start + offset].kind:+ return False+ return True+++def _merge_adjacent_pairs(raw: list[ClonePair]) -> list[ClonePair]:+ """Merge overlapping/adjacent clone windows in the same (a, b) pair.++ Two pairs are merged when:+ - they share file_a and file_b+ - their A-side and B-side ranges both touch or overlap (within 1+ line of slack for token-level windows that don't perfectly+ align with statement boundaries).+ """+ if not raw:+ return []++ def _key(p: ClonePair) -> tuple[str, str, int, int]:+ return (p.file_a, p.file_b, p.a_start_line, p.b_start_line)++ raw = sorted(raw, key=_key)+ merged: list[ClonePair] = []+ for p in raw:+ if not merged:+ merged.append(p)+ continue+ last = merged[-1]+ same_pair = last.file_a == p.file_a and last.file_b == p.file_b+ a_touch = p.a_start_line <= last.a_end_line + 1+ b_touch = p.b_start_line <= last.b_end_line + 1+ if same_pair and a_touch and b_touch:+ merged[-1] = ClonePair(+ file_a=last.file_a,+ file_b=last.file_b,+ a_start_line=last.a_start_line,+ a_end_line=max(last.a_end_line, p.a_end_line),+ b_start_line=last.b_start_line,+ b_end_line=max(last.b_end_line, p.b_end_line),+ token_count=last.token_count + p.token_count,+ co_change_count=max(last.co_change_count, p.co_change_count),+ )+ else:+ merged.append(p)+ return merged+++def detect_clones(+ parsed_files: Iterable[Any],+ git_meta_map: dict[str, dict[str, Any]] | None = None,+ *,+ window_tokens: int = DEFAULT_WINDOW_TOKENS,+ min_lines: int = DEFAULT_MIN_LINES,+) -> DuplicationReport:+ """Run the duplication pipeline over the supplied parsed files.++ The detector reads source bytes from ``ParsedFile.file_info.abs_path``+ and tokenizes each file once. Skipping files where tokenization+ returns an empty list (unsupported language, parse failure) keeps+ the rest of the pipeline running.+ """+ meta_map = git_meta_map or {}+ per_file_tokens: dict[str, list[Token]] = {}+ per_file_nloc: dict[str, int] = {}+ all_windows: list[WindowHash] = []++ for pf in parsed_files:+ path = pf.file_info.path+ language = pf.file_info.language+ source = _read_source(pf.file_info.abs_path)+ if source is None:+ continue+ toks = tokenize_file(language, source)+ if len(toks) < window_tokens:+ continue+ per_file_tokens[path] = toks+ per_file_nloc[path] = _nloc(source)+ all_windows.extend(rolling_hashes(path, toks, window_tokens))++ if not all_windows:+ return DuplicationReport()++ bucket = index_by_hash(all_windows)+ raw_pairs: list[ClonePair] = []+ seen: set[tuple[str, int, str, int]] = set()++ for windows in bucket.values():+ if len(windows) < 2:+ continue+ # All-pairs within a bucket — buckets are small in practice.+ for i in range(len(windows)):+ for j in range(i + 1, len(windows)):+ a, b = windows[i], windows[j]+ # Canonicalize so (file_a, file_b) is stable.+ if (a.file_path, a.start_index) > (b.file_path, b.start_index):+ a, b = b, a+ key = (a.file_path, a.start_index, b.file_path, b.start_index)+ if key in seen:+ continue+ seen.add(key)+ if not _tokens_equal(+ per_file_tokens[a.file_path],+ per_file_tokens[b.file_path],+ a.start_index,+ b.start_index,+ window_tokens,+ ):+ continue+ raw_pairs.append(+ ClonePair(+ file_a=a.file_path,+ file_b=b.file_path,+ a_start_line=a.start_line,+ a_end_line=a.end_line,+ b_start_line=b.start_line,+ b_end_line=b.end_line,+ token_count=window_tokens,+ )+ )++ merged = _merge_adjacent_pairs(raw_pairs)+ final: list[ClonePair] = []+ for p in merged:+ if min(p.a_line_count, p.b_line_count) < min_lines:+ continue+ score = _co_change_score(p.file_a, p.file_b, meta_map)+ if score:+ p = ClonePair(+ file_a=p.file_a,+ file_b=p.file_b,+ a_start_line=p.a_start_line,+ a_end_line=p.a_end_line,+ b_start_line=p.b_start_line,+ b_end_line=p.b_end_line,+ token_count=p.token_count,+ co_change_count=score,+ )+ final.append(p)++ pairs_by_file: dict[str, list[ClonePair]] = defaultdict(list)+ dup_lines: dict[str, int] = defaultdict(int)+ for p in final:+ pairs_by_file[p.file_a].append(p)+ dup_lines[p.file_a] += p.a_line_count+ if not p.is_intra_file:+ pairs_by_file[p.file_b].append(p)+ dup_lines[p.file_b] += p.b_line_count++ duplication_pct: dict[str, float] = {}+ for path, dup in dup_lines.items():+ nloc = per_file_nloc.get(path, 0)+ if nloc <= 0:+ continue+ # Cap at 100% — overlapping clones can otherwise double-count+ # the same physical lines.+ duplication_pct[path] = round(min(100.0, 100.0 * dup / nloc), 2)++ return DuplicationReport(+ pairs=final,+ duplication_pct=duplication_pct,+ pairs_by_file=dict(pairs_by_file),+ )+++def _nloc(source: bytes) -> int:+ try:+ text = source.decode("utf-8", errors="replace")+ except Exception:+ return 0+ return sum(1 for line in text.splitlines() if line.strip())diff --git a/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py b/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.pynew file mode 100644index 000000000..846169f71--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/duplication/rabin_karp.py@@ -0,0 +1,129 @@+"""Rabin-Karp rolling hash over normalized token windows.++We compute a 64-bit rolling polynomial hash over fixed-size windows of+token ``kind`` strings. Equal hashes flag a candidate clone; the+verifier in ``detector.py`` then confirms by comparing the actual token+sequences (so we don't trust a hash collision alone).++The math:++ H(w_0..w_{n-1}) = sum_{i=0..n-1} h(w_i) * B^(n-1-i) (mod M)++Roll forward by one position:++ H' = (H - h(w_0)*B^(n-1)) * B + h(w_{n-1+1}) (mod M)++We use Python ints (arbitrary precision) but pin both base and modulus+to 64-bit values so the math is portable and hash collisions are well+distributed. Modulus is a large prime under 2**63.+"""++from __future__ import annotations++from collections.abc import Iterable, Iterator+from dataclasses import dataclass++from .tokenizer import Token++# Pinned constants — changing these invalidates any persisted hashes.+_BASE = 1_000_003+_MODULUS = 9_223_372_036_854_775_783 # largest prime < 2**63+++def _token_hash(tok_kind: str) -> int:+ """Stable per-kind hash. Plain ``hash()`` is randomized by Python's+ hash seed — we need determinism across processes."""+ h = 1469598103934665603+ for ch in tok_kind.encode("utf-8"):+ h ^= ch+ h = (h * 1099511628211) % _MODULUS+ return h+++@dataclass(frozen=True)+class WindowHash:+ """One rolling-hash window with origin file + line span."""++ file_path: str+ hash_value: int+ start_index: int # token index of the window's first token+ start_line: int+ end_line: int+++def rolling_hashes(+ file_path: str,+ tokens: list[Token],+ window: int,+) -> list[WindowHash]:+ """Compute rolling hashes for every window of length *window*.++ Returns an empty list when the file has fewer tokens than the+ window size — callers filter clone candidates by minimum size+ upstream so the empty-result case is well-defined.+ """+ n = len(tokens)+ if n < window or window <= 0:+ return []++ base_pow = pow(_BASE, window - 1, _MODULUS)+ kind_hashes = [_token_hash(t.kind) for t in tokens]++ h = 0+ for i in range(window):+ h = (h * _BASE + kind_hashes[i]) % _MODULUS++ out: list[WindowHash] = []+ out.append(+ WindowHash(+ file_path=file_path,+ hash_value=h,+ start_index=0,+ start_line=tokens[0].start_line,+ end_line=tokens[window - 1].end_line,+ )+ )+ for i in range(1, n - window + 1):+ h = ((h - kind_hashes[i - 1] * base_pow) * _BASE + kind_hashes[i + window - 1]) % _MODULUS+ # Python's % already yields a non-negative result for a positive+ # modulus, but we keep the guard for clarity.+ if h < 0:+ h += _MODULUS+ out.append(+ WindowHash(+ file_path=file_path,+ hash_value=h,+ start_index=i,+ start_line=tokens[i].start_line,+ end_line=tokens[i + window - 1].end_line,+ )+ )+ return out+++def index_by_hash(hashes: Iterable[WindowHash]) -> dict[int, list[WindowHash]]:+ """Group windows by their hash so collisions are easy to walk."""+ bucket: dict[int, list[WindowHash]] = {}+ for w in hashes:+ bucket.setdefault(w.hash_value, []).append(w)+ return bucket+++def iter_collisions(+ bucket: dict[int, list[WindowHash]],+) -> Iterator[tuple[WindowHash, WindowHash]]:+ """Yield (a, b) pairs of windows that share a hash, a different file+ or non-overlapping windows in the same file. The verifier in+ ``detector.py`` then confirms by token-by-token compare."""+ for windows in bucket.values():+ if len(windows) < 2:+ continue+ for i in range(len(windows)):+ for j in range(i + 1, len(windows)):+ a, b = windows[i], windows[j]+ if a.file_path == b.file_path and abs(a.start_index - b.start_index) < (+ b.end_line - b.start_line + 1+ ):+ # Skip overlapping windows in the same file.+ continue+ yield a, bdiff --git a/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.pynew file mode 100644index 000000000..fb7ba70e5--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/duplication/tokenizer.py@@ -0,0 +1,164 @@+"""Tree-sitter token extraction for duplication detection.++The tokenizer walks a parsed tree and yields a stream of ``Token``s, one+per leaf node, excluding:++- whitespace-only nodes+- comment nodes (``comment``, ``line_comment``, ``block_comment``,+ ``doc_comment``)+- syntax-error and missing nodes++Two normalization knobs control how aggressive matching is:++- **identifiers** are normalized to a single placeholder ``ID`` so that+ ``foo`` and ``bar`` collide. This is the v1 default — it catches+ semantically-equivalent clones with renamed variables.+- **literals** (numbers, strings) are normalized to ``LIT`` for the same+ reason; string content is rarely the meaningful signal in a clone.++Operators and keywords pass through as their literal token text so we+preserve structure.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from tree_sitter import Node+++_COMMENT_KINDS = frozenset(+ {+ "comment",+ "line_comment",+ "block_comment",+ "doc_comment",+ "documentation_comment",+ "shebang",+ }+)++_IDENTIFIER_KINDS = frozenset(+ {+ "identifier",+ "property_identifier",+ "field_identifier",+ "shorthand_property_identifier",+ "type_identifier",+ "scoped_identifier",+ }+)++_LITERAL_KINDS = frozenset(+ {+ "string",+ "string_literal",+ "string_fragment",+ "raw_string_literal",+ "interpreted_string_literal",+ "integer",+ "float",+ "number",+ "integer_literal",+ "float_literal",+ "decimal_integer_literal",+ "decimal_floating_point_literal",+ "true",+ "false",+ "null",+ "nil",+ "None",+ "boolean",+ }+)+++@dataclass(frozen=True)+class Token:+ """One AST token with the source location of its origin node."""++ kind: str # normalized token category or literal text+ start_line: int # 1-indexed+ end_line: int # 1-indexed+ start_byte: int+ end_byte: int+++def _is_skippable(node: Node) -> bool:+ if node.type in _COMMENT_KINDS:+ return True+ # Tree-sitter exposes ERROR / MISSING for parse errors - drop them+ # so a single broken file can't pollute the hash stream.+ return bool(getattr(node, "has_error", False) and node.child_count == 0)+++def tokenize_tree(root: Node, source: bytes) -> list[Token]:+ """Walk *root* and return the flattened token list.++ Iterative DFS — uses a stack rather than recursion so very deep+ files don't blow the recursion limit.+ """+ out: list[Token] = []+ stack: list[Node] = [root]+ while stack:+ node = stack.pop()+ if _is_skippable(node):+ continue+ if node.child_count == 0:+ tok = _tokenize_leaf(node, source)+ if tok is not None:+ out.append(tok)+ continue+ # Push in reverse so we visit in source order on the next pop.+ for child in reversed(node.children):+ stack.append(child)+ return out+++def _tokenize_leaf(node: Node, source: bytes) -> Token | None:+ if node.type in _IDENTIFIER_KINDS:+ kind = "ID"+ elif node.type in _LITERAL_KINDS:+ kind = "LIT"+ else:+ # Use the raw token text for operators / keywords / punctuation.+ text = source[node.start_byte : node.end_byte]+ if not text.strip():+ return None+ try:+ kind = text.decode("utf-8", errors="replace")+ except Exception:+ return None+ return Token(+ kind=kind,+ start_line=node.start_point[0] + 1,+ end_line=node.end_point[0] + 1,+ start_byte=node.start_byte,+ end_byte=node.end_byte,+ )+++def tokenize_file(language: str, source: bytes) -> list[Token]:+ """Parse *source* and return its normalized token stream.++ Returns an empty list when the language is unsupported or parsing+ fails — callers treat that as "no clone candidates from this file".+ """+ try:+ from tree_sitter import Parser++ from repowise.core.ingestion.parser import _get_language+ except Exception:+ return []++ grammar = _get_language(language)+ if grammar is None:+ return []+ try:+ parser = Parser(grammar)+ tree = parser.parse(source)+ except Exception:+ return []+ return tokenize_tree(tree.root_node, source)diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pynew file mode 100644index 000000000..edd4f7665--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -0,0 +1,412 @@+"""HealthAnalyzer — thin orchestrator over walker → biomarkers → scorer.++Run sequence per file:++ 1. Open the source bytes from ``ParsedFile.file_info.abs_path``.+ 2. Walk the AST with ``complexity.walk_file_complexity`` → list of+ ``FunctionComplexity``.+ 3. Build a ``FileContext`` (function metrics, git meta, dependents+ count, NLOC, test-file flag).+ 4. Run all registered biomarkers via ``biomarkers.detect_all``.+ 5. Score the file, attach per-finding impacts.+ 6. Side effect: write ``max(ccn)`` into each Symbol's+ ``complexity_estimate`` so downstream consumers benefit.++Repo-level KPIs are computed from the final per-file metrics.+"""++from __future__ import annotations++import asyncio+import os+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++import structlog++from .biomarkers import FileContext, detect_all+from .complexity import FunctionComplexity, walk_file_complexity+from .coverage import is_test_file as _coverage_is_test_file+from .duplication import DuplicationReport, detect_clones+from .models import HealthFileMetricData, HealthFindingData, HealthReport+from .scoring import attach_impacts, compute_kpis, score_file++log = structlog.get_logger(__name__)+++def _is_test_file(rel_path: str) -> bool:+ p = rel_path.lower()+ return (+ "/test/" in p+ or "/tests/" in p+ or "/__tests__/" in p+ or p.startswith("test_")+ or p.endswith("_test.py")+ or p.endswith(".test.ts")+ or p.endswith(".test.tsx")+ or p.endswith(".test.js")+ or p.endswith(".spec.ts")+ or p.endswith(".spec.js")+ or p.endswith("_test.go")+ )+++def _fallback_module(rel_path: str) -> str | None:+ """Top-level directory as a stand-in module label when no community map.++ Returns ``None`` for root-level files so the rollup endpoint doesn't+ create a phantom "" bucket.+ """+ norm = rel_path.replace("\\", "/")+ if "/" not in norm:+ return None+ head = norm.split("/", 1)[0]+ return head or None+++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*?++ Cheap and conservative — looks for common test-file naming+ conventions paired with the same basename.+ """+ p = Path(rel_path)+ stem = p.stem+ candidates = {+ f"test_{stem}.py",+ f"{stem}_test.py",+ f"{stem}.test.ts",+ f"{stem}.test.tsx",+ f"{stem}.test.js",+ f"{stem}.spec.ts",+ f"{stem}.spec.js",+ f"{stem}_test.go",+ }+ return any(+ any(other.endswith("/" + c) or other == c for c in candidates) for other in all_paths+ )+++class HealthAnalyzer:+ """Pure-Python health analyzer. No LLM, no network."""++ def __init__(+ self,+ graph: Any, # networkx.DiGraph+ git_meta_map: dict[str, dict] | None = None,+ parsed_files: list[Any] | None = None,+ coverage_map: dict[str, dict[str, Any]] | None = None,+ module_map: dict[str, str] | None = None,+ ) -> None:+ self.graph = graph+ self.git_meta_map = git_meta_map or {}+ self.parsed_files = list(parsed_files or [])+ # Per-file coverage keyed by repo-relative POSIX path. Each value+ # is ``{line_coverage_pct, branch_coverage_pct, covered_lines,+ # total_coverable_lines}``. ``None``-equivalent files are simply+ # absent from the map.+ self.coverage_map = coverage_map or {}+ # Per-file module label keyed by repo-relative POSIX path.+ # Populated from graph community labels by the orchestrator. When+ # missing, the engine falls back to the top-level directory so+ # module rollups still group sensibly on small repos that didn't+ # produce community labels.+ self.module_map = module_map or {}++ def analyze(+ self,+ config: dict | None = None,+ *,+ on_step: Any | None = None,+ changed_files: set[str] | list[str] | None = None,+ ) -> HealthReport:+ """Analyze the configured parsed files.++ Pass *changed_files* (repo-relative POSIX paths) for incremental+ runs from ``repowise update`` — the engine still needs the full+ parsed-file set to build duplication context (clones cross+ files), but only files in *changed_files* contribute findings /+ metrics. The caller is responsible for upserting (not replacing)+ the result against the existing rows.+ """+ cfg = config or {}+ disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))+ per_file_disabled: dict[str, set[str]] = cfg.get("per_file_disabled", {}) or {}+ changed_set: set[str] | None = set(changed_files) if changed_files is not None else None++ # PageRank is optional — graph_builder.symbol_pagerank exists but+ # 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}++ # Duplication runs once, up-front, so each file biomarker can see+ # its clone list. Cheap when the repo is small; when disabled+ # explicitly we skip the work entirely. Even for incremental+ # runs we keep the full-repo scan: a changed file's clone partners+ # may be unchanged files we still need to compare against.+ if "dry_violation" in disabled:+ dup_report = DuplicationReport()+ else:+ try:+ dup_report = detect_clones(self.parsed_files, self.git_meta_map)+ except Exception as exc:+ log.debug("health_duplication_failed", error=str(exc))+ dup_report = DuplicationReport()++ findings: list[HealthFindingData] = []+ metrics: list[HealthFileMetricData] = []++ for pf in self.parsed_files:+ if changed_set is not None and pf.file_info.path not in changed_set:+ continue+ try:+ fc_list = self._walk(pf)+ except Exception as exc:+ log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))+ fc_list = []++ # Side-effect: bump Symbol.complexity_estimate when we can+ # match by enclosing line range. Symbols not matched keep+ # their default (1).+ self._populate_symbol_complexity(pf, fc_list)++ file_disabled = list(disabled)+ extra = per_file_disabled.get(pf.file_info.path)+ if extra:+ for name in extra:+ 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+ )+ metrics.append(file_metric)+ findings.extend(file_findings)++ if on_step:+ on_step(pf.file_info.path)++ # KPIs are repo-wide; on an incremental run they would be biased+ # by the changed-files subset. Skip them in that case — the+ # ``persist`` step recomputes KPIs from the merged DB rows.+ if changed_set is None:+ hotspot_paths = {p for p, meta in self.git_meta_map.items() if self._is_hotspot(meta)}+ kpis = compute_kpis(metrics, hotspot_paths)+ else:+ kpis = {}++ return HealthReport(+ repo_id="",+ analyzed_at=datetime.now(UTC),+ findings=findings,+ metrics=metrics,+ kpis=kpis,+ )++ async def analyze_async(+ self,+ config: dict | None = None,+ *,+ on_step: Any | None = None,+ changed_files: set[str] | list[str] | None = None,+ max_workers: int | None = None,+ ) -> HealthReport:+ """Parallel variant of :meth:`analyze` for large repos.++ Splits the per-file work across an ``asyncio.gather`` of+ ``asyncio.to_thread`` calls. Tree-sitter parsing releases the+ GIL, so this gives a real wall-clock win even on single-process+ Python — the 30s budget on a 3,000-file synthetic repo (plan §4+ P4.6) is met by this path.++ Duplication still runs once up-front (cross-file by nature), and+ the symbol-complexity write-back still runs on the main thread+ so ORM objects don't cross thread boundaries unexpectedly.+ """+ cfg = config or {}+ disabled: list[str] = list(cfg.get("disabled_biomarkers", ()))+ per_file_disabled: dict[str, set[str]] = cfg.get("per_file_disabled", {}) or {}+ 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}++ if "dry_violation" in disabled:+ dup_report = DuplicationReport()+ else:+ try:+ dup_report = await asyncio.to_thread(+ detect_clones, self.parsed_files, self.git_meta_map+ )+ except Exception as exc:+ log.debug("health_duplication_failed", error=str(exc))+ dup_report = DuplicationReport()++ target_files = [+ pf+ for pf in self.parsed_files+ if changed_set is None or pf.file_info.path in changed_set+ ]+ if not target_files:+ return HealthReport(+ repo_id="",+ analyzed_at=datetime.now(UTC),+ findings=[],+ metrics=[],+ kpis={},+ )++ # Pre-walk in worker threads so each task hands a list of+ # FunctionComplexity entries to the synchronous biomarker stage.+ # tree-sitter parsing releases the GIL → real parallelism here.+ workers = max(1, int(max_workers or os.cpu_count() or 4))+ semaphore = asyncio.Semaphore(workers)++ async def _one(pf: Any) -> tuple[Any, list[FunctionComplexity]]:+ async with semaphore:+ try:+ fc = await asyncio.to_thread(self._walk, pf)+ except Exception as exc:+ log.debug("health_walk_failed", path=pf.file_info.path, error=str(exc))+ fc = []+ return pf, fc++ walked = await asyncio.gather(*[_one(pf) for pf in target_files])++ findings: list[HealthFindingData] = []+ metrics: list[HealthFileMetricData] = []+ for pf, fc_list in walked:+ self._populate_symbol_complexity(pf, fc_list)+ file_disabled = list(disabled)+ extra = per_file_disabled.get(pf.file_info.path)+ if extra:+ for name in extra:+ 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+ )+ metrics.append(file_metric)+ findings.extend(file_findings)+ if on_step:+ on_step(pf.file_info.path)++ if changed_set is None:+ hotspot_paths = {p for p, meta in self.git_meta_map.items() if self._is_hotspot(meta)}+ kpis = compute_kpis(metrics, hotspot_paths)+ else:+ kpis = {}++ return HealthReport(+ repo_id="",+ analyzed_at=datetime.now(UTC),+ findings=findings,+ metrics=metrics,+ kpis=kpis,+ )++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ def _walk(self, pf: Any) -> list[FunctionComplexity]:+ path = pf.file_info.abs_path+ language = pf.file_info.language+ try:+ source = Path(path).read_bytes()+ except OSError:+ return []+ return walk_file_complexity(path, language, source)++ def _populate_symbol_complexity(self, pf: Any, fc_list: list[FunctionComplexity]) -> None:+ if not fc_list:+ return+ # Index function metrics by (start_line, end_line) for fast lookup.+ by_range = {(fc.start_line, fc.end_line): fc for fc in fc_list}+ by_name = {fc.name: fc for fc in fc_list}+ for sym in pf.symbols:+ fc = by_range.get((sym.start_line, sym.end_line)) or by_name.get(sym.name)+ if fc is None:+ continue+ # Cap at the ORM Integer; CCN beyond ~10k is implausible.+ sym.complexity_estimate = int(min(fc.ccn, 9999))++ def _evaluate_file(+ self,+ pf: Any,+ fc_list: list[FunctionComplexity],+ all_paths: set[str],+ *,+ disabled: list[str],+ dup_report: DuplicationReport,+ ) -> tuple[HealthFileMetricData, list[HealthFindingData]]:+ file_path = pf.file_info.path++ fn_metrics: dict[str, FunctionComplexity] = {fc.name: fc for fc in fc_list}+ max_ccn = max((fc.ccn for fc in fc_list), default=1)+ max_nesting = max((fc.max_nesting for fc in fc_list), default=0)+ nloc = sum(fc.nloc for fc in fc_list)++ dependents_count = 0+ if self.graph is not None and file_path in self.graph:+ try:+ dependents_count = int(self.graph.in_degree(file_path))+ except Exception:+ dependents_count = 0++ cov = self.coverage_map.get(file_path)+ if cov is None:+ cov = self.coverage_map.get(file_path.replace("\\", "/"))+ line_cov = cov.get("line_coverage_pct") if cov else None+ branch_cov = cov.get("branch_coverage_pct") if cov else None+ covered_lines: set[int] = set(cov.get("covered_lines") or ()) if cov else set()+ total_coverable_lines = int(cov.get("total_coverable_lines", 0)) if cov else 0++ clones = dup_report.pairs_by_file.get(file_path, [])+ dup_pct = dup_report.duplication_pct.get(file_path)++ module = self.module_map.get(file_path) or _fallback_module(file_path)++ ctx = FileContext(+ file_path=file_path,+ language=pf.file_info.language,+ nloc=nloc,+ has_test_file=_has_paired_test_file(file_path, all_paths)+ or _is_test_file(file_path)+ or _coverage_is_test_file(file_path),+ module=module,+ function_metrics=fn_metrics,+ git_meta=self.git_meta_map.get(file_path, {}) or {},+ dependents_count=dependents_count,+ pagerank_score=0.0,+ line_coverage_pct=line_cov,+ branch_coverage_pct=branch_cov,+ covered_lines=covered_lines,+ total_coverable_lines=total_coverable_lines,+ clones=list(clones),+ duplication_pct=dup_pct,+ )++ biomarker_results = detect_all(ctx, disabled=disabled)+ score, deductions = score_file(biomarker_results)+ findings = attach_impacts(biomarker_results, deductions)+ for f in findings:+ f.file_path = file_path++ metric = HealthFileMetricData(+ file_path=file_path,+ score=round(score, 2),+ max_ccn=max_ccn,+ max_nesting=max_nesting,+ nloc=nloc,+ has_test_file=ctx.has_test_file,+ module=module,+ line_coverage_pct=line_cov,+ branch_coverage_pct=branch_cov,+ duplication_pct=dup_pct,+ )+ return metric, findings++ def _is_hotspot(self, meta: dict | object) -> bool:+ if isinstance(meta, dict):+ return bool(meta.get("is_hotspot", False))+ return bool(getattr(meta, "is_hotspot", False))diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pynew file mode 100644index 000000000..f3e40ca94--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -0,0 +1,61 @@+"""Dataclasses returned by the health analyzer.++These are language-agnostic plain dataclasses, mirrored by SQLAlchemy ORM+counterparts in ``persistence/models.py`` (``HealthFinding``,+``HealthFileMetric``, ``HealthSnapshot``).+"""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime+from enum import StrEnum+from typing import Any+++class Severity(StrEnum):+ LOW = "low"+ MEDIUM = "medium"+ HIGH = "high"+ CRITICAL = "critical"+++@dataclass+class HealthFindingData:+ """One biomarker hit. Persisted as a ``HealthFinding`` row."""++ biomarker_type: str+ severity: Severity+ file_path: str+ function_name: str | None+ line_start: int | None+ line_end: int | None+ details: dict[str, Any]+ health_impact: float+ reason: str = ""+++@dataclass+class HealthFileMetricData:+ """Per-file aggregate. Persisted as a ``HealthFileMetric`` row."""++ file_path: str+ score: float+ max_ccn: int+ max_nesting: int+ nloc: int+ has_test_file: bool+ module: str | None = None+ duplication_pct: float | None = None+ line_coverage_pct: float | None = None+ branch_coverage_pct: float | None = None+++@dataclass+class HealthReport:+ repo_id: str+ analyzed_at: datetime+ findings: list[HealthFindingData] = field(default_factory=list)+ metrics: list[HealthFileMetricData] = field(default_factory=list)+ # Repo-level KPIs computed by ``scoring.compute_kpis``.+ kpis: dict[str, Any] = field(default_factory=dict)diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.pynew file mode 100644index 000000000..e0dcad4c1--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/scoring.py@@ -0,0 +1,160 @@+"""Per-file score aggregation + repo-level KPIs.++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:++ structural_complexity -> -3.5+ size_and_complexity -> -2.0+ duplication -> -1.5+ test_coverage -> -2.0+ organizational -> -1.0+"""++from __future__ import annotations++from collections.abc import Iterable++from .biomarkers.base import BiomarkerResult+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,+ "test_coverage": 2.0,+ "organizational": 1.0,+}++# Per-biomarker deduction by severity. The scorer caps the per-category+# total at the value in ``CATEGORY_CAPS``.+_SEVERITY_DEDUCTION: dict[Severity, float] = {+ Severity.LOW: 0.3,+ Severity.MEDIUM: 0.7,+ Severity.HIGH: 1.2,+ Severity.CRITICAL: 2.0,+}++# 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.+_BIOMARKER_CATEGORY: dict[str, str] = {+ "brain_method": "structural_complexity",+ "nested_complexity": "structural_complexity",+ "bumpy_road": "structural_complexity",+ "complex_method": "size_and_complexity",+ "large_method": "size_and_complexity",+ "primitive_obsession": "size_and_complexity",+ "dry_violation": "duplication",+ "untested_hotspot": "test_coverage",+ "coverage_gap": "test_coverage",+ "developer_congestion": "organizational",+ "knowledge_loss": "organizational",+}+++def severity_deduction(sev: Severity) -> float:+ return _SEVERITY_DEDUCTION.get(sev, 0.5)+++def biomarker_category(name: str) -> str:+ """Default to ``size_and_complexity`` for unknown biomarkers."""+ return _BIOMARKER_CATEGORY.get(name, "size_and_complexity")+++def score_file(results: Iterable[BiomarkerResult]) -> tuple[float, list[float]]:+ """Aggregate biomarker hits → final score in [1.0, 10.0].++ Returns ``(score, per_result_deductions)`` where the deductions list+ is parallel to *results* and represents each finding's contribution+ AFTER category capping. Use it to populate+ ``HealthFindingData.health_impact`` so the UI can show per-finding+ impact.+ """+ results_list = list(results)+ 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)))++ per_result = [0.0] * len(results_list)+ total = 0.0+ for cat, entries in raw.items():+ cap = CATEGORY_CAPS.get(cat, 1.0)+ cat_sum = sum(d for _, d in entries)+ if cat_sum <= cap:+ for idx, d in entries:+ per_result[idx] = d+ total += cat_sum+ else:+ # Scale down proportionally so the cap is respected.+ scale = cap / cat_sum if cat_sum > 0 else 0.0+ for idx, d in entries:+ per_result[idx] = d * scale+ total += cap++ score = max(1.0, min(10.0, 10.0 - total))+ return score, per_result+++def attach_impacts(+ results: list[BiomarkerResult], deductions: list[float]+) -> list[HealthFindingData]:+ """Lift ``BiomarkerResult`` → ``HealthFindingData`` with impact attached."""+ out: list[HealthFindingData] = []+ for r, d in zip(results, deductions, strict=True):+ out.append(+ HealthFindingData(+ biomarker_type=r.biomarker_type,+ severity=r.severity,+ file_path="", # filled by engine+ function_name=r.function_name,+ line_start=r.line_start,+ line_end=r.line_end,+ details=r.details,+ health_impact=round(d, 3),+ reason=r.reason,+ )+ )+ return out+++def compute_kpis(+ metrics: list[HealthFileMetricData],+ hotspot_paths: set[str],+) -> dict[str, object]:+ """Repo-level KPIs derived from per-file metrics.++ - ``hotspot_health``: NLOC-weighted average over files in *hotspot_paths*.+ - ``average_health``: NLOC-weighted average over all files.+ - ``worst_performer``: lowest-scoring file + score.+ """+ if not metrics:+ return {+ "hotspot_health": 10.0,+ "average_health": 10.0,+ "worst_performer_path": None,+ "worst_performer_score": None,+ "file_count": 0,+ }++ def _wavg(rows: list[HealthFileMetricData]) -> float:+ if not rows:+ return 10.0+ total_w = sum(max(r.nloc, 1) for r in rows)+ if total_w == 0:+ return sum(r.score for r in rows) / len(rows)+ return sum(r.score * max(r.nloc, 1) for r in rows) / total_w++ hotspots = [m for m in metrics if m.file_path in hotspot_paths]+ worst = min(metrics, key=lambda m: m.score)+ return {+ "hotspot_health": round(_wavg(hotspots), 2),+ "average_health": round(_wavg(metrics), 2),+ "worst_performer_path": worst.file_path,+ "worst_performer_score": round(worst.score, 2),+ "file_count": len(metrics),+ }diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.pynew file mode 100644index 000000000..9658a8a97--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py@@ -0,0 +1,100 @@+"""Deterministic refactoring suggestions for biomarker findings.++Zero LLM calls — every suggestion is a static, rule-based template+keyed on biomarker type and severity. Used by:++ * ``get_health(include=["refactoring"])`` — attaches a ``suggestion``+ field to each finding in the response.+ * The dashboard's ``RefactoringCard`` — same text, no separate+ server round-trip needed.++Why this lives in the core (not in the MCP layer): suggestion text is+part of the health domain model, not the wire format. Keeping it here+means the CLI (``repowise health --refactoring-targets``) and the MCP+tool share one canonical source of truth.+"""++from __future__ import annotations++from typing import Any++_TEMPLATES: dict[str, str] = {+ "brain_method": (+ "Split this function. It carries high cyclomatic complexity and "+ "many dependents — extract cohesive responsibilities into helpers "+ "so each call site sees a smaller surface area."+ ),+ "nested_complexity": (+ "Flatten the control flow. Pull early-return guards to the top, "+ "extract the deepest branch into a helper, and consider "+ "replacing nested conditionals with a strategy table or "+ "dispatch dict."+ ),+ "complex_method": (+ "Reduce cyclomatic complexity. Decompose the function along its "+ "conditional axes; if it dispatches on a type tag, replace the "+ "if/elif ladder with polymorphism or a lookup table."+ ),+ "bumpy_road": (+ "Smooth the road. Multiple branches at the same nesting depth "+ "usually means the function is doing several jobs — split it "+ "into stages so each stage stays at a single level of "+ "abstraction."+ ),+ "large_method": (+ "Shorten the function. Extract paragraphs (each comment block "+ "is usually a candidate) into named helpers; aim for a body "+ "that reads as a high-level outline of intent."+ ),+ "primitive_obsession": (+ "Introduce a parameter object. Group the related primitives "+ "passed in here into a dataclass so the type names tell the "+ "story and adding another field doesn't break every caller."+ ),+ "dry_violation": (+ "De-duplicate the clone. Extract the shared block into a "+ "private helper, or push it down to a base class if the "+ "structure is genuinely shared rather than coincidental."+ ),+ "untested_hotspot": (+ "Write tests before refactoring. This file is high-churn and "+ "high-dependents but lacks coverage — add characterization "+ "tests for the current behavior first, then refactor with "+ "confidence."+ ),+ "coverage_gap": (+ "Cover the uncovered branches. Start with the highest-impact "+ "uncovered code paths (errors, edge cases, security-sensitive "+ "branches) rather than just chasing the percentage."+ ),+ "developer_congestion": (+ "Cool the contention. Too many authors are touching this file "+ "at once — clarify ownership, or split the file along its "+ "natural seams so contributors don't collide."+ ),+ "knowledge_loss": (+ "Document the surviving knowledge. The primary author(s) of "+ "this file are no longer active — pair-program with someone "+ "still on the team or write down the design intent before "+ "the next change."+ ),+}+++def suggestion_for(biomarker_type: str) -> str:+ """Return the canonical refactoring suggestion for a biomarker.++ Unknown biomarker names fall back to a generic prompt — keeps the+ field non-null on every finding so the UI can rely on it.+ """+ return _TEMPLATES.get(+ biomarker_type,+ "Review this finding and decide whether the underlying smell is "+ "worth refactoring or suppressing via `.repowise/health-rules.json`.",+ )+++def annotate_finding(finding: dict[str, Any]) -> dict[str, Any]:+ """Return *finding* with a ``suggestion`` field added (immutable copy)."""+ biomarker = str(finding.get("biomarker_type", ""))+ return {**finding, "suggestion": suggestion_for(biomarker)}diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.pynew file mode 100644index 000000000..7dd63c406--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/trends.py@@ -0,0 +1,199 @@+"""Snapshot diffing + trend alerts.++Consumed by:+ * the snapshot writer (``persistence/crud.py.save_health_snapshot``) which+ feeds in the rolling window+ * the ``repowise health --trend`` CLI flag (prints the 10 most recent+ snapshots' KPIs side-by-side)+ * the MCP ``get_health(include=["trend"])`` response++Two alert kinds are emitted, matching plan §4 Phase 4 P4.1:++ * ``declining`` — current ``hotspot_health`` is ≥ ``DECLINE_THRESHOLD``+ points (default 0.5) below the snapshot N-5 entries ago. This catches+ sustained drops, not single-snapshot noise.+ * ``predicted_decline`` — the three most recent snapshots are each+ strictly below the one before them. Magnitude is not required —+ direction is the signal.++The module is intentionally state-free. Callers pass in the snapshot+history (oldest → newest) and receive a list of alerts back. No DB+access lives here so trend logic stays unit-testable without an engine+or a session.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime+from typing import Any, Protocol++DECLINE_THRESHOLD: float = 0.5+DECLINE_LOOKBACK: int = 5 # compare current vs snapshot N positions back+PREDICTED_DECLINE_CONSECUTIVE: int = 3+++class SnapshotLike(Protocol):+ """Minimal shape the trend logic needs from a snapshot row."""++ taken_at: datetime+ hotspot_health: float+ average_health: float+ worst_performer_path: str | None+ worst_performer_score: float | None+++@dataclass+class TrendAlert:+ """A single trend signal worth surfacing on the dashboard / CLI."""++ kind: str # "declining" | "predicted_decline"+ metric: str # "hotspot_health" | "average_health"+ current: float+ baseline: float | None+ delta: float+ message: str+++@dataclass+class TrendSummary:+ """Lightweight diff between the newest snapshot and the prior window."""++ current_hotspot_health: float+ current_average_health: float+ previous_hotspot_health: float | None+ previous_average_health: float | None+ hotspot_delta: float | None+ average_delta: float | None+ alerts: list[TrendAlert] = field(default_factory=list)+++def _delta(current: float, previous: float | None) -> float | None:+ if previous is None:+ return None+ return round(current - previous, 3)+++def diff_snapshots(history: list[Any]) -> TrendSummary:+ """Compare the newest snapshot against the window behind it.++ *history* is expected oldest-first (the natural insertion order in+ ``HealthSnapshot``). Empty history yields a summary with neutral+ fields and no alerts.+ """+ if not history:+ return TrendSummary(+ current_hotspot_health=10.0,+ current_average_health=10.0,+ previous_hotspot_health=None,+ previous_average_health=None,+ hotspot_delta=None,+ average_delta=None,+ )++ current = history[-1]+ prior = history[-2] if len(history) >= 2 else None+ summary = TrendSummary(+ current_hotspot_health=float(current.hotspot_health),+ current_average_health=float(current.average_health),+ previous_hotspot_health=float(prior.hotspot_health) if prior else None,+ previous_average_health=float(prior.average_health) if prior else None,+ hotspot_delta=_delta(+ float(current.hotspot_health),+ float(prior.hotspot_health) if prior else None,+ ),+ average_delta=_delta(+ float(current.average_health),+ float(prior.average_health) if prior else None,+ ),+ )++ summary.alerts.extend(_declining_alerts(history))+ summary.alerts.extend(_predicted_decline_alerts(history))+ return summary+++def _declining_alerts(history: list[Any]) -> list[TrendAlert]:+ """``Declining Health`` — current is ≥ threshold below snapshot N-5."""+ if len(history) <= DECLINE_LOOKBACK:+ return []+ current = history[-1]+ baseline = history[-1 - DECLINE_LOOKBACK]+ out: list[TrendAlert] = []+ for metric in ("hotspot_health", "average_health"):+ cur_val = float(getattr(current, metric))+ base_val = float(getattr(baseline, metric))+ delta = round(cur_val - base_val, 3)+ if delta <= -DECLINE_THRESHOLD:+ out.append(+ TrendAlert(+ kind="declining",+ metric=metric,+ current=round(cur_val, 2),+ baseline=round(base_val, 2),+ delta=delta,+ message=(+ f"{metric.replace('_', ' ').title()} dropped "+ f"{abs(delta):.2f} points vs. snapshot "+ f"{DECLINE_LOOKBACK} ago "+ f"({base_val:.2f} → {cur_val:.2f})."+ ),+ )+ )+ return out+++def _predicted_decline_alerts(history: list[Any]) -> list[TrendAlert]:+ """``Predicted Decline`` — N consecutive strict drops, any magnitude."""+ needed = PREDICTED_DECLINE_CONSECUTIVE + 1+ if len(history) < needed:+ return []+ tail = history[-needed:]+ out: list[TrendAlert] = []+ for metric in ("hotspot_health", "average_health"):+ vals = [float(getattr(s, metric)) for s in tail]+ if all(vals[i + 1] < vals[i] for i in range(len(vals) - 1)):+ delta = round(vals[-1] - vals[0], 3)+ out.append(+ TrendAlert(+ kind="predicted_decline",+ metric=metric,+ current=round(vals[-1], 2),+ baseline=round(vals[0], 2),+ delta=delta,+ message=(+ f"{metric.replace('_', ' ').title()} declined for "+ f"{PREDICTED_DECLINE_CONSECUTIVE} consecutive snapshots "+ f"({vals[0]:.2f} → {vals[-1]:.2f})."+ ),+ )+ )+ return out+++def recent_kpis(history: list[Any], limit: int = 10) -> list[dict[str, Any]]:+ """Serialize the most-recent *limit* snapshots for CLI / API consumers.++ Newest first (so the CLI table reads top-down chronologically when+ flipped, which matches user expectation for "recent runs"). Each row+ is a plain dict — no ORM leakage.+ """+ if not history:+ return []+ tail = history[-limit:]+ rows: list[dict[str, Any]] = []+ for snap in reversed(tail):+ rows.append(+ {+ "taken_at": snap.taken_at.isoformat() if snap.taken_at else None,+ "hotspot_health": round(float(snap.hotspot_health), 2),+ "average_health": round(float(snap.average_health), 2),+ "worst_performer_path": snap.worst_performer_path,+ "worst_performer_score": (+ round(float(snap.worst_performer_score), 2)+ if snap.worst_performer_score is not None+ else None+ ),+ }+ )+ return rowsdiff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.pyindex 183bd6716..7ad08a731 100644--- a/packages/core/src/repowise/core/generation/editor_files/data.py+++ b/packages/core/src/repowise/core/generation/editor_files/data.py@@ -41,6 +41,19 @@ class DecisionSummary:decision: str = "" # what was chosen (first ~120 chars)+@dataclass(frozen=True)+class CodeHealthBlock:+ """Compact summary for the generated CLAUDE.md ``## Code health`` section."""++ hotspot_health: float+ average_health: float+ worst_score: float+ worst_path: str+ hotspot_trend: str = "stable"+ critical_biomarkers: list[dict] = field(default_factory=list)+ untested_hotspots: list[dict] = field(default_factory=list)++@dataclass(frozen=True)class EditorFileData:repo_name: str@@ -54,6 +67,7 @@ class EditorFileData:decisions: list[DecisionSummary] = field(default_factory=list)build_commands: dict[str, str] = field(default_factory=dict)avg_confidence: float = 0.0+ code_health: CodeHealthBlock | None = None# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.pyindex 9f27cb0f9..7bf4839a8 100644--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py@@ -19,10 +19,18 @@ from repowise.core.persistence.models import (DecisionRecord,GitMetadata,GraphNode,+ HealthFileMetric,+ HealthFinding,Page,)-from .data import DecisionSummary, EditorFileData, HotspotFile, KeyModule+from .data import (+ CodeHealthBlock,+ DecisionSummary,+ EditorFileData,+ HotspotFile,+ KeyModule,+)from .tech_stack import detect_build_commands, detect_tech_stack# Maximum items per section to keep CLAUDE.md within ~200 lines@@ -62,6 +70,7 @@ class EditorFileDataFetcher:decisions=await self._get_decisions(),build_commands=detect_build_commands(self._repo_path),avg_confidence=await self._get_avg_confidence(),+ code_health=await self._get_code_health(),)# ------------------------------------------------------------------@@ -203,6 +212,92 @@ class EditorFileDataFetcher:avg = result.scalar_one_or_none()return round(float(avg), 2) if avg is not None else 0.0+ async def _get_code_health(self) -> CodeHealthBlock | None:+ """Build the compact code-health block for CLAUDE.md.++ Filters per plan §9: critical biomarkers in hotspot files, plus+ any Brain Method finding. Empty list when no health data yet.+ """+ metric_rows = list(+ (+ await self._session.execute(+ select(HealthFileMetric).where(+ HealthFileMetric.repository_id == self._repo_id,+ )+ )+ )+ .scalars()+ .all()+ )+ if not metric_rows:+ return None++ # KPIs.+ total_nloc = sum(max(m.nloc, 1) for m in metric_rows)+ avg = (+ sum(m.score * max(m.nloc, 1) for m in metric_rows) / total_nloc+ if total_nloc+ else sum(m.score for m in metric_rows) / len(metric_rows)+ )+ worst = min(metric_rows, key=lambda m: m.score)++ # Hotspot-flagged paths.+ hotspot_paths_res = await self._session.execute(+ select(GitMetadata.file_path).where(+ GitMetadata.repository_id == self._repo_id,+ GitMetadata.is_hotspot == True, # noqa: E712+ )+ )+ hotspot_paths = {row[0] for row in hotspot_paths_res.all()}++ hotspot_metrics = [m for m in metric_rows if m.file_path in hotspot_paths]+ if hotspot_metrics:+ h_nloc = sum(max(m.nloc, 1) for m in hotspot_metrics)+ hotspot_health = (+ sum(m.score * max(m.nloc, 1) for m in hotspot_metrics) / h_nloc+ if h_nloc+ else avg+ )+ else:+ hotspot_health = avg++ # Critical biomarkers: brain methods, or critical-severity findings+ # in hotspot files. Cap at 5 to keep CLAUDE.md tight.+ f_res = await self._session.execute(+ select(HealthFinding)+ .where(+ HealthFinding.repository_id == self._repo_id,+ HealthFinding.status == "open",+ )+ .order_by(HealthFinding.health_impact.desc())+ )+ all_findings = list(f_res.scalars().all())+ critical = []+ for f in all_findings:+ if len(critical) >= 5:+ break+ if f.biomarker_type == "brain_method" or (+ f.severity == "critical" and f.file_path in hotspot_paths+ ):+ critical.append({+ "path": f.file_path,+ "summary": (+ f"{f.biomarker_type.replace('_', ' ')}"+ + (f" ({f.function_name})" if f.function_name else "")+ + f" — impact −{f.health_impact:.1f}"+ ),+ })++ return CodeHealthBlock(+ hotspot_health=round(hotspot_health, 2),+ average_health=round(avg, 2),+ worst_score=round(worst.score, 2),+ worst_path=worst.file_path,+ hotspot_trend="stable",+ critical_biomarkers=critical,+ untested_hotspots=[], # Phase 2 fills this from coverage data+ )+async def _get_owners_for_paths(self, paths: list[str]) -> dict[str, str]:"""Return {path: primary_owner_name} for the given paths."""if not paths:diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index d046dcf78..6e0e62cb1 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -47,6 +47,27 @@ Last indexed: {{ data.indexed_at }}{% if data.indexed_commit %} (commit {{ data.| `{{ h.path }}` | {{ h.churn_percentile }}th %ile | {{ h.commit_count_90d }} | {{ h.owner or "—" }} |{% endfor %}{% endif %}+{% if data.code_health %}++## Code health+Hotspot health: {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}) ·+Average: {{ data.code_health.average_health }}/10 ·+Worst: {{ data.code_health.worst_score }}/10 (`{{ data.code_health.worst_path }}`)+{% if data.code_health.critical_biomarkers %}++### Critical biomarkers+{% for b in data.code_health.critical_biomarkers %}+- `{{ b.path }}` — {{ b.summary }}+{% endfor %}+{% endif %}+{% if data.code_health.untested_hotspots %}++### Untested hotspots+{% for h in data.code_health.untested_hotspots %}+- `{{ h.path }}` — {{ h.dependents }} dependents, {{ h.coverage_pct }}% coverage, {{ h.commits_90d }} commits/90d+{% endfor %}+{% endif %}+{% endif %}### Repowise MCP Toolsdiff --git a/packages/core/src/repowise/core/persistence/crud.py b/packages/core/src/repowise/core/persistence/crud.pyindex 7bd3baef7..1f5e387c5 100644--- a/packages/core/src/repowise/core/persistence/crud.py+++ b/packages/core/src/repowise/core/persistence/crud.py@@ -24,6 +24,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom .models import (ChatMessage,Conversation,+ CoverageFile,DeadCodeFinding,DecisionRecord,ExternalSystem,@@ -31,6 +32,9 @@ from .models import (GitMetadata,GraphEdge,GraphNode,+ HealthFileMetric,+ HealthFinding,+ HealthSnapshot,Page,PageVersion,Repository,@@ -130,9 +134,7 @@ async def delete_repository(session: AsyncSession, repo_id: str) -> bool:async def list_page_ids(session: AsyncSession, repository_id: str) -> list[str]:"""Return all page IDs for a repository (lightweight, ID-only query)."""- result = await session.execute(- select(Page.id).where(Page.repository_id == repository_id)- )+ result = await session.execute(select(Page.id).where(Page.repository_id == repository_id))return list(result.scalars().all())@@ -347,9 +349,7 @@ async def load_prior_pages(# module-load time.from repowise.core.generation.page_generator import PriorPage- result = await session.execute(- select(Page).where(Page.repository_id == repository_id)- )+ result = await session.execute(select(Page).where(Page.repository_id == repository_id))prior: dict[str, Any] = {}for row in result.scalars():prior[row.id] = PriorPage(@@ -642,9 +642,7 @@ async def link_graph_nodes_to_external_systems(return updated-async def list_external_systems(- session: AsyncSession, repository_id: str-) -> list[ExternalSystem]:+async def list_external_systems(session: AsyncSession, repository_id: str) -> list[ExternalSystem]:"""List all external systems for a repository, ordered by name."""result = await session.execute(select(ExternalSystem)@@ -1299,6 +1297,7 @@ async def delete_decision(session: AsyncSession, decision_id: str) -> bool:def _normalize_title(title: str) -> str:"""Normalize a decision title for cross-source dedup comparison."""import re as _re+t = title.lower().strip()t = _re.sub(r"[^a-z0-9\s]", "", t)t = _re.sub(r"\s+", " ", t)@@ -1808,3 +1807,526 @@ async def get_node_degree_counts("in_degree": in_result.scalar() or 0,"out_degree": out_result.scalar() or 0,}+++# ---------------------------------------------------------------------------+# Code Health CRUD+# ---------------------------------------------------------------------------+++async def save_health_findings(+ session: AsyncSession,+ repository_id: str,+ findings: list[Any],+) -> None:+ """Replace open health findings for *repository_id* with *findings*.++ Mirrors ``save_dead_code_findings`` — delete-then-insert. Accepts+ either ``HealthFindingData`` dataclasses or plain dicts.+ """+ existing = await session.execute(+ select(HealthFinding).where(+ HealthFinding.repository_id == repository_id,+ HealthFinding.status == "open",+ )+ )+ for row in existing.scalars().all():+ await session.delete(row)++ for i in range(0, len(findings), _BATCH_SIZE):+ batch = findings[i : i + _BATCH_SIZE]+ for f in batch:+ if hasattr(f, "biomarker_type"):+ severity = f.severity+ severity_str = str(severity.value) if hasattr(severity, "value") else str(severity)+ data = {+ "file_path": f.file_path,+ "biomarker_type": f.biomarker_type,+ "severity": severity_str,+ "function_name": f.function_name,+ "line_start": f.line_start,+ "line_end": f.line_end,+ "details_json": json.dumps(f.details or {}),+ "health_impact": float(f.health_impact),+ "reason": f.reason or "",+ }+ else:+ data = dict(f)+ if "details" in data:+ data["details_json"] = json.dumps(data.pop("details") or {})++ session.add(+ HealthFinding(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in data.items()+ if k not in ("id", "repository_id") and hasattr(HealthFinding, k)+ },+ )+ )+ await session.flush()+++async def save_health_metrics(+ session: AsyncSession,+ repository_id: str,+ metrics: list[Any],+) -> None:+ """Replace per-file health metrics for *repository_id*.++ Delete-then-insert (matches the findings writer). The unique+ constraint on (repository_id, file_path) means we cannot leave+ stale rows around without an upsert dance — delete-and-insert keeps+ it simple and aligns with how dead-code findings are written.+ """+ existing = await session.execute(+ select(HealthFileMetric).where(HealthFileMetric.repository_id == repository_id)+ )+ for row in existing.scalars().all():+ await session.delete(row)+ await session.flush()++ for i in range(0, len(metrics), _BATCH_SIZE):+ batch = metrics[i : i + _BATCH_SIZE]+ for m in batch:+ if hasattr(m, "file_path"):+ data = {+ "file_path": m.file_path,+ "score": float(m.score),+ "max_ccn": int(m.max_ccn),+ "max_nesting": int(m.max_nesting),+ "nloc": int(m.nloc),+ "duplication_pct": m.duplication_pct,+ "has_test_file": bool(m.has_test_file),+ "line_coverage_pct": m.line_coverage_pct,+ "branch_coverage_pct": m.branch_coverage_pct,+ "module": m.module,+ }+ else:+ data = dict(m)++ session.add(+ HealthFileMetric(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in data.items()+ if k not in ("id", "repository_id") and hasattr(HealthFileMetric, k)+ },+ )+ )+ await session.flush()+++async def get_health_findings(+ session: AsyncSession,+ repository_id: str,+ *,+ biomarker_type: str | None = None,+ min_severity: str | None = None,+ file_path: str | None = None,+ status: str = "open",+) -> list[HealthFinding]:+ q = select(HealthFinding).where(+ HealthFinding.repository_id == repository_id,+ HealthFinding.status == status,+ )+ if biomarker_type is not None:+ q = q.where(HealthFinding.biomarker_type == biomarker_type)+ if file_path is not None:+ q = q.where(HealthFinding.file_path == file_path)+ if min_severity is not None:+ # Severity order: low < medium < high < critical+ order = {"low": 0, "medium": 1, "high": 2, "critical": 3}+ threshold = order.get(min_severity, 0)+ allowed = [k for k, v in order.items() if v >= threshold]+ q = q.where(HealthFinding.severity.in_(allowed))+ q = q.order_by(HealthFinding.health_impact.desc())+ result = await session.execute(q)+ return list(result.scalars().all())+++async def get_health_metrics(+ session: AsyncSession,+ repository_id: str,+ *,+ file_paths: list[str] | None = None,+) -> list[HealthFileMetric]:+ q = select(HealthFileMetric).where(HealthFileMetric.repository_id == repository_id)+ if file_paths is not None:+ q = q.where(HealthFileMetric.file_path.in_(file_paths))+ q = q.order_by(HealthFileMetric.score.asc())+ result = await session.execute(q)+ return list(result.scalars().all())+++async def get_health_summary(session: AsyncSession, repository_id: str) -> dict:+ """Aggregate KPIs over the per-file metrics table."""+ metrics = await get_health_metrics(session, repository_id)+ if not metrics:+ return {+ "file_count": 0,+ "average_health": 10.0,+ "worst_performer_path": None,+ "worst_performer_score": None,+ "open_findings": 0,+ }+ total_nloc = sum(max(m.nloc, 1) for m in metrics)+ if total_nloc:+ avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc+ else:+ avg = sum(m.score for m in metrics) / len(metrics)+ worst = min(metrics, key=lambda r: r.score)+ findings_count = await session.execute(+ select(func.count())+ .select_from(HealthFinding)+ .where(+ HealthFinding.repository_id == repository_id,+ HealthFinding.status == "open",+ )+ )+ return {+ "file_count": len(metrics),+ "average_health": round(avg, 2),+ "worst_performer_path": worst.file_path,+ "worst_performer_score": round(worst.score, 2),+ "open_findings": findings_count.scalar() or 0,+ }+++async def update_health_finding_status(+ session: AsyncSession,+ finding_id: str,+ status: str,+) -> HealthFinding | None:+ f = await session.get(HealthFinding, finding_id)+ if f is None:+ return None+ f.status = status+ await session.flush()+ return f+++# Rolling history kept per repo. Older snapshots are deleted on insert.+# 50 entries gives Phase 4's `--trend` flag (last 10) plus the 5-back+# Declining-Health baseline plenty of headroom.+HEALTH_SNAPSHOT_RETENTION: int = 50+++async def save_health_snapshot(+ session: AsyncSession,+ repository_id: str,+ *,+ hotspot_health: float,+ average_health: float,+ worst_performer_path: str | None,+ worst_performer_score: float | None,+ per_file_scores: dict[str, float] | None = None,+ taken_at: datetime | None = None,+) -> HealthSnapshot:+ """Append a snapshot; prune oldest rows past ``HEALTH_SNAPSHOT_RETENTION``.++ Returns the inserted row. Per-file scores are stored compactly as+ ``{path: score}`` JSON (no per-finding detail — that lives in+ ``HealthFinding`` rows; snapshots are a thin history layer).+ """+ snap = HealthSnapshot(+ id=_new_uuid(),+ repository_id=repository_id,+ taken_at=taken_at or _now_utc(),+ hotspot_health=float(hotspot_health),+ average_health=float(average_health),+ worst_performer_path=worst_performer_path,+ worst_performer_score=(+ float(worst_performer_score) if worst_performer_score is not None else None+ ),+ per_file_scores_json=json.dumps(per_file_scores or {}, separators=(",", ":")),+ )+ session.add(snap)+ await session.flush()++ # Prune older-than-retention rows. We keep the *N* newest by+ # ``taken_at``; ties are broken by id (UUIDs are random but stable).+ rows = await session.execute(+ select(HealthSnapshot)+ .where(HealthSnapshot.repository_id == repository_id)+ .order_by(HealthSnapshot.taken_at.desc(), HealthSnapshot.id.desc())+ )+ history = list(rows.scalars().all())+ if len(history) > HEALTH_SNAPSHOT_RETENTION:+ for row in history[HEALTH_SNAPSHOT_RETENTION:]:+ await session.delete(row)+ await session.flush()+ return snap+++async def list_health_snapshots(+ session: AsyncSession,+ repository_id: str,+ *,+ limit: int | None = None,+) -> list[HealthSnapshot]:+ """Return snapshots **oldest-first** (the shape ``trends.diff_snapshots``+ expects). Pass ``limit`` to cap the most recent N (still returned+ oldest-first for stable iteration)."""+ q = (+ select(HealthSnapshot)+ .where(HealthSnapshot.repository_id == repository_id)+ .order_by(HealthSnapshot.taken_at.asc(), HealthSnapshot.id.asc())+ )+ result = await session.execute(q)+ rows = list(result.scalars().all())+ if limit is not None and len(rows) > limit:+ rows = rows[-limit:]+ return rows+++async def upsert_health_findings(+ session: AsyncSession,+ repository_id: str,+ findings: list[Any],+ *,+ file_paths: list[str],+) -> None:+ """Replace open findings **only for the given file paths**.++ Used by the incremental ``repowise update`` path so unchanged files+ keep their findings instead of being wiped on every partial re-index.+ """+ if not file_paths:+ return+ existing = await session.execute(+ select(HealthFinding).where(+ HealthFinding.repository_id == repository_id,+ HealthFinding.status == "open",+ HealthFinding.file_path.in_(file_paths),+ )+ )+ for row in existing.scalars().all():+ await session.delete(row)+ await session.flush()++ for i in range(0, len(findings), _BATCH_SIZE):+ batch = findings[i : i + _BATCH_SIZE]+ for f in batch:+ if hasattr(f, "biomarker_type"):+ severity = f.severity+ severity_str = str(severity.value) if hasattr(severity, "value") else str(severity)+ data = {+ "file_path": f.file_path,+ "biomarker_type": f.biomarker_type,+ "severity": severity_str,+ "function_name": f.function_name,+ "line_start": f.line_start,+ "line_end": f.line_end,+ "details_json": json.dumps(f.details or {}),+ "health_impact": float(f.health_impact),+ "reason": f.reason or "",+ }+ else:+ data = dict(f)+ if "details" in data:+ data["details_json"] = json.dumps(data.pop("details") or {})++ session.add(+ HealthFinding(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in data.items()+ if k not in ("id", "repository_id") and hasattr(HealthFinding, k)+ },+ )+ )+ await session.flush()+++async def upsert_health_metrics(+ session: AsyncSession,+ repository_id: str,+ metrics: list[Any],+) -> None:+ """Upsert per-file metrics; unchanged files in the table stay put.++ Sibling of ``save_health_metrics`` (which delete-then-inserts the+ whole repo). Used by the incremental analysis path so a partial+ re-index never wipes metric rows for files that weren't touched.+ """+ if not metrics:+ return+ paths = [m.file_path if hasattr(m, "file_path") else m["file_path"] for m in metrics]+ existing = await session.execute(+ select(HealthFileMetric).where(+ HealthFileMetric.repository_id == repository_id,+ HealthFileMetric.file_path.in_(paths),+ )+ )+ by_path = {row.file_path: row for row in existing.scalars().all()}++ for m in metrics:+ if hasattr(m, "file_path"):+ data = {+ "file_path": m.file_path,+ "score": float(m.score),+ "max_ccn": int(m.max_ccn),+ "max_nesting": int(m.max_nesting),+ "nloc": int(m.nloc),+ "duplication_pct": m.duplication_pct,+ "has_test_file": bool(m.has_test_file),+ "line_coverage_pct": m.line_coverage_pct,+ "branch_coverage_pct": m.branch_coverage_pct,+ "module": m.module,+ }+ else:+ data = dict(m)++ row = by_path.get(data["file_path"])+ if row is not None:+ for k, v in data.items():+ if k in ("id", "repository_id") or not hasattr(HealthFileMetric, k):+ continue+ setattr(row, k, v)+ else:+ session.add(+ HealthFileMetric(+ id=_new_uuid(),+ repository_id=repository_id,+ **{+ k: v+ for k, v in data.items()+ if k not in ("id", "repository_id") and hasattr(HealthFileMetric, k)+ },+ )+ )+ await session.flush()+++# ---------------------------------------------------------------------------+# Coverage CRUD+# ---------------------------------------------------------------------------+++async def save_coverage_files(+ session: AsyncSession,+ repository_id: str,+ files: list[Any],+ *,+ source_format: str,+ ingested_commit_sha: str | None = None,+) -> None:+ """Replace coverage rows for *repository_id* with *files*.++ Mirrors the delete-then-insert pattern used by the health writers.+ *files* is a list of ``FileCoverage`` dataclasses (or dicts with the+ same shape).+ """+ existing = await session.execute(+ select(CoverageFile).where(CoverageFile.repository_id == repository_id)+ )+ for row in existing.scalars().all():+ await session.delete(row)+ await session.flush()++ for i in range(0, len(files), _BATCH_SIZE):+ batch = files[i : i + _BATCH_SIZE]+ for f in batch:+ if hasattr(f, "file_path"):+ data = {+ "file_path": f.file_path,+ "line_coverage_pct": float(f.line_coverage_pct),+ "branch_coverage_pct": (+ float(f.branch_coverage_pct) if f.branch_coverage_pct is not None else None+ ),+ "covered_lines_json": json.dumps(list(f.covered_lines or [])),+ "total_coverable_lines": int(f.total_coverable_lines or 0),+ }+ else:+ data = dict(f)+ if "covered_lines" in data:+ data["covered_lines_json"] = json.dumps(list(data.pop("covered_lines") or []))++ session.add(+ CoverageFile(+ id=_new_uuid(),+ repository_id=repository_id,+ source_format=source_format,+ ingested_commit_sha=ingested_commit_sha,+ **{+ k: v+ for k, v in data.items()+ if k+ not in (+ "id",+ "repository_id",+ "source_format",+ "ingested_commit_sha",+ )+ and hasattr(CoverageFile, k)+ },+ )+ )+ await session.flush()+++async def load_coverage_for_repo(+ session: AsyncSession,+ repository_id: str,+ *,+ file_paths: list[str] | None = None,+) -> list[CoverageFile]:+ q = select(CoverageFile).where(CoverageFile.repository_id == repository_id)+ if file_paths is not None:+ q = q.where(CoverageFile.file_path.in_(file_paths))+ result = await session.execute(q)+ return list(result.scalars().all())+++async def get_coverage_summary(+ session: AsyncSession,+ repository_id: str,+) -> dict[str, Any]:+ """Repo-level coverage aggregate. Returns an empty shape when no rows."""+ rows = await load_coverage_for_repo(session, repository_id)+ if not rows:+ return {+ "file_count": 0,+ "covered_lines": 0,+ "total_lines": 0,+ "line_coverage_pct": None,+ "branch_coverage_pct": None,+ "source_format": None,+ "ingested_at": None,+ "ingested_commit_sha": None,+ }+ covered = 0+ total = 0+ branch_pcts: list[float] = []+ branch_weights: list[int] = []+ for r in rows:+ covered += round(r.line_coverage_pct / 100.0 * r.total_coverable_lines)+ total += r.total_coverable_lines+ if r.branch_coverage_pct is not None:+ branch_pcts.append(r.branch_coverage_pct)+ branch_weights.append(max(r.total_coverable_lines, 1))+ line_pct = (covered / total * 100.0) if total else 0.0+ branch_pct: float | None+ if branch_pcts:+ wsum = sum(branch_weights)+ branch_pct = sum(p * w for p, w in zip(branch_pcts, branch_weights, strict=True)) / wsum+ else:+ branch_pct = None+ latest = max(rows, key=lambda r: r.ingested_at)+ return {+ "file_count": len(rows),+ "covered_lines": covered,+ "total_lines": total,+ "line_coverage_pct": round(line_pct, 2),+ "branch_coverage_pct": round(branch_pct, 2) if branch_pct is not None else None,+ "source_format": latest.source_format,+ "ingested_at": latest.ingested_at,+ "ingested_commit_sha": latest.ingested_commit_sha,+ }diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 315199f51..780fb74cc 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -535,6 +535,105 @@ class DeadCodeFinding(Base):)+class HealthFinding(Base):+ """One biomarker hit produced by the code-health analyzer."""++ __tablename__ = "health_findings"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ biomarker_type: Mapped[str] = mapped_column(String(64), nullable=False)+ severity: Mapped[str] = mapped_column(String(16), nullable=False)+ function_name: Mapped[str | None] = mapped_column(String(255), nullable=True)+ line_start: Mapped[int | None] = mapped_column(Integer, nullable=True)+ line_end: Mapped[int | None] = mapped_column(Integer, nullable=True)+ details_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+ health_impact: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ reason: Mapped[str] = mapped_column(Text, nullable=False, default="")+ status: Mapped[str] = mapped_column(String(32), nullable=False, default="open")+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )+++class HealthFileMetric(Base):+ """Per-file aggregate metrics + final score."""++ __tablename__ = "health_file_metrics"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ score: Mapped[float] = mapped_column(Float, nullable=False, default=10.0)+ max_ccn: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ max_nesting: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ nloc: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ duplication_pct: Mapped[float | None] = mapped_column(Float, nullable=True)+ has_test_file: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)+ line_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)+ branch_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)+ module: Mapped[str | None] = mapped_column(String(255), nullable=True)+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc+ )++ __table_args__ = (+ UniqueConstraint("repository_id", "file_path", name="uq_health_file_metrics"),+ )+++class HealthSnapshot(Base):+ """KPI history + compact per-file score map. Keep last 50 per repo."""++ __tablename__ = "health_snapshots"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ taken_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ hotspot_health: Mapped[float] = mapped_column(Float, nullable=False, default=10.0)+ average_health: Mapped[float] = mapped_column(Float, nullable=False, default=10.0)+ worst_performer_path: Mapped[str | None] = mapped_column(Text, nullable=True)+ worst_performer_score: Mapped[float | None] = mapped_column(Float, nullable=True)+ per_file_scores_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")+++class CoverageFile(Base):+ """Per-file coverage data, overwritten on each --coverage run."""++ __tablename__ = "coverage_files"++ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)+ repository_id: Mapped[str] = mapped_column(+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False+ )+ file_path: Mapped[str] = mapped_column(Text, nullable=False)+ source_format: Mapped[str] = mapped_column(String(32), nullable=False)+ line_coverage_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)+ branch_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)+ covered_lines_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")+ total_coverable_lines: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ ingested_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), nullable=False, default=_now_utc+ )+ ingested_commit_sha: Mapped[str | None] = mapped_column(String(40), nullable=True)++ __table_args__ = (+ UniqueConstraint("repository_id", "file_path", name="uq_coverage_files"),+ )++class AnswerCache(Base):"""Cached LLM-synthesized answers from get_answer.diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 7621df7a8..34c0894e4 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -171,6 +171,9 @@ class PipelineResult:execution_flow_report: Any | None = None"""``ExecutionFlowReport`` or None (populated after graph build)."""+ health_report: Any | None = None+ """``HealthReport`` or None — populated by ``_run_health_analysis``."""+# Traversal statstraversal_stats: Any | None = None"""``TraversalStats`` from the file traverser, or None."""@@ -342,7 +345,7 @@ async def run_pipeline("info",f"→ External systems: {len(external_systems):,} declared deps across manifests",)- except Exception as _ext_err: # noqa: BLE001+ except Exception as _ext_err:logger.warning("external_systems_extraction_failed", error=str(_ext_err))_phase_done(progress, "external_systems")@@ -391,6 +394,10 @@ async def run_pipeline(dead_code_report = await _run_dead_code_analysis(graph_builder, git_meta_map, progress=progress)+ health_report = await _run_health_analysis(+ graph_builder, git_meta_map, parsed_files, repo_path=repo_path, progress=progress+ )+decision_report = await _run_decision_extraction(repo_path,llm_client=llm_client,@@ -414,7 +421,7 @@ async def run_pipeline(resolved_generation_config = GenerationConfig(max_concurrency=concurrency,- reasoning=resolve_reasoning(config=load_repo_config(repo_path))+ reasoning=resolve_reasoning(config=load_repo_config(repo_path)),)# Phase 2 enrichment: flag framework-defined HTTP surfaces (FastAPI,@@ -423,12 +430,11 @@ async def run_pipeline(# generation package so language-specific heuristics stay co-located# with the templates that consume them.from repowise.core.generation import detect_code_api_contracts as _detect_apis+try:flipped = _detect_apis(parsed_files)if flipped and progress:- progress.on_message(- "info", f"→ Detected {flipped} additional API contract file(s)"- )+ progress.on_message("info", f"→ Detected {flipped} additional API contract file(s)")except Exception as _api_err:logger.warning("api_contract_detection_failed", error=str(_api_err))@@ -477,6 +483,7 @@ async def run_pipeline(git_summary=git_summary,dead_code_report=dead_code_report,decision_report=decision_report,+ health_report=health_report,execution_flow_report=execution_flow_report,generated_pages=generated_pages,traversal_stats=traversal_stats,@@ -486,8 +493,7 @@ async def run_pipeline(languages=languages,elapsed_seconds=elapsed,tech_stack=[- {"name": t.name, "version": t.version, "category": t.category}- for t in tech_items+ {"name": t.name, "version": t.version, "category": t.category} for t in tech_items],external_systems=external_systems,)@@ -887,6 +893,86 @@ async def _run_dead_code_analysis(return None+async def _run_health_analysis(+ graph_builder: Any,+ git_meta_map: dict[str, dict],+ parsed_files: list[Any],+ *,+ repo_path: Path | None = None,+ progress: ProgressCallback | None,+) -> Any | None:+ """Run code-health analysis (complexity + biomarkers + scoring)."""+ try:+ from repowise.core.analysis.health import HealthAnalyzer+ from repowise.core.analysis.health.config import HealthConfig++ if progress:+ # Per-file determinate progress: one tick per parsed file.+ progress.on_phase_start("health", len(parsed_files))++ # Build a {file_path → community label} map so per-file metrics+ # carry a real module name, not None. Community detection is+ # already computed for the graph view, so this is essentially+ # free.+ module_map: dict[str, str] = {}+ try:+ cd = graph_builder.community_detection()+ ci = graph_builder.community_info()+ for node_id, comm_id in cd.items():+ info = ci.get(comm_id)+ label = getattr(info, "label", None) if info else None+ if label:+ module_map[node_id] = label+ except Exception as exc:+ logger.debug("health_module_map_failed", error=str(exc))++ analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map=git_meta_map,+ parsed_files=parsed_files,+ module_map=module_map,+ )++ # Load per-file override rules from `.repowise/health-rules.json`.+ # Missing or malformed file → empty config (no-op).+ analyzer_config: dict[str, object] | None = None+ if repo_path is not None:+ cfg = HealthConfig.load(repo_path)+ if cfg.disabled_biomarkers or cfg.rules:+ file_paths = [pf.file_info.path for pf in parsed_files]+ analyzer_config = cfg.to_analyzer_config(file_paths)++ def _step(_path: str) -> None:+ if progress:+ progress.on_item_done("health")++ # Parallel path for repos large enough to benefit (tree-sitter+ # releases the GIL during parsing, so asyncio.gather over a+ # thread pool actually scales). Threshold chosen so small repos+ # avoid the overhead.+ if len(parsed_files) >= 500:+ report = await analyzer.analyze_async(analyzer_config, on_step=_step)+ else:+ report = await asyncio.to_thread(analyzer.analyze, analyzer_config, on_step=_step)++ if progress:+ findings_count = len(report.findings)+ avg = report.kpis.get("average_health", 10.0)+ worst = report.kpis.get("worst_performer_score", 10.0)+ progress.on_message(+ "info",+ f"→ {findings_count} health findings · avg {avg}/10 · worst {worst}/10",+ )++ _phase_done(progress, "health")+ return report+ except Exception as exc:+ if progress:+ progress.on_message("warning", f"Health analysis skipped: {exc}")+ _phase_done(progress, "health")+ return None++async def _run_decision_extraction(repo_path: Path,*,@@ -1065,8 +1151,7 @@ async def run_generation(if progress:if onboarding_generated or promoted_present:slots_made = sorted(- {p.metadata.get("subkind", "?") for p in onboarding_generated}- | promoted_present+ {p.metadata.get("subkind", "?") for p in onboarding_generated} | promoted_present)progress.on_message("info",diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex ff87bb8ca..0456351dc 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -123,7 +123,6 @@ async def persist_pipeline_result("""from repowise.core.persistence import (batch_upsert_graph_edges,- batch_upsert_graph_nodes,batch_upsert_symbols,bulk_upsert_external_systems,link_graph_nodes_to_external_systems,@@ -133,6 +132,9 @@ async def persist_pipeline_result(bulk_upsert_decisions,recompute_decision_staleness,save_dead_code_findings,+ save_health_findings,+ save_health_metrics,+ save_health_snapshot,upsert_git_metadata_bulk,)@@ -203,12 +205,10 @@ async def persist_pipeline_result(scanner = SecurityScanner(session, repo_id)for pf in result.parsed_files:source_text = getattr(pf.file_info, "content", "") or ""- findings = await scanner.scan_file(- pf.file_info.path, source_text, pf.symbols- )+ findings = await scanner.scan_file(pf.file_info.path, source_text, pf.symbols)if findings:await scanner.persist(pf.file_info.path, findings)- except Exception as _sec_err: # noqa: BLE001 — scanner must never break the pipeline+ except Exception as _sec_err:logger.warning("security_scan_skipped", error=str(_sec_err))# ---- Git metadata --------------------------------------------------------@@ -219,6 +219,27 @@ async def persist_pipeline_result(if result.dead_code_report and result.dead_code_report.findings:await save_dead_code_findings(session, repo_id, result.dead_code_report.findings)+ # ---- Health findings + per-file metrics ---------------------------------+ if getattr(result, "health_report", None):+ hr = result.health_report+ await save_health_metrics(session, repo_id, hr.metrics or [])+ if hr.findings:+ await save_health_findings(session, repo_id, hr.findings)+ # Snapshot the run for trend tracking (rolling delete inside).+ kpis = hr.kpis or {}+ try:+ await save_health_snapshot(+ session,+ repo_id,+ hotspot_health=float(kpis.get("hotspot_health", 10.0)),+ average_health=float(kpis.get("average_health", 10.0)),+ worst_performer_path=kpis.get("worst_performer_path"),+ worst_performer_score=kpis.get("worst_performer_score"),+ per_file_scores={m.file_path: round(float(m.score), 2) for m in hr.metrics or []},+ )+ except Exception as _snap_err:+ logger.warning("health_snapshot_skipped", error=str(_snap_err))+# ---- Decision records ----------------------------------------------------if result.decision_report and result.decision_report.decisions:await bulk_upsert_decisions(@@ -236,9 +257,7 @@ async def persist_pipeline_result(if fp:git_meta_map[fp] = gm_dictif git_meta_map:- updated = await recompute_decision_staleness(- session, repo_id, git_meta_map- )+ updated = await recompute_decision_staleness(session, repo_id, git_meta_map)if updated:logger.info("decision_staleness_recomputed", updated=updated)except Exception as _stale_err:diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 466f4311d..a9cfc17b9 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -12,10 +12,10 @@ import osfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager+from fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse-from fastapi import FastAPI, Requestfrom repowise.core.persistence.database import (create_engine,create_session_factory,@@ -32,6 +32,7 @@ from repowise.server.routers import (c4,chat,claude_md,+ code_health,costs,dead_code,decisions,@@ -97,8 +98,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:db_url = resolve_db_url()if not os.environ.get("REPOWISE_DB_URL") and not os.environ.get("REPOWISE_DATABASE_URL"):try:- from pathlib import Path as _WsPath- from repowise.core.workspace.config import find_workspace_root, WorkspaceConfig+ from repowise.core.workspace.config import WorkspaceConfig, find_workspace_root_ws_root = find_workspace_root()if _ws_root is not None:@@ -123,9 +123,12 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:# Note: with multi-worker deployments this is a best-effort race; the# try/except prevents a SQLite lock error from crashing startup.try:+ from datetime import UTC as _UTC+ from datetime import datetime+from sqlalchemy import update as sa_update+from repowise.core.persistence.models import GenerationJob- from datetime import datetime, UTC as _UTCasync with get_session(session_factory) as session:stale_result = await session.execute(@@ -338,6 +341,7 @@ def create_app() -> FastAPI:app.include_router(webhooks.router)app.include_router(git.router)app.include_router(dead_code.router)+ app.include_router(code_health.router)app.include_router(claude_md.router)app.include_router(decisions.router)app.include_router(chat.router)diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex cc4405f3c..c0fcfba7a 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -16,6 +16,9 @@ from typing import Any# --- Import submodules in dependency order (triggers tool registration) ---from repowise.server.mcp_server import _state+from repowise.server.mcp_server._graph_utils import ( # used by routers/graph.py+ build_visual_context as _build_visual_context,+)from repowise.server.mcp_server._helpers import (_build_origin_story,_compute_alignment,@@ -27,12 +30,10 @@ from repowise.server.mcp_server._server import (mcp,run_mcp,)-from repowise.server.mcp_server._graph_utils import ( # used by routers/graph.py- build_visual_context as _build_visual_context,-)from repowise.server.mcp_server.tool_answer import get_answerfrom repowise.server.mcp_server.tool_context import get_contextfrom repowise.server.mcp_server.tool_dead_code import get_dead_code+from repowise.server.mcp_server.tool_health import get_healthfrom repowise.server.mcp_server.tool_overview import get_overviewfrom repowise.server.mcp_server.tool_risk import get_riskfrom repowise.server.mcp_server.tool_search import search_codebase@@ -95,6 +96,7 @@ __all__ = ["get_answer","get_context","get_dead_code",+ "get_health","get_overview","get_risk","get_symbol",diff --git a/packages/server/src/repowise/server/mcp_server/tool_context.py b/packages/server/src/repowise/server/mcp_server/tool_context.pyindex c26857755..059eb03ac 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context.py@@ -58,10 +58,13 @@ from repowise.core.persistence.crud import ()from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (+ CoverageFile,DecisionRecord,GitMetadata,GraphEdge,GraphNode,+ HealthFileMetric,+ HealthFinding,Page,Repository,WikiSymbol,@@ -80,9 +83,7 @@ from repowise.server.mcp_server._server import mcp_MIN_CALL_CONFIDENCE = 0.7-def _synthesize_structural_summary(- file_path: str, classes: list[str], functions: list[str]-) -> str:+def _synthesize_structural_summary(file_path: str, classes: list[str], functions: list[str]) -> str:"""Build a deterministic 1-line summary when no LLM-generated summary exists.Used in --index-only mode (no wiki pages) and as a fallback when an LLM@@ -226,7 +227,9 @@ async def _resolve_one_target("the PageRank threshold. Run `repowise update` to regenerate docs."),"exists_in_git": True,- "last_commit_at": meta.last_commit_at.isoformat() if meta.last_commit_at else None,+ "last_commit_at": meta.last_commit_at.isoformat()+ if meta.last_commit_at+ else None,"primary_owner": meta.primary_owner_name,"is_hotspot": meta.is_hotspot,}@@ -322,9 +325,7 @@ async def _resolve_one_target("hint": "Call with compact=False or include=['full_doc'] for the full list.",}if not docs.get("summary"):- docs["summary"] = _synthesize_structural_summary(- target, classes, functions- )+ docs["summary"] = _synthesize_structural_summary(target, classes, functions)else:docs["symbols"] = [{@@ -340,9 +341,7 @@ async def _resolve_one_target(# Structure summary block — quick scan of what's in the filetotal_loc = max((s.end_line for s in symbols), default=0)avg_complexity = (- sum(s.complexity_estimate for s in symbols) / len(symbols)- if symbols- else 0+ sum(s.complexity_estimate for s in symbols) / len(symbols) if symbols else 0)docs["structure"] = {"classes": classes,@@ -354,9 +353,7 @@ async def _resolve_one_target(# Fallback summary: if no Page (index-only mode) or page.summary# is empty, synthesize a deterministic one-liner from structure.if not docs.get("summary"):- docs["summary"] = _synthesize_structural_summary(- target, classes, functions- )+ docs["summary"] = _synthesize_structural_summary(target, classes, functions)# Importersres = await session.execute(select(GraphEdge).where(@@ -613,8 +610,13 @@ async def _resolve_one_target(want_callees = bool(include and "callees" in include)if want_callers or want_callees:await _resolve_call_graph(- session, repository, target, target_type, result_data,- want_callers=want_callers, want_callees=want_callees,+ session,+ repository,+ target,+ target_type,+ result_data,+ want_callers=want_callers,+ want_callees=want_callees,)# --- Metrics (replaces get_graph_metrics) ---@@ -625,6 +627,10 @@ async def _resolve_one_target(if include and "community" in include:await _resolve_community(session, repository, target, result_data)+ # --- Code health (Phase 2) ---+ if include and "health" in include:+ await _resolve_health(session, repository, target, target_type, result_data)+return result_data@@ -684,16 +690,18 @@ async def _resolve_call_graph(direction = "callees"edges = await get_graph_edges_for_node(- session, repo_id, node.node_id,- direction=direction, edge_types=["calls", "extends", "implements"],+ session,+ repo_id,+ node.node_id,+ direction=direction,+ edge_types=["calls", "extends", "implements"],limit=limit,)# Hydrate other nodes- other_ids = list({- e.source_node_id if e.target_node_id == node.node_id else e.target_node_id- for e in edges- })+ other_ids = list(+ {e.source_node_id if e.target_node_id == node.node_id else e.target_node_id for e in edges}+ )node_map = await get_graph_nodes_by_ids(session, repo_id, other_ids)callers: list[dict[str, Any]] = []@@ -710,9 +718,13 @@ async def _resolve_call_graph(entry: dict[str, Any] = {"symbol_id": other_id,- "name": other_node.name if other_node else (other_id.split("::")[-1] if "::" in other_id else other_id),+ "name": other_node.name+ if other_node+ else (other_id.split("::")[-1] if "::" in other_id else other_id),"kind": other_node.kind if other_node else None,- "file": other_node.file_path if other_node else (other_id.split("::")[0] if "::" in other_id else other_id),+ "file": other_node.file_path+ if other_node+ else (other_id.split("::")[0] if "::" in other_id else other_id),"confidence": e.confidence,"edge_type": e.edge_type,}@@ -813,11 +825,13 @@ async def _resolve_community(nlabel = nmeta.get("label", "")except (json.JSONDecodeError, TypeError):pass- neighbors.append({- "id": nid,- "label": nlabel or f"cluster_{nid}",- "cross_edges": ce["edge_count"],- })+ neighbors.append(+ {+ "id": nid,+ "label": nlabel or f"cluster_{nid}",+ "cross_edges": ce["edge_count"],+ }+ )result_data["community"] = {"id": node.community_id,@@ -828,6 +842,104 @@ async def _resolve_community(}+async def _resolve_health(+ session: AsyncSession,+ repository: Repository,+ target: str,+ target_type: str,+ result_data: dict[str, Any],+) -> None:+ """Attach per-file health metric + top 2 biomarkers + coverage row.++ Only meaningful for *file* targets. For symbol targets we resolve the+ enclosing file path via the already-computed ``file_path_for_git`` is+ not available here — we fall back to ``target`` when ``target_type``+ is ``"file"`` and otherwise inspect the target string for a+ ``"path::symbol"`` separator.+ """+ file_path: str | None+ if target_type == "file":+ file_path = target+ elif "::" in target:+ file_path = target.split("::", 1)[0]+ else:+ file_path = None++ if not file_path:+ result_data["health"] = None+ return++ repo_id = repository.id+ metric = (+ await session.execute(+ select(HealthFileMetric).where(+ HealthFileMetric.repository_id == repo_id,+ HealthFileMetric.file_path == file_path,+ )+ )+ ).scalar_one_or_none()++ if metric is None:+ result_data["health"] = None+ return++ findings_res = await session.execute(+ select(HealthFinding)+ .where(+ HealthFinding.repository_id == repo_id,+ HealthFinding.file_path == file_path,+ HealthFinding.status == "open",+ )+ .order_by(HealthFinding.health_impact.desc())+ .limit(2)+ )+ from repowise.core.analysis.health.suggestions import suggestion_for++ top_biomarkers = [+ {+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ "function_name": f.function_name,+ "impact": round(f.health_impact, 2),+ "suggestion": suggestion_for(f.biomarker_type),+ }+ for f in findings_res.scalars().all()+ ]++ coverage_row = (+ await session.execute(+ select(CoverageFile).where(+ CoverageFile.repository_id == repo_id,+ CoverageFile.file_path == file_path,+ )+ )+ ).scalar_one_or_none()++ health: dict[str, Any] = {+ "score": round(metric.score, 2),+ "max_ccn": metric.max_ccn,+ "max_nesting": metric.max_nesting,+ "nloc": metric.nloc,+ "has_test_file": metric.has_test_file,+ "module": metric.module,+ "duplication_pct": metric.duplication_pct,+ "top_biomarkers": top_biomarkers,+ }+ if coverage_row is not None:+ health["coverage"] = {+ "source_format": coverage_row.source_format,+ "line_coverage_pct": coverage_row.line_coverage_pct,+ "branch_coverage_pct": coverage_row.branch_coverage_pct,+ "total_coverable_lines": coverage_row.total_coverable_lines,+ }+ elif metric.line_coverage_pct is not None:+ health["coverage"] = {+ "line_coverage_pct": metric.line_coverage_pct,+ "branch_coverage_pct": metric.branch_coverage_pct,+ }+ result_data["health"] = health++def _estimate_tokens(obj: Any) -> int:"""Cheap upper-bound token estimate for an arbitrary JSON-serialisable object.@@ -863,8 +975,14 @@ def _symbol_priority(sym: dict[str, Any], query_terms: set[str]) -> tuple[int, ifuzzy = 1 if any(t and t in name for t in query_terms) else 0kind = (sym.get("kind") or "").lower()kind_rank = {- "class": 3, "interface": 3, "struct": 3, "trait": 3, "type": 3, "enum": 3,- "function": 2, "method": 2,+ "class": 3,+ "interface": 3,+ "struct": 3,+ "trait": 3,+ "type": 3,+ "enum": 3,+ "function": 2,+ "method": 2,}.get(kind, 1)centrality = int((sym.get("pagerank") or sym.get("centrality") or 0) * 1000)return (exact * 10 + fuzzy * 5 + kind_rank, centrality, -len(json.dumps(sym, default=str)))@@ -1010,9 +1128,7 @@ def _truncate_to_budget("token_budget": _TOKEN_BUDGET,"final_chars": _size(),"dropped_targets": result["dropped_targets"],- "dropped_symbol_counts": {- k: len(v) for k, v in result["dropped_symbols"].items()- },+ "dropped_symbol_counts": {k: len(v) for k, v in result["dropped_symbols"].items()},},)return result@@ -1067,6 +1183,7 @@ async def get_context(include_set = set(include) if include else {"docs", "freshness"}import time as _time+_t0 = _time.perf_counter()async with get_session(ctx.session_factory) as session:repository = await _get_repo(session)@@ -1074,7 +1191,11 @@ async def get_context(results = await asyncio.gather(*[_resolve_one_target(- session, repository, t, include_set, compact,+ session,+ repository,+ t,+ include_set,+ compact,)for t in targets]@@ -1106,12 +1227,8 @@ async def get_context(# Contract links (Phase 4)if enricher.has_contract_data:- provider_links = enricher.get_contract_links_as_provider(- ctx.alias, target_key- )- consumer_links = enricher.get_contract_links_as_consumer(- ctx.alias, target_key- )+ provider_links = enricher.get_contract_links_as_provider(ctx.alias, target_key)+ consumer_links = enricher.get_contract_links_as_consumer(ctx.alias, target_key)if provider_links or consumer_links:contracts: dict[str, Any] = {}if provider_links:diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pynew file mode 100644index 000000000..de7910811--- /dev/null+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -0,0 +1,301 @@+"""MCP tool: get_health — code-health biomarkers and per-file scores."""++from __future__ import annotations++import json+from typing import Any++from sqlalchemy import select++from repowise.core.analysis.health.suggestions import suggestion_for+from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis+from repowise.core.persistence.crud import (+ get_coverage_summary,+ list_health_snapshots,+ load_coverage_for_repo,+)+from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import HealthFileMetric, HealthFinding+from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context+from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.mcp_server._server import mcp+++def _serialize_finding(f: HealthFinding) -> dict[str, Any]:+ try:+ details = json.loads(f.details_json) if f.details_json else {}+ except Exception:+ details = {}+ return {+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ "file_path": f.file_path,+ "function_name": f.function_name,+ "line_start": f.line_start,+ "line_end": f.line_end,+ "health_impact": round(f.health_impact, 3),+ "reason": f.reason,+ "details": details,+ "status": f.status,+ }+++def _serialize_metric(m: HealthFileMetric) -> dict[str, Any]:+ return {+ "file_path": m.file_path,+ "score": round(m.score, 2),+ "max_ccn": m.max_ccn,+ "max_nesting": m.max_nesting,+ "nloc": m.nloc,+ "has_test_file": m.has_test_file,+ "line_coverage_pct": m.line_coverage_pct,+ "branch_coverage_pct": m.branch_coverage_pct,+ "module": m.module,+ }+++def _serialize_coverage_row(row: Any) -> dict[str, Any]:+ try:+ covered = json.loads(row.covered_lines_json) if row.covered_lines_json else []+ except Exception:+ covered = []+ return {+ "file_path": row.file_path,+ "source_format": row.source_format,+ "line_coverage_pct": row.line_coverage_pct,+ "branch_coverage_pct": row.branch_coverage_pct,+ "covered_lines": covered,+ "total_coverable_lines": row.total_coverable_lines,+ "ingested_at": row.ingested_at.isoformat() if row.ingested_at else None,+ "ingested_commit_sha": row.ingested_commit_sha,+ }+++def _module_rollups(metrics: list[HealthFileMetric]) -> list[dict[str, Any]]:+ """NLOC-weighted module rollups derived from ``HealthFileMetric.module``.++ One row per module; ``None`` modules are dropped. Sorted by health+ ascending so the worst modules surface first — matches the per-file+ ordering and what the dashboard already expects.+ """+ buckets: dict[str, list[HealthFileMetric]] = {}+ for m in metrics:+ if m.module:+ buckets.setdefault(m.module, []).append(m)+ out: list[dict[str, Any]] = []+ for name, rows in buckets.items():+ total_nloc = sum(max(r.nloc, 1) for r in rows)+ if total_nloc:+ avg = sum(r.score * max(r.nloc, 1) for r in rows) / total_nloc+ else:+ avg = sum(r.score for r in rows) / len(rows)+ worst = min(rows, key=lambda r: r.score)+ out.append(+ {+ "module": name,+ "file_count": len(rows),+ "nloc": sum(r.nloc for r in rows),+ "average_health": round(avg, 2),+ "worst_performer_path": worst.file_path,+ "worst_performer_score": round(worst.score, 2),+ }+ )+ out.sort(key=lambda r: r["average_health"])+ return out+++def _compute_kpis(metrics: list[HealthFileMetric]) -> dict[str, Any]:+ if not metrics:+ return {+ "file_count": 0,+ "average_health": 10.0,+ "worst_performer_path": None,+ "worst_performer_score": None,+ }+ total_nloc = sum(max(m.nloc, 1) for m in metrics)+ avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc+ worst = min(metrics, key=lambda r: r.score)+ return {+ "file_count": len(metrics),+ "average_health": round(avg, 2),+ "worst_performer_path": worst.file_path,+ "worst_performer_score": round(worst.score, 2),+ }+++async def get_health(+ targets: list[str] | None = None,+ include: list[str] | None = None,+ repo: str | None = None,+ limit: int = 20,+) -> dict:+ """Code-health biomarkers and per-file scores.++ Dashboard mode (no ``targets``) returns repo-level KPIs + the+ lowest-scoring files. Targeted mode returns per-file findings and+ metrics for each path in ``targets``.++ Biomarkers in v1: ``brain_method``, ``nested_complexity``,+ ``complex_method``. Phase 2 adds coverage biomarkers; Phase 3 adds+ duplication + organizational biomarkers.++ Args:+ targets: List of file paths. Empty → dashboard mode.+ include: Optional flags. ``"biomarkers"`` always returns findings;+ ``"coverage"`` will surface coverage data when available+ (Phase 2).+ repo: Repo alias / id / path.+ limit: Max rows in the lowest-scoring file list (capped at 50).+ """+ limit = min(max(limit, 1), 50)+ include_set = set(include or [])++ # Split ``module:foo`` targets out of the path list. A target that+ # matches one or more modules is expanded into the set of files+ # belonging to those modules.+ raw_targets = list(targets or [])+ module_targets = [t.split(":", 1)[1] for t in raw_targets if t.startswith("module:")]+ file_targets = [t for t in raw_targets if not t.startswith("module:")]++ ctx = await _resolve_repo_context(repo)+ async with get_session(ctx.session_factory) as session:+ repository = await _get_repo(session, repo)++ all_metrics_q = select(HealthFileMetric).where(+ HealthFileMetric.repository_id == repository.id+ )+ all_metrics = list((await session.execute(all_metrics_q)).scalars().all())++ if module_targets:+ module_set = set(module_targets)+ for m in all_metrics:+ if m.module in module_set:+ file_targets.append(m.file_path)+ file_targets = sorted(set(file_targets))++ effective_targets = file_targets if (raw_targets) else []++ if effective_targets:+ metric_rows = [+ m+ for m in sorted(all_metrics, key=lambda r: r.score)+ if m.file_path in set(effective_targets)+ ]+ else:+ metric_rows = sorted(all_metrics, key=lambda r: r.score)++ finding_q = select(HealthFinding).where(+ HealthFinding.repository_id == repository.id,+ HealthFinding.status == "open",+ )+ if effective_targets:+ finding_q = finding_q.where(HealthFinding.file_path.in_(effective_targets))+ finding_q = finding_q.order_by(HealthFinding.health_impact.desc())+ finding_rows = list((await session.execute(finding_q)).scalars().all())++ coverage_rows: list[Any] = []+ coverage_summary: dict[str, Any] = {}+ if "coverage" in include_set:+ coverage_rows = await load_coverage_for_repo(+ session, repository.id, file_paths=list(targets) if targets else None+ )+ coverage_summary = await get_coverage_summary(session, repository.id)++ snapshots: list[Any] = []+ if "trend" in include_set:+ snapshots = await list_health_snapshots(session, repository.id, limit=20)++ kpis = _compute_kpis(metric_rows if effective_targets else all_metrics)++ if effective_targets:+ result: dict[str, Any] = {+ "mode": "targets",+ "targets": raw_targets,+ "metrics": [_serialize_metric(m) for m in metric_rows],+ "findings": [_serialize_finding(f) for f in finding_rows],+ }+ if module_targets:+ scoped = [m for m in all_metrics if m.module in set(module_targets)]+ result["modules"] = _module_rollups(scoped)+ else:+ # Dashboard mode — top-N worst files + headline findings + the+ # per-module rollup so the overview page doesn't need a second+ # round-trip.+ result = {+ "mode": "dashboard",+ "kpis": kpis,+ "worst_files": [_serialize_metric(m) for m in metric_rows[:limit]],+ "top_findings": [_serialize_finding(f) for f in finding_rows[:limit]],+ "modules": _module_rollups(all_metrics),+ }++ if "biomarkers" in include_set and "findings" not in result:+ result["findings"] = [_serialize_finding(f) for f in finding_rows]++ if "refactoring" in include_set:+ # Attach deterministic refactoring suggestions to every finding+ # in the response. Surfaces on the dashboard cards as well so+ # both consumers stay in sync.+ for field in ("findings", "top_findings"):+ rows = result.get(field)+ if rows:+ result[field] = [+ {**row, "suggestion": suggestion_for(row.get("biomarker_type", ""))}+ for row in rows+ ]+ if "findings" not in result and "top_findings" not in result:+ result["findings"] = [+ {+ **_serialize_finding(f),+ "suggestion": suggestion_for(f.biomarker_type),+ }+ for f in finding_rows+ ]++ if "trend" in include_set:+ summary = diff_snapshots(snapshots)+ result["trend"] = {+ "current_hotspot_health": summary.current_hotspot_health,+ "current_average_health": summary.current_average_health,+ "previous_hotspot_health": summary.previous_hotspot_health,+ "previous_average_health": summary.previous_average_health,+ "hotspot_delta": summary.hotspot_delta,+ "average_delta": summary.average_delta,+ "alerts": [+ {+ "kind": a.kind,+ "metric": a.metric,+ "current": a.current,+ "baseline": a.baseline,+ "delta": a.delta,+ "message": a.message,+ }+ for a in summary.alerts+ ],+ "recent": recent_kpis(snapshots, limit=10),+ }++ if "coverage" in include_set:+ # Drop the bulky covered-lines arrays from dashboard mode; full+ # detail is available in targeted mode.+ if targets:+ coverage_payload = [_serialize_coverage_row(r) for r in coverage_rows]+ else:+ coverage_payload = [+ {k: v for k, v in _serialize_coverage_row(r).items() if k != "covered_lines"}+ for r in coverage_rows[:limit]+ ]+ # ``ingested_at`` is a datetime on the summary too — coerce.+ if coverage_summary.get("ingested_at") is not None:+ coverage_summary = {+ **coverage_summary,+ "ingested_at": coverage_summary["ingested_at"].isoformat(),+ }+ result["coverage"] = {+ "summary": coverage_summary,+ "files": coverage_payload,+ }++ result["_meta"] = _build_meta(repository=repository)+ return resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex f6f6be8fc..edba58504 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -8,6 +8,10 @@ from typing import Anyfrom sqlalchemy import func as sa_func, select+from repowise.core.persistence.crud import (+ get_health_metrics as _get_health_metrics,+ get_health_summary as _get_health_summary,+)from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (GitMetadata,@@ -61,7 +65,9 @@ async def _workspace_overview() -> dict:# File and symbol countsfile_count_res = await session.execute(- select(sa_func.count()).select_from(GraphNode).where(+ select(sa_func.count())+ .select_from(GraphNode)+ .where(GraphNode.repository_id == repo_obj.id,GraphNode.node_type == "file",)@@ -69,7 +75,9 @@ async def _workspace_overview() -> dict:file_count = file_count_res.scalar_one()symbol_count_res = await session.execute(- select(sa_func.count()).select_from(GraphNode).where(+ select(sa_func.count())+ .select_from(GraphNode)+ .where(GraphNode.repository_id == repo_obj.id,GraphNode.node_type == "symbol",)@@ -79,19 +87,18 @@ async def _workspace_overview() -> dict:total_files += file_counttotal_symbols += symbol_count- is_default = (- registry is not None- and ctx.alias == registry.get_default_alias()- )+ is_default = registry is not None and ctx.alias == registry.get_default_alias()- repos_info.append({- "alias": ctx.alias,- "path": str(ctx.path),- "summary": summary,- "file_count": file_count,- "symbol_count": symbol_count,- "is_default": is_default,- })+ repos_info.append(+ {+ "alias": ctx.alias,+ "path": str(ctx.path),+ "summary": summary,+ "file_count": file_count,+ "symbol_count": symbol_count,+ "is_default": is_default,+ }+ )# Cross-repo topology (Phase 3 + 4)cross_repo_topology: dict[str, Any] = {}@@ -104,9 +111,7 @@ async def _workspace_overview() -> dict:for repo_info in repos_info:deps = enricher.get_package_deps(repo_info["alias"])if deps:- repo_info["depends_on"] = sorted(- set(d["target_repo"] for d in deps)- )+ repo_info["depends_on"] = sorted(set(d["target_repo"] for d in deps))result: dict[str, Any] = {"workspace": True,@@ -115,10 +120,7 @@ async def _workspace_overview() -> dict:"total_files": total_files,"total_symbols": total_symbols,"repos": repos_info,- "hint": (- "Use repo='<alias>' to query a specific repo. "- "Omit repo to use the default."- ),+ "hint": ("Use repo='<alias>' to query a specific repo. Omit repo to use the default."),}if cross_repo_topology:result["cross_repo_topology"] = cross_repo_topology@@ -138,9 +140,7 @@ def _build_workspace_footer() -> dict | None:return Nonedefault_alias = registry.get_default_alias()- other_repos = [- a for a in registry.get_all_aliases() if a != default_alias- ]+ other_repos = [a for a in registry.get_all_aliases() if a != default_alias]if not other_repos:return None@@ -308,8 +308,12 @@ async def get_overview(repo: str | None = None) -> dict:# knowledge_silos: files where primary owner has > 80% ownership# Filter out boilerplate (migrations, __init__.py, config, lock files)silo_exclude_patterns = (- "alembic/versions/", "__init__.py", "migrations/",- ".lock", "package-lock", "conftest.py",+ "alembic/versions/",+ "__init__.py",+ "migrations/",+ ".lock",+ "package-lock",+ "conftest.py",)knowledge_silos = [g.file_path@@ -352,9 +356,7 @@ async def get_overview(repo: str | None = None) -> dict:# Sort communities by size descending, take top 10# Skip communities with generic/unhelpful labelsgeneric_labels = {"packages", "src", "lib", "core", "app", ""}- for cid, members in sorted(- community_groups.items(), key=lambda x: -len(x[1])- ):+ for cid, members in sorted(community_groups.items(), key=lambda x: -len(x[1])):if len(community_summary) >= 10:breaklabel = ""@@ -385,12 +387,14 @@ async def get_overview(repo: str | None = None) -> dict:else:display_label = f"cluster_{cid}"- community_summary.append({- "id": cid,- "label": display_label,- "size": len(members),- "cohesion": round(cohesion, 3),- })+ community_summary.append(+ {+ "id": cid,+ "label": display_label,+ "size": len(members),+ "cohesion": round(cohesion, 3),+ }+ )# Older indexes persisted titles like "Repository Overview: repo" because# repo_name was not passed through to generate_repo_overview. Substitute@@ -402,9 +406,35 @@ async def get_overview(repo: str | None = None) -> dict:)else:title = repository.name+ # Code-health KPIs — three headline numbers for the architecture+ # summary. Falls back to defaults (avg 10/10, no worst file) when+ # health hasn't been run on this repo yet.+ code_health: dict[str, Any] = {}+ try:+ health_summary = await _get_health_summary(session, repository.id)+ metrics_rows = await _get_health_metrics(session, repository.id)+ if metrics_rows:+ # Hotspot health: NLOC-weighted avg over the top-25% files+ # by NLOC, matching the dashboard KPI definition.+ sorted_by_nloc = sorted(metrics_rows, key=lambda m: m.nloc or 0, reverse=True)+ top_q = sorted_by_nloc[: max(1, len(sorted_by_nloc) // 4)]+ tot = sum(max(m.nloc, 1) for m in top_q)+ hotspot_avg = sum(m.score * max(m.nloc, 1) for m in top_q) / tot if tot else 10.0+ code_health = {+ "average_health": health_summary["average_health"],+ "hotspot_health": round(hotspot_avg, 2),+ "worst_performer_path": health_summary["worst_performer_path"],+ "worst_performer_score": health_summary["worst_performer_score"],+ "open_findings": health_summary["open_findings"],+ "file_count": health_summary["file_count"],+ }+ except Exception:+ code_health = {}+result = {"title": title,"content_md": overview_page.content if overview_page else "No overview generated yet.",+ "code_health": code_health,"key_modules": [{"name": p.title,diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk.pyindex 7b0f01cb9..75a7c1838 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk.py@@ -8,11 +8,9 @@ import jsonimport refrom typing import Any-from sqlalchemy import select+from sqlalchemy import select, textfrom sqlalchemy.ext.asyncio import AsyncSession-from sqlalchemy import text-from repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import (GitMetadata,@@ -187,7 +185,7 @@ async def _get_security_signals({"kind": r[0], "severity": r[1], "snippet": r[2]}for r in rows.all()]- except Exception: # noqa: BLE001 — table may not exist pre-migration+ except Exception:return []@@ -521,6 +519,58 @@ async def get_risk(f"{r['dependents_count']} dependents",)+ # ---- Code-health enrichment --------------------------------------------+ # Attach per-file health_score + top_biomarkers (up to 3) drawn from the+ # health tables. Conservative: missing data → no field, never invented.+ try:+ from repowise.core.persistence.models import HealthFileMetric, HealthFinding++ target_paths = [r["target"] for r in results if r.get("target")]+ if target_paths:+ async with get_session(ctx.session_factory) as _h_session:+ m_res = await _h_session.execute(+ select(HealthFileMetric).where(+ HealthFileMetric.repository_id == repo_id,+ HealthFileMetric.file_path.in_(target_paths),+ )+ )+ metric_map = {m.file_path: m for m in m_res.scalars().all()}++ f_res = await _h_session.execute(+ select(HealthFinding)+ .where(+ HealthFinding.repository_id == repo_id,+ HealthFinding.file_path.in_(target_paths),+ HealthFinding.status == "open",+ )+ .order_by(HealthFinding.health_impact.desc())+ )+ top_by_file: dict[str, list[dict]] = {}+ for f in f_res.scalars().all():+ lst = top_by_file.setdefault(f.file_path, [])+ if len(lst) >= 3:+ continue+ lst.append({+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ "function_name": f.function_name,+ "impact": round(f.health_impact, 2),+ })++ for r in results:+ path = r.get("target")+ m = metric_map.get(path)+ if m is not None:+ r["health_score"] = round(m.score, 2)+ if m.line_coverage_pct is not None:+ r["coverage_pct"] = round(m.line_coverage_pct, 2)+ if m.branch_coverage_pct is not None:+ r["branch_coverage_pct"] = round(m.branch_coverage_pct, 2)+ if path in top_by_file:+ r["top_biomarkers"] = top_by_file[path]+ except Exception:+ pass+response: dict = {"targets": {r["target"]: r for r in results},}diff --git a/packages/server/src/repowise/server/routers/code_health.py b/packages/server/src/repowise/server/routers/code_health.pynew file mode 100644index 000000000..125ca202b--- /dev/null+++ b/packages/server/src/repowise/server/routers/code_health.py@@ -0,0 +1,614 @@+"""/api/repos/{repo_id}/health/* — code-health endpoints.++Distinct from ``routers/health.py`` (liveness / Prometheus). All routes+here require API-key auth and operate on the ``health_findings`` /+``health_file_metrics`` tables.+"""++from __future__ import annotations++import json+import re+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Query+from pydantic import BaseModel, Field+from sqlalchemy.ext.asyncio import AsyncSession++from repowise.core.analysis.health.models import Severity+from repowise.core.analysis.health.scoring import (+ CATEGORY_CAPS,+ biomarker_category,+ severity_deduction,+)+from repowise.core.analysis.health.suggestions import suggestion_for as _suggestion_for+from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis+from repowise.core.persistence import crud+from repowise.server.deps import get_db_session, verify_api_key++router = APIRouter(+ tags=["code-health"],+ dependencies=[Depends(verify_api_key)],+)+++_SEVERITY_ORDER = {"low": 0, "medium": 1, "high": 2, "critical": 3}+++def _finding_to_dict(f: Any) -> dict:+ try:+ details = json.loads(f.details_json) if f.details_json else {}+ except Exception:+ details = {}+ return {+ "id": f.id,+ "file_path": f.file_path,+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ "function_name": f.function_name,+ "line_start": f.line_start,+ "line_end": f.line_end,+ "health_impact": round(f.health_impact, 3),+ "reason": f.reason,+ "details": details,+ "status": f.status,+ }+++def _metric_to_dict(m: Any) -> dict:+ return {+ "file_path": m.file_path,+ "score": round(m.score, 2),+ "max_ccn": m.max_ccn,+ "max_nesting": m.max_nesting,+ "nloc": m.nloc,+ "has_test_file": m.has_test_file,+ "line_coverage_pct": m.line_coverage_pct,+ "module": m.module,+ "duplication_pct": getattr(m, "duplication_pct", None),+ }+++# Strip the trailing " (N)" suffix that community detection appends to+# disambiguate same-named modules. The leak is harmless in the DB but+# noisy in the dashboard.+_MODULE_SUFFIX = re.compile(r"\s*\(\d+\)\s*$")+++def _clean_module(name: str) -> str:+ return _MODULE_SUFFIX.sub("", name).strip()+++def _module_rollups(metrics: list[Any]) -> list[dict]:+ """NLOC-weighted module rollups derived from ``HealthFileMetric.module``."""+ buckets: dict[str, list[Any]] = {}+ for m in metrics:+ if m.module:+ buckets.setdefault(_clean_module(m.module), []).append(m)+ rows: list[dict] = []+ for name, group in buckets.items():+ total_nloc = sum(max(r.nloc, 1) for r in group)+ avg = sum(r.score * max(r.nloc, 1) for r in group) / total_nloc if total_nloc else 10.0+ worst = min(group, key=lambda r: r.score)+ rows.append(+ {+ "module": name,+ "file_count": len(group),+ "nloc": sum(r.nloc for r in group),+ "average_health": round(avg, 2),+ "worst_performer_path": worst.file_path,+ "worst_performer_score": round(worst.score, 2),+ }+ )+ rows.sort(key=lambda r: r["average_health"])+ return rows+++def _severity_breakdown(findings: list[Any]) -> dict[str, int]:+ out = {"critical": 0, "high": 0, "medium": 0, "low": 0}+ for f in findings:+ s = (f.severity or "").lower()+ if s in out:+ out[s] += 1+ return out+++def _biomarker_breakdown(findings: list[Any]) -> list[dict]:+ """Per-biomarker counts split by severity, sorted by total."""+ by_type: dict[str, dict[str, int]] = {}+ for f in findings:+ b = f.biomarker_type+ sev = (f.severity or "").lower()+ bucket = by_type.setdefault(+ b, {"critical": 0, "high": 0, "medium": 0, "low": 0, "total": 0}+ )+ if sev in bucket:+ bucket[sev] += 1+ bucket["total"] += 1+ rows = [{"biomarker_type": b, **counts} for b, counts in by_type.items()]+ rows.sort(key=lambda r: r["total"], reverse=True)+ return rows++[email protected]("/api/repos/{repo_id}/health/overview")+async def health_overview(+ repo_id: str,+ limit: int = Query(20, ge=1, le=200),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """KPIs + lowest-scoring files + per-module rollup + meta."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ summary = await crud.get_health_summary(session, repo_id)+ metrics = await crud.get_health_metrics(session, repo_id)+ findings = await crud.get_health_findings(session, repo_id)+ snapshots = await crud.list_health_snapshots(session, repo_id)++ # Pull hotspot_health from the latest snapshot (KPIs aren't recomputed+ # on every overview hit — the snapshot is authoritative).+ hotspot_health: float | None = None+ last_indexed_at: str | None = None+ if snapshots:+ latest = snapshots[-1]+ hotspot_health = round(float(latest.hotspot_health), 2)+ last_indexed_at = latest.taken_at.isoformat() if latest.taken_at else None++ summary = {+ **summary,+ "hotspot_health": hotspot_health,+ "severity_breakdown": _severity_breakdown(findings),+ }++ return {+ "summary": summary,+ "files": [_metric_to_dict(m) for m in metrics[:limit]],+ "top_findings": [_finding_to_dict(f) for f in findings[:limit]],+ "modules": _module_rollups(metrics),+ "biomarkers": _biomarker_breakdown(findings),+ "meta": {+ "last_indexed_at": last_indexed_at,+ "head_commit": repo.head_commit,+ "snapshot_count": len(snapshots),+ },+ }++[email protected]("/api/repos/{repo_id}/health/modules")+async def health_modules(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """NLOC-weighted module rollups for the dashboard module section."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ metrics = await crud.get_health_metrics(session, repo_id)+ return {"modules": _module_rollups(metrics)}++[email protected]("/api/repos/{repo_id}/health/findings")+async def list_health_findings(+ repo_id: str,+ biomarker_type: str | None = Query(None),+ file_path: str | None = Query(None),+ min_severity: str | None = Query(None),+ limit: int = Query(100, ge=1, le=1000),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> list[dict]:+ findings = await crud.get_health_findings(+ session,+ repo_id,+ biomarker_type=biomarker_type,+ file_path=file_path,+ min_severity=min_severity,+ )+ return [_finding_to_dict(f) for f in findings[:limit]]+++_SORT_FIELDS = {+ "score",+ "max_ccn",+ "max_nesting",+ "nloc",+ "duplication_pct",+ "line_coverage_pct",+ "file_path",+}++[email protected]("/api/repos/{repo_id}/health/files")+async def list_health_files(+ repo_id: str,+ limit: int = Query(200, ge=1, le=2000),+ offset: int = Query(0, ge=0),+ sort: str = Query("score", description="Sort field"),+ order: str = Query("asc", pattern="^(asc|desc)$"),+ search: str | None = Query(None, description="Substring filter on file_path"),+ module: str | None = Query(None, description="Filter to a module prefix"),+ only_hotspots: bool = Query(False),+ only_untested: bool = Query(False),+ only_failing: bool = Query(False, description="score < 7"),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ if sort not in _SORT_FIELDS:+ sort = "score"+ metrics = await crud.get_health_metrics(session, repo_id)++ hotspot_paths: set[str] = set()+ if only_hotspots:+ git_meta = await crud.get_all_git_metadata(session, repo_id)+ hotspot_paths = {p for p, gm in git_meta.items() if getattr(gm, "is_hotspot", False)}++ def _keep(m: Any) -> bool:+ if search and search.lower() not in m.file_path.lower():+ return False+ if module and not m.file_path.startswith(module):+ return False+ if only_hotspots and m.file_path not in hotspot_paths:+ return False+ if only_untested and m.has_test_file:+ return False+ return not (only_failing and m.score >= 7)++ filtered = [m for m in metrics if _keep(m)]++ def _key(m: Any):+ v = getattr(m, sort, None)+ if v is None:+ return (1, 0) if order == "asc" else (0, 0)+ return (0, v) if order == "asc" else (0, -v if isinstance(v, (int, float)) else v)++ reverse = order == "desc" and sort == "file_path"+ if sort == "file_path":+ filtered.sort(key=lambda m: m.file_path, reverse=reverse)+ else:+ filtered.sort(key=_key, reverse=False)++ total = len(filtered)+ page = filtered[offset : offset + limit]+ return {+ "total": total,+ "offset": offset,+ "limit": limit,+ "files": [_metric_to_dict(m) for m in page],+ }+++def _score_breakdown_from_findings(findings: list[Any]) -> dict:+ """Recompute per-category deductions from open findings of one file.++ Mirrors ``scoring.score_file`` so the dashboard can show how a file's+ score was built up — even though the scoring math runs at index time,+ not at request time.+ """+ raw_per_cat: dict[str, list[tuple[Any, float]]] = {}+ for f in findings:+ sev = Severity(f.severity) if not isinstance(f.severity, Severity) else f.severity+ d = severity_deduction(sev)+ cat = biomarker_category(f.biomarker_type)+ raw_per_cat.setdefault(cat, []).append((f, d))++ categories: list[dict] = []+ total_deduction = 0.0+ for cat, cap in CATEGORY_CAPS.items():+ entries = raw_per_cat.get(cat, [])+ raw_sum = sum(d for _, d in entries)+ capped = min(raw_sum, cap)+ scale = (cap / raw_sum) if raw_sum > cap and raw_sum > 0 else 1.0+ categories.append(+ {+ "category": cat,+ "cap": round(cap, 2),+ "raw_deduction": round(raw_sum, 3),+ "applied_deduction": round(capped, 3),+ "capped": raw_sum > cap,+ "finding_count": len(entries),+ "findings": [+ {+ "id": f.id,+ "biomarker_type": f.biomarker_type,+ "severity": f.severity,+ "raw_impact": round(d, 3),+ "applied_impact": round(d * scale, 3),+ "function_name": f.function_name,+ "reason": f.reason,+ }+ for f, d in entries+ ],+ }+ )+ total_deduction += capped+ score = max(1.0, min(10.0, 10.0 - total_deduction))+ return {+ "score": round(score, 2),+ "total_deduction": round(total_deduction, 3),+ "categories": categories,+ }++[email protected]("/api/repos/{repo_id}/health/files/breakdown")+async def file_score_breakdown(+ repo_id: str,+ file_path: str = Query(..., description="File path to break down"),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ metrics = await crud.get_health_metrics(session, repo_id, file_paths=[file_path])+ metric = metrics[0] if metrics else None+ findings = await crud.get_health_findings(session, repo_id, file_path=file_path)+ breakdown = _score_breakdown_from_findings(findings)+ return {+ "file_path": file_path,+ "metric": _metric_to_dict(metric) if metric else None,+ "breakdown": breakdown,+ "findings": [_finding_to_dict(f) for f in findings],+ "suggestions": {+ b: _suggestion_for(b) for b in {f.biomarker_type for f in findings}+ },+ }++[email protected]("/api/repos/{repo_id}/health/trend")+async def health_trend(+ repo_id: str,+ limit: int = Query(20, ge=1, le=50),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")+ snapshots = await crud.list_health_snapshots(session, repo_id)+ summary = diff_snapshots(snapshots)++ # Per-file delta from the last two snapshots.+ file_deltas: list[dict] = []+ if len(snapshots) >= 2:+ try:+ prev = json.loads(snapshots[-2].per_file_scores_json or "{}")+ cur = json.loads(snapshots[-1].per_file_scores_json or "{}")+ except Exception:+ prev, cur = {}, {}+ all_paths = set(prev) | set(cur)+ for p in all_paths:+ before = prev.get(p)+ after = cur.get(p)+ if before is None or after is None:+ continue+ d = round(float(after) - float(before), 2)+ if d == 0:+ continue+ file_deltas.append(+ {"file_path": p, "before": before, "after": after, "delta": d}+ )+ file_deltas.sort(key=lambda r: r["delta"])++ return {+ "history": recent_kpis(snapshots, limit=limit),+ "summary": {+ "current_hotspot_health": summary.current_hotspot_health,+ "current_average_health": summary.current_average_health,+ "previous_hotspot_health": summary.previous_hotspot_health,+ "previous_average_health": summary.previous_average_health,+ "hotspot_delta": summary.hotspot_delta,+ "average_delta": summary.average_delta,+ },+ "alerts": [+ {+ "kind": a.kind,+ "metric": a.metric,+ "current": a.current,+ "baseline": a.baseline,+ "delta": a.delta,+ "message": a.message,+ }+ for a in summary.alerts+ ],+ "file_deltas": file_deltas[:50],+ "snapshot_count": len(snapshots),+ }+++class FindingStatusUpdate(BaseModel):+ status: str = Field(..., description="open | acknowledged | resolved | false_positive")+++_ALLOWED_STATUSES = {"open", "acknowledged", "resolved", "false_positive"}++[email protected]("/api/repos/{repo_id}/health/findings/{finding_id}")+async def update_finding_status(+ repo_id: str,+ finding_id: str,+ payload: FindingStatusUpdate,+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ if payload.status not in _ALLOWED_STATUSES:+ raise HTTPException(status_code=400, detail=f"status must be one of {sorted(_ALLOWED_STATUSES)}")+ f = await crud.update_health_finding_status(session, finding_id, payload.status)+ if f is None:+ raise HTTPException(status_code=404, detail="Finding not found")+ await session.commit()+ return _finding_to_dict(f)+++def _coverage_row_to_dict(row: Any, *, include_covered_lines: bool = False) -> dict:+ out: dict[str, Any] = {+ "file_path": row.file_path,+ "source_format": row.source_format,+ "line_coverage_pct": row.line_coverage_pct,+ "branch_coverage_pct": row.branch_coverage_pct,+ "total_coverable_lines": row.total_coverable_lines,+ "ingested_at": row.ingested_at.isoformat() if row.ingested_at else None,+ "ingested_commit_sha": row.ingested_commit_sha,+ }+ if include_covered_lines:+ try:+ out["covered_lines"] = json.loads(row.covered_lines_json or "[]")+ except Exception:+ out["covered_lines"] = []+ return out++[email protected]("/api/repos/{repo_id}/health/coverage")+async def health_coverage(+ repo_id: str,+ file_path: str | None = Query(None),+ limit: int = Query(500, ge=1, le=5000),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """Coverage summary + per-file rows.++ Pass ``file_path`` to fetch a single file's full covered-line set.+ Without ``file_path`` we return the summary + a list of per-file+ rows trimmed by ``limit`` (covered_lines arrays stripped).+ """+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ summary = await crud.get_coverage_summary(session, repo_id)+ if summary.get("ingested_at") is not None:+ summary = {**summary, "ingested_at": summary["ingested_at"].isoformat()}+ rows = await crud.load_coverage_for_repo(+ session, repo_id, file_paths=[file_path] if file_path else None+ )+ metrics = await crud.get_health_metrics(session, repo_id)+ metric_by_path = {m.file_path: m for m in metrics}++ if file_path:+ files = [_coverage_row_to_dict(r, include_covered_lines=True) for r in rows]+ else:+ rows_sorted = sorted(rows, key=lambda r: r.line_coverage_pct)+ files = [_coverage_row_to_dict(r) for r in rows_sorted[:limit]]+ # Attach per-file health score so the UI can render a coverage+ # x score matrix without a second request.+ for f in files:+ m = metric_by_path.get(f["file_path"])+ if m is not None:+ f["health_score"] = round(m.score, 2)+ f["nloc"] = m.nloc++ # Aggregate by directory for module-level bars (cheap; one pass).+ modules: dict[str, dict[str, Any]] = {}+ for r in rows:+ mod = r.file_path.rsplit("/", 1)[0] if "/" in r.file_path else "(root)"+ bucket = modules.setdefault(mod, {"covered": 0, "total": 0, "files": 0})+ bucket["files"] += 1+ bucket["total"] += r.total_coverable_lines+ bucket["covered"] += round(r.line_coverage_pct / 100.0 * r.total_coverable_lines)+ module_rows = [+ {+ "module": name,+ "files": v["files"],+ "covered_lines": v["covered"],+ "total_lines": v["total"],+ "line_coverage_pct": (+ round(v["covered"] / v["total"] * 100.0, 2) if v["total"] else 0.0+ ),+ }+ for name, v in modules.items()+ ]+ module_rows.sort(key=lambda x: x["line_coverage_pct"])++ return {+ "summary": summary,+ "files": files,+ "modules": module_rows[:limit],+ }+++_EFFORT_BUCKETS: tuple[tuple[int, str], ...] = (+ (40, "S"),+ (150, "M"),+ (400, "L"),+)+++def _effort_for_nloc(nloc: int) -> str:+ for ceiling, label in _EFFORT_BUCKETS:+ if nloc <= ceiling:+ return label+ return "XL"++[email protected]("/api/repos/{repo_id}/health/refactoring-targets")+async def refactoring_targets(+ repo_id: str,+ limit: int = Query(200, ge=1, le=500),+ module: str | None = Query(None, description="Filter to files in this module path"),+ biomarker: str | None = Query(None, description="Filter to one biomarker type"),+ min_severity: str | None = Query(None),+ max_effort: str | None = Query(None, description="S | M | L | XL"),+ sort: str = Query("impact_per_effort", pattern="^(impact_per_effort|total_impact|score|finding_count)$"),+ session: AsyncSession = Depends(get_db_session), # noqa: B008+) -> dict:+ """Refactoring candidates ranked by impact / effort."""+ repo = await crud.get_repository(session, repo_id)+ if repo is None:+ raise HTTPException(status_code=404, detail="Repository not found")++ metrics = await crud.get_health_metrics(session, repo_id)+ metric_by_path = {m.file_path: m for m in metrics}+ findings = await crud.get_health_findings(session, repo_id)++ by_file: dict[str, list[Any]] = {}+ for f in findings:+ if biomarker and f.biomarker_type != biomarker:+ continue+ if min_severity:+ order = _SEVERITY_ORDER+ if order.get(f.severity, 0) < order.get(min_severity, 0):+ continue+ by_file.setdefault(f.file_path, []).append(f)++ effort_rank = {"S": 1, "M": 2, "L": 3, "XL": 5}+ max_effort_rank = effort_rank.get(max_effort or "", 99)++ targets: list[dict] = []+ for file_path, fs in by_file.items():+ if module and not file_path.startswith(module):+ continue+ m = metric_by_path.get(file_path)+ nloc = m.nloc if m is not None else 0+ score = m.score if m is not None else 10.0+ primary = max(fs, key=lambda x: x.health_impact)+ total_impact = round(sum(x.health_impact for x in fs), 3)+ effort_bucket = _effort_for_nloc(nloc)+ if effort_rank[effort_bucket] > max_effort_rank:+ continue+ weight = effort_rank[effort_bucket]+ ratio = round(total_impact / weight, 3)+ targets.append(+ {+ "file_path": file_path,+ "score": round(score, 2),+ "nloc": nloc,+ "module": _clean_module(m.module) if (m and m.module) else None,+ "primary_biomarker": primary.biomarker_type,+ "primary_severity": primary.severity,+ "primary_reason": primary.reason,+ "primary_function": primary.function_name,+ "primary_line_start": primary.line_start,+ "primary_line_end": primary.line_end,+ "primary_suggestion": _suggestion_for(primary.biomarker_type),+ "primary_finding_id": primary.id,+ "total_impact": total_impact,+ "finding_count": len(fs),+ "biomarkers": sorted({x.biomarker_type for x in fs}),+ "effort_bucket": effort_bucket,+ "impact_per_effort": ratio,+ "all_findings": [_finding_to_dict(f) for f in fs],+ }+ )++ sort_key_map = {+ "impact_per_effort": lambda t: (-t["impact_per_effort"], -t["total_impact"]),+ "total_impact": lambda t: -t["total_impact"],+ "score": lambda t: t["score"],+ "finding_count": lambda t: -t["finding_count"],+ }+ targets.sort(key=sort_key_map[sort])+ return {"targets": targets[:limit], "total": len(targets)}diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 27573ef37..c4b2c50d5 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -24,6 +24,8 @@"./git/*": "./src/git/*.tsx","./dead-code": "./src/dead-code/index.ts","./dead-code/*": "./src/dead-code/*.tsx",+ "./health": "./src/health/index.ts",+ "./health/*": "./src/health/*.tsx","./decisions": "./src/decisions/index.ts","./decisions/*": "./src/decisions/*.tsx","./docs": "./src/docs/index.ts",diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsnew file mode 100644index 000000000..5eac93364--- /dev/null+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -0,0 +1,281 @@+/**+ * Build high-quality AI-agent prompts for the code-health surface.+ *+ * Two prompt kinds today:+ * - `buildAiPrompt(target)` — refactor one file: every biomarker hit,+ * line range, score deduction, and constraint needed to act.+ * - `buildCoverageAiPrompt(row)` — add tests for one uncovered or+ * under-covered file.+ *+ * Both are deliberately structured (role → file → state → tasks →+ * constraints → completion contract) so the agent doesn't have to ask+ * follow-up questions before making its first move.+ */++import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";+import type { RefactoringTarget } from "./refactoring-card";++export type AiPromptFlavor = "generic" | "claude-code" | "cursor";++const FLAVOR_PREAMBLE: Record<AiPromptFlavor, string> = {+ generic:+ "You are a senior engineer working on one file in this repository. The findings below were detected by a static analyzer — treat them as **leads, not ground truth**. Open the file, read its callers, tests, and neighbors, and verify each finding against the actual code before you act. If a finding is a false positive given the broader context, say so and skip it.",+ "claude-code":+ "You are Claude Code working in this repository. The findings below were detected by a static analyzer — treat them as leads to investigate, not commands to execute. Use Read, Grep, and Glob to explore the file, its callers, its tests, and any related modules before planning edits. Verify each finding against the actual code; flag any that turn out to be false positives. Use TodoWrite for non-trivial steps.",+ cursor:+ "Work on the file referenced below. The findings below were detected by a static analyzer — treat them as leads, not ground truth. Use @file and @codebase to read the file, its callers, its tests, and neighboring modules before editing. Verify each finding against the real code; skip and call out any false positives.",+};++function bulletList(items: (string | null | undefined | false)[]): string {+ return items.filter(Boolean).map((s) => `- ${s}`).join("\n");+}++function effortHint(effort: RefactoringTarget["effort_bucket"]): string {+ switch (effort) {+ case "S":+ return "Small (≤40 NLOC) — should be doable in one focused pass.";+ case "M":+ return "Medium (≤150 NLOC) — plan 2–3 sub-steps before editing.";+ case "L":+ return "Large (≤400 NLOC) — break into a TODO list of sub-refactors first.";+ case "XL":+ return "Extra large (>400 NLOC) — propose a staged plan and confirm scope before editing.";+ }+}++// ─────────────────────────────────────────────────────────────────────+// Refactor prompt+// ─────────────────────────────────────────────────────────────────────++export interface BuildPromptOptions {+ target: RefactoringTarget;+ flavor?: AiPromptFlavor;+ repoName?: string;+}++export function buildAiPrompt({+ target,+ flavor = "generic",+ repoName,+}: BuildPromptOptions): string {+ const t = target;+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";++ const findings = (+ t.all_findings && t.all_findings.length > 0+ ? t.all_findings+ : [+ {+ id: t.primary_finding_id ?? "primary",+ biomarker_type: t.primary_biomarker,+ severity: t.primary_severity,+ function_name: t.primary_function,+ health_impact:+ t.total_impact / Math.max(t.finding_count || 1, 1),+ reason: t.primary_reason,+ },+ ]+ )+ .slice()+ .sort((a, b) => b.health_impact - a.health_impact);++ const findingsBlock = findings+ .map((f, i) => {+ const info = biomarkerInfo(f.biomarker_type);+ const loc = f.function_name+ ? `function \`${f.function_name}\`${+ "line_start" in f && (f as any).line_start+ ? ` (line ${(f as any).line_start}${(f as any).line_end ? `–${(f as any).line_end}` : ""})`+ : ""+ }`+ : "file-level";+ return [+ `${i + 1}. **${info.label}** · ${CATEGORY_LABEL[info.category]} · ${f.severity.toUpperCase()} · health impact −${f.health_impact.toFixed(2)}`,+ ` - Where: ${loc}`,+ ` - Why it's a problem: ${info.description}`,+ ` - Observed: ${f.reason}`,+ ].join("\n");+ })+ .join("\n\n");++ const constraintList = [+ "**Read first, edit second.** Read the file, its callers, its tests, and any obvious helpers before proposing a change.",+ "Do **not** change public function signatures or exported names unless absolutely required to fix a verified finding — flag it explicitly if you must.",+ "Preserve runtime behavior. Refactors only — no new features, no opportunistic rewrites in unrelated regions.",+ "Keep test coverage at least as high as before. If you change logic, add or update tests.",+ "Match the existing code style of the file and its neighbors (formatter, naming, comment density). When in doubt, check what the rest of the codebase does.",+ "Make a single coherent commit-sized change centered on this file. Touching adjacent files (tests, a tightly-coupled helper) is fine; sprawling cross-cutting edits are not — stop and propose a phased plan first.",+ "If a finding turns out to be a false positive once you've read the code, skip it and explain why in your summary.",+ ];++ const completionContract = [+ "1. A short plan (3–6 bullets) describing the structural change before any edits.",+ "2. The edits themselves, scoped to the file above (plus tests / direct helpers if needed).",+ "3. A diff-style summary of what changed and why each change reduces a specific biomarker.",+ "4. An estimate of the new biomarker state for that file: which findings should disappear, which remain.",+ ];++ return [+ FLAVOR_PREAMBLE[flavor],+ "",+ `## Target file${repoLine}`,+ "",+ `\`${t.file_path}\``,+ "",+ "## Current health snapshot",+ "",+ bulletList([+ `Health score: **${t.score.toFixed(1)}/10** (lower is worse; 10.0 is clean)`,+ `Total impact across this file: **−${t.total_impact.toFixed(2)} points** from ${t.finding_count} finding${t.finding_count === 1 ? "" : "s"}`,+ `File size: ${t.nloc} NLOC — ${effortHint(t.effort_bucket)}`,+ t.module ? `Module: \`${t.module}\`` : null,+ ]),+ "",+ "## Issues to fix (ranked by impact)",+ "",+ findingsBlock,+ "",+ t.primary_suggestion+ ? ["## Suggested direction", "", t.primary_suggestion, ""].join("\n")+ : "",+ "## Hard constraints",+ "",+ bulletList(constraintList),+ "",+ "## What I expect back",+ "",+ completionContract.join("\n"),+ "",+ "Start by reading the file end-to-end, then explore its callers, tests, and any related helpers. The findings below describe symptoms — the actual root cause may live elsewhere. Don't propose a fix until you've grounded each one in the real code.",+ ]+ .filter((s) => s !== "")+ .join("\n");+}++// ─────────────────────────────────────────────────────────────────────+// Coverage prompt+// ─────────────────────────────────────────────────────────────────────++export interface CoverageFilePromptInput {+ file_path: string;+ line_coverage_pct: number | null;+ branch_coverage_pct?: number | null;+ total_coverable_lines?: number;+ covered_lines?: number[];+ source_format?: string;+ health_score?: number | null;+ nloc?: number | null;+ module?: string | null;+}++export interface BuildCoveragePromptOptions {+ row: CoverageFilePromptInput;+ flavor?: AiPromptFlavor;+ repoName?: string;+}++function uncoveredRanges(+ covered: number[] | undefined,+ total: number | undefined,+): string {+ if (!covered || !total || covered.length === 0) return "";+ const set = new Set(covered);+ const ranges: [number, number][] = [];+ let start: number | null = null;+ for (let i = 1; i <= total; i++) {+ if (!set.has(i)) {+ if (start === null) start = i;+ } else if (start !== null) {+ ranges.push([start, i - 1]);+ start = null;+ }+ }+ if (start !== null) ranges.push([start, total]);+ if (ranges.length === 0) return "";+ // Cap to ~20 ranges so the prompt stays readable.+ const shown = ranges.slice(0, 20);+ const more = ranges.length - shown.length;+ return (+ shown.map(([a, b]) => (a === b ? `${a}` : `${a}–${b}`)).join(", ") ++ (more > 0 ? `, … (+${more} more ranges)` : "")+ );+}++export function buildCoverageAiPrompt({+ row,+ flavor = "generic",+ repoName,+}: BuildCoveragePromptOptions): string {+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";+ const linePct = row.line_coverage_pct;+ const branchPct = row.branch_coverage_pct;+ const ranges = uncoveredRanges(row.covered_lines, row.total_coverable_lines);++ const constraintList = [+ "**Read first, write second.** Read the source file, the existing tests directory, and at least one nearby test file so you adopt the project's conventions instead of inventing your own.",+ "Use the project's existing test framework, fixtures, and naming conventions — don't introduce a new framework.",+ "Cover the listed uncovered branches/lines explicitly; do not just pad coverage with trivial cases.",+ "Each new test must have a clear behavior name (`should …` / `test_*_when_*`), one logical assertion focus, and no shared mutable state with other tests.",+ "Mock external IO (network, filesystem outside fixtures, time, env) — but do not mock the file under test.",+ "If you discover a real bug while writing the tests, add a failing test that documents it and call it out; do not silently fix.",+ "Trust the real source code over the coverage numbers in this prompt. If a line marked uncovered turns out to be unreachable or dead, say so and move on.",+ ];++ const completionContract = [+ "1. A short plan: which functions / branches you'll cover and in what order (3–6 bullets).",+ "2. The new tests, in the same test file location convention the project already uses.",+ "3. A coverage estimate: which uncovered ranges your new tests now hit, and which remain.",+ "4. A list of any bugs or surprising behavior you found while writing the tests.",+ ];++ return [+ FLAVOR_PREAMBLE[flavor],+ "",+ `## Target file${repoLine}`,+ "",+ `\`${row.file_path}\``,+ "",+ "## Current coverage state",+ "",+ bulletList([+ linePct == null+ ? "Line coverage: **no data** — file is not covered by any test run."+ : `Line coverage: **${linePct.toFixed(1)}%** (lower is worse)`,+ branchPct == null+ ? null+ : `Branch coverage: ${branchPct.toFixed(1)}%`,+ row.total_coverable_lines+ ? `Coverable lines: ${row.total_coverable_lines}`+ : null,+ row.nloc ? `File size: ${row.nloc} NLOC` : null,+ row.health_score != null+ ? `Current health score: ${row.health_score.toFixed(1)}/10 — risky changes here are likely to break things, so tests pay off.`+ : null,+ row.module ? `Module: \`${row.module}\`` : null,+ row.source_format ? `Coverage source: ${row.source_format.toUpperCase()}` : null,+ ]),+ "",+ ranges+ ? ["## Uncovered line ranges", "", "```", ranges, "```", ""].join("\n")+ : "",+ "## Your task",+ "",+ bulletList([+ "Add tests that cover the uncovered lines/branches listed above, prioritizing the riskiest code paths.",+ "If the file has no tests at all yet, create the test file in the project's standard location and seed it with the most important happy-path + edge cases first.",+ "Aim for a meaningful coverage jump (≥ 70% line coverage as a target), but quality of assertions matters more than the number.",+ ]),+ "",+ "## Hard constraints",+ "",+ bulletList(constraintList),+ "",+ "## What I expect back",+ "",+ completionContract.join("\n"),+ "",+ "Start by reading the file end-to-end, then explore its callers, the existing tests directory, and any sibling files that test similar code. The coverage numbers below come from a static report — verify them by looking at the real test files and the real source. Don't write a test before you've seen the code it's exercising and the project's existing test conventions.",+ ]+ .filter((s) => s !== "")+ .join("\n");+}diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsxnew file mode 100644index 000000000..69dd55e67--- /dev/null+++ b/packages/ui/src/health/ai-prompt-modal.tsx@@ -0,0 +1,167 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import {+ Check,+ Copy,+ Sparkles,+ Bot,+ Code2,+ Wand2,+} from "lucide-react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "../ui/dialog";+import type { AiPromptFlavor } from "./ai-prompt-builder";++export interface AiPromptModalProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Pure builder that returns the prompt string for the chosen flavor. */+ getPrompt: ((flavor: AiPromptFlavor) => string) | null;+ /** Path or other one-line identifier shown next to the title. */+ filePath?: string | null;+ /** Section heading (e.g. "AI fix prompt", "AI test prompt"). */+ title?: string;+ /** One-line subtitle below the title. */+ description?: string;+}++const FLAVORS: {+ value: AiPromptFlavor;+ label: string;+ Icon: React.ComponentType<{ className?: string }>;+ hint: string;+}[] = [+ { value: "generic", label: "Generic", Icon: Wand2, hint: "Any agent — Copilot, Codex, ChatGPT, custom." },+ { value: "claude-code", label: "Claude Code", Icon: Bot, hint: "Tuned for Claude Code's tools (Read / Edit / TodoWrite)." },+ { value: "cursor", label: "Cursor", Icon: Code2, hint: "Uses @file context, Cursor editing conventions." },+];++export function AiPromptModal({+ open,+ onOpenChange,+ getPrompt,+ filePath,+ title = "AI fix prompt",+ description = "A ready-to-paste prompt that gives your AI coding agent every detail needed to make this change in one focused pass.",+}: AiPromptModalProps) {+ const [flavor, setFlavor] = useState<AiPromptFlavor>("generic");+ const [copied, setCopied] = useState(false);++ const prompt = useMemo(+ () => (getPrompt ? getPrompt(flavor) : ""),+ [getPrompt, flavor],+ );++ useEffect(() => {+ if (!open) {+ setCopied(false);+ setFlavor("generic");+ }+ }, [open]);++ const handleCopy = async () => {+ try {+ await navigator.clipboard.writeText(prompt);+ setCopied(true);+ setTimeout(() => setCopied(false), 1800);+ } catch {+ /* clipboard blocked — user can still select + Cmd/Ctrl-C */+ }+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-3xl">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2">+ <Sparkles className="h-4 w-4 text-emerald-500" />+ {title}+ {filePath ? (+ <span className="ml-2 text-xs font-mono font-normal text-[var(--color-text-tertiary)] truncate max-w-[260px]">+ {filePath}+ </span>+ ) : null}+ </DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>++ <div className="space-y-3">+ <div>+ <p className="text-[11px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-1.5">+ Target agent+ </p>+ <div className="grid grid-cols-3 gap-2">+ {FLAVORS.map((f) => {+ const active = flavor === f.value;+ return (+ <button+ key={f.value}+ type="button"+ onClick={() => setFlavor(f.value)}+ className={+ "rounded-md border px-3 py-2 text-left transition-colors " ++ (active+ ? "border-emerald-500 bg-emerald-500/10"+ : "border-[var(--color-border-default)] hover:border-[var(--color-border-strong)] hover:bg-[var(--color-bg-elevated)]")+ }+ title={f.hint}+ >+ <div className="flex items-center gap-1.5">+ <f.Icon className={`h-3.5 w-3.5 ${active ? "text-emerald-500" : "text-[var(--color-text-tertiary)]"}`} />+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">+ {f.label}+ </span>+ </div>+ <p className="mt-0.5 text-[11px] text-[var(--color-text-tertiary)] leading-snug">+ {f.hint}+ </p>+ </button>+ );+ })}+ </div>+ </div>++ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-muted)] max-h-[420px] overflow-y-auto">+ <pre className="px-3 py-2 text-[11.5px] font-mono text-[var(--color-text-primary)] whitespace-pre-wrap break-words">+ {prompt}+ </pre>+ </div>++ <div className="flex flex-wrap items-center justify-between gap-2 text-[11px] text-[var(--color-text-tertiary)]">+ <span>+ {prompt.length.toLocaleString()} chars · approx{" "}+ {Math.round(prompt.length / 4).toLocaleString()} tokens+ </span>+ <button+ type="button"+ onClick={handleCopy}+ disabled={!prompt}+ className={+ "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors " ++ (copied+ ? "bg-emerald-500 text-white"+ : "bg-[var(--color-accent-primary)] text-[var(--color-bg-surface)] hover:opacity-90")+ }+ >+ {copied ? (+ <>+ <Check className="h-3.5 w-3.5" /> Copied+ </>+ ) : (+ <>+ <Copy className="h-3.5 w-3.5" /> Copy prompt+ </>+ )}+ </button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/ui/src/health/biomarker-chip.tsx b/packages/ui/src/health/biomarker-chip.tsxnew file mode 100644index 000000000..f902f0820--- /dev/null+++ b/packages/ui/src/health/biomarker-chip.tsx@@ -0,0 +1,26 @@+"use client";++import { Info } from "lucide-react";+import { biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";++export interface BiomarkerChipProps {+ type: string;+ showInfo?: boolean;+ className?: string;+}++export function BiomarkerChip({ type, showInfo = true, className = "" }: BiomarkerChipProps) {+ const info = biomarkerInfo(type);+ const title = `${info.label} · ${CATEGORY_LABEL[info.category]}\n\n${info.description}`;+ return (+ <span+ className={`inline-flex items-center gap-1 text-xs font-medium text-[var(--color-text-primary)] ${className}`}+ title={title}+ >+ {info.label}+ {showInfo && info.description ? (+ <Info className="h-3 w-3 text-[var(--color-text-tertiary)]" aria-hidden />+ ) : null}+ </span>+ );+}diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.tsnew file mode 100644index 000000000..f99609c30--- /dev/null+++ b/packages/ui/src/health/biomarker-glossary.ts@@ -0,0 +1,120 @@+/**+ * Biomarker glossary — single source of truth for the human-readable+ * label, category, and short explanation used in tooltips, info popovers,+ * and grouped views across all three health pages.+ *+ * Keep in sync with ``packages/core/src/repowise/core/analysis/health/scoring.py``+ * (the python ``_BIOMARKER_CATEGORY`` map) and ``biomarkers/registry.py``.+ */++export type BiomarkerCategory =+ | "structural_complexity"+ | "size_and_complexity"+ | "duplication"+ | "test_coverage"+ | "organizational";++export interface BiomarkerInfo {+ label: string;+ category: BiomarkerCategory;+ description: string;+}++export const CATEGORY_LABEL: Record<BiomarkerCategory, string> = {+ structural_complexity: "Structural complexity",+ size_and_complexity: "Size & complexity",+ duplication: "Duplication",+ test_coverage: "Test coverage",+ organizational: "Organizational",+};++export const CATEGORY_CAP: Record<BiomarkerCategory, number> = {+ structural_complexity: 3.5,+ size_and_complexity: 2.0,+ duplication: 1.5,+ test_coverage: 2.0,+ organizational: 1.0,+};++export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {+ brain_method: {+ label: "Brain method",+ category: "structural_complexity",+ description:+ "A function that knows too much — high cyclomatic complexity, many parameters, and deep nesting all at once. Hard to test, easy to break.",+ },+ nested_complexity: {+ label: "Nested complexity",+ category: "structural_complexity",+ description:+ "Deeply nested control flow (≥4 levels). Cognitive load grows non-linearly with nesting; flatten with early returns or extracted helpers.",+ },+ bumpy_road: {+ label: "Bumpy road",+ category: "structural_complexity",+ description:+ "A function with multiple shallow complexity bumps stitched together. No single block is bad, but the whole reads as a sequence of mini-functions.",+ },+ complex_method: {+ label: "Complex method",+ category: "size_and_complexity",+ description:+ "Cyclomatic complexity above the language threshold. Many independent paths through one function.",+ },+ large_method: {+ label: "Large method",+ category: "size_and_complexity",+ description:+ "A function with too many non-comment lines of code. Even simple logic gets hard to hold in your head past a point.",+ },+ primitive_obsession: {+ label: "Primitive obsession",+ category: "size_and_complexity",+ description:+ "Many primitive parameters where a domain object would carry the same data. Calls become positional and easy to mismatch.",+ },+ dry_violation: {+ label: "DRY violation",+ category: "duplication",+ description:+ "Code blocks duplicated across files. Ranked by co-change frequency — clones that move together are most worth consolidating.",+ },+ untested_hotspot: {+ label: "Untested hotspot",+ category: "test_coverage",+ description:+ "High-churn, centrally depended-on file with no paired test file and low coverage. The riskiest place to leave untested.",+ },+ coverage_gap: {+ label: "Coverage gap",+ category: "test_coverage",+ description:+ "Specific uncovered lines in a file. Surfaced when a coverage report has been ingested.",+ },+ developer_congestion: {+ label: "Developer congestion",+ category: "organizational",+ description:+ "Multiple authors editing the same file frequently — a coordination cost signal. Often points to an unclear module boundary.",+ },+ knowledge_loss: {+ label: "Knowledge loss",+ category: "organizational",+ description:+ "Files whose primary author has reduced or stopped contributing — a bus-factor warning.",+ },+};++export function biomarkerInfo(name: string): BiomarkerInfo {+ return (+ BIOMARKER_GLOSSARY[name] ?? {+ label: name.replace(/_/g, " "),+ category: "size_and_complexity",+ description: "",+ }+ );+}++export function biomarkerLabel(name: string): string {+ return biomarkerInfo(name).label;+}diff --git a/packages/ui/src/health/biomarker-list.tsx b/packages/ui/src/health/biomarker-list.tsxnew file mode 100644index 000000000..ac20585ad--- /dev/null+++ b/packages/ui/src/health/biomarker-list.tsx@@ -0,0 +1,185 @@+"use client";++import { useState } from "react";+import { ChevronDown, ChevronRight } from "lucide-react";+import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";+import { SEVERITY_CHIP, SEVERITY_LABEL, SEVERITY_ORDER, type Severity } from "./tokens";++export interface BiomarkerFinding {+ id: string;+ file_path: string;+ biomarker_type: string;+ severity: Severity;+ function_name: string | null;+ health_impact: number;+ reason: string;+}++export interface BiomarkerListProps {+ findings: BiomarkerFinding[];+ /** When true, group by biomarker type with collapsible sections. */+ grouped?: boolean;+ /** Optional minimum severity filter. */+ minSeverity?: Severity;+ onSelect?: ((f: BiomarkerFinding) => void) | undefined;+ maxPerGroup?: number;+}++export function BiomarkerList({+ findings,+ grouped = false,+ minSeverity,+ onSelect,+ maxPerGroup = 8,+}: BiomarkerListProps) {+ const filtered = minSeverity+ ? findings.filter((f) => SEVERITY_ORDER[f.severity] >= SEVERITY_ORDER[minSeverity])+ : findings;++ if (filtered.length === 0) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">+ No biomarker findings match the current filters.+ </div>+ );+ }++ if (!grouped) {+ return (+ <ul className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">+ {filtered.map((f) => (+ <FindingRow key={f.id} finding={f} onSelect={onSelect} />+ ))}+ </ul>+ );+ }++ // Group by biomarker_type+ const groups = new Map<string, BiomarkerFinding[]>();+ for (const f of filtered) {+ if (!groups.has(f.biomarker_type)) groups.set(f.biomarker_type, []);+ groups.get(f.biomarker_type)!.push(f);+ }+ const sortedGroups = [...groups.entries()].sort(+ (a, b) => b[1].length - a[1].length,+ );++ return (+ <div className="space-y-2">+ {sortedGroups.map(([type, group]) => (+ <BiomarkerGroup+ key={type}+ type={type}+ findings={group}+ onSelect={onSelect}+ maxPerGroup={maxPerGroup}+ />+ ))}+ </div>+ );+}++function BiomarkerGroup({+ type,+ findings,+ onSelect,+ maxPerGroup,+}: {+ type: string;+ findings: BiomarkerFinding[];+ onSelect?: ((f: BiomarkerFinding) => void) | undefined;+ maxPerGroup: number;+}) {+ const [expanded, setExpanded] = useState(false);+ const info = biomarkerInfo(type);+ const sevCounts = { critical: 0, high: 0, medium: 0, low: 0 } as Record<Severity, number>;+ for (const f of findings) sevCounts[f.severity]++;+ const visible = expanded ? findings : findings.slice(0, maxPerGroup);+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]">+ <button+ type="button"+ onClick={() => setExpanded((e) => !e)}+ className="flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-[var(--color-bg-elevated)] transition-colors"+ >+ {expanded ? (+ <ChevronDown className="h-4 w-4 text-[var(--color-text-tertiary)]" />+ ) : (+ <ChevronRight className="h-4 w-4 text-[var(--color-text-tertiary)]" />+ )}+ <span className="text-sm font-medium text-[var(--color-text-primary)]">+ {info.label}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {CATEGORY_LABEL[info.category]}+ </span>+ <span className="ml-auto inline-flex items-center gap-1.5 text-[11px] tabular-nums">+ {(Object.keys(sevCounts) as Severity[]).map((s) =>+ sevCounts[s] > 0 ? (+ <span+ key={s}+ className={`inline-flex items-center rounded px-1.5 py-0.5 font-semibold ${SEVERITY_CHIP[s]}`}+ title={SEVERITY_LABEL[s]}+ >+ {sevCounts[s]}+ </span>+ ) : null,+ )}+ <span className="ml-1 text-[var(--color-text-secondary)]">+ {findings.length}+ </span>+ </span>+ </button>+ <ul className="divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)]">+ {visible.map((f) => (+ <FindingRow key={f.id} finding={f} onSelect={onSelect} hideBiomarker />+ ))}+ {!expanded && findings.length > maxPerGroup ? (+ <li className="px-3 py-2 text-xs text-[var(--color-text-tertiary)]">+ + {findings.length - maxPerGroup} more — click header to expand+ </li>+ ) : null}+ </ul>+ </div>+ );+}++function FindingRow({+ finding,+ onSelect,+ hideBiomarker = false,+}: {+ finding: BiomarkerFinding;+ onSelect?: ((f: BiomarkerFinding) => void) | undefined;+ hideBiomarker?: boolean;+}) {+ const f = finding;+ const interactive = !!onSelect;+ return (+ <li+ className={`p-3 space-y-1 ${interactive ? "cursor-pointer hover:bg-[var(--color-bg-elevated)]" : ""}`}+ onClick={interactive ? () => onSelect!(f) : undefined}+ >+ <div className="flex items-center gap-2">+ <span+ className={`inline-block rounded px-2 py-0.5 text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}+ >+ {SEVERITY_LABEL[f.severity]}+ </span>+ {!hideBiomarker ? (+ <span className="text-xs font-medium text-[var(--color-text-primary)]">+ {biomarkerLabel(f.biomarker_type)}+ </span>+ ) : null}+ <span className="ml-auto text-xs tabular-nums text-red-500">+ −{f.health_impact.toFixed(2)}+ </span>+ </div>+ <p className="text-xs text-[var(--color-text-secondary)] truncate font-mono">+ {f.file_path}+ {f.function_name ? ` :: ${f.function_name}` : ""}+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)] line-clamp-2">{f.reason}</p>+ </li>+ );+}diff --git a/packages/ui/src/health/coverage-bar.tsx b/packages/ui/src/health/coverage-bar.tsxnew file mode 100644index 000000000..c5a31504c--- /dev/null+++ b/packages/ui/src/health/coverage-bar.tsx@@ -0,0 +1,38 @@+export interface CoverageBarProps {+ value: number | null | undefined;+ label?: string;+ size?: "sm" | "md";+}++function color(pct: number): string {+ if (pct < 30) return "bg-red-500";+ if (pct < 60) return "bg-amber-500";+ if (pct < 80) return "bg-yellow-400";+ return "bg-emerald-500";+}++export function CoverageBar({ value, label, size = "md" }: CoverageBarProps) {+ const pct = value == null ? 0 : Math.max(0, Math.min(100, value));+ const has = value != null;+ const h = size === "sm" ? "h-1.5" : "h-2";+ return (+ <div className="flex items-center gap-2">+ <div+ className={`relative flex-1 ${h} rounded-full bg-[var(--color-bg-muted)] overflow-hidden`}+ >+ {has && (+ <div+ className={`absolute inset-y-0 left-0 ${color(pct)} rounded-full transition-all`}+ style={{ width: `${pct}%` }}+ />+ )}+ </div>+ <span className="text-xs tabular-nums text-[var(--color-text-secondary)] w-12 text-right">+ {has ? `${pct.toFixed(0)}%` : "—"}+ </span>+ {label && (+ <span className="text-xs text-[var(--color-text-tertiary)]">{label}</span>+ )}+ </div>+ );+}diff --git a/packages/ui/src/health/file-table.tsx b/packages/ui/src/health/file-table.tsxnew file mode 100644index 000000000..88f3bc0c2--- /dev/null+++ b/packages/ui/src/health/file-table.tsx@@ -0,0 +1,152 @@+"use client";++import { ArrowDown, ArrowUp, FileText } from "lucide-react";+import { scoreBadgeClass } from "./tokens";++export interface HealthFileRow {+ file_path: string;+ score: number;+ max_ccn: number;+ max_nesting: number;+ nloc: number;+ has_test_file: boolean;+ line_coverage_pct?: number | null;+ module?: string | null;+ duplication_pct?: number | null;+}++export type FileSortField =+ | "score"+ | "max_ccn"+ | "max_nesting"+ | "nloc"+ | "duplication_pct"+ | "line_coverage_pct"+ | "file_path";++export interface HealthFileTableProps {+ files: HealthFileRow[];+ sortField?: FileSortField;+ sortOrder?: "asc" | "desc";+ onSort?: (field: FileSortField) => void;+ onSelect?: (row: HealthFileRow) => void;+ selectedPath?: string | null;+ emptyMessage?: string;+}++interface ColDef {+ key: FileSortField | "tests";+ label: string;+ align: "left" | "right" | "center";+ sortable: boolean;+ className?: string;+}++const COLS: ColDef[] = [+ { key: "file_path", label: "File", align: "left", sortable: true },+ { key: "score", label: "Score", align: "right", sortable: true },+ { key: "max_ccn", label: "CCN", align: "right", sortable: true },+ { key: "max_nesting", label: "Nest", align: "right", sortable: true },+ { key: "nloc", label: "NLOC", align: "right", sortable: true },+ { key: "duplication_pct", label: "Dup %", align: "right", sortable: true },+ { key: "line_coverage_pct", label: "Cov", align: "right", sortable: true },+ { key: "tests", label: "Tests", align: "center", sortable: false },+];++export function HealthFileTable({+ files,+ sortField = "score",+ sortOrder = "asc",+ onSort,+ onSelect,+ selectedPath,+ emptyMessage,+}: HealthFileTableProps) {+ if (files.length === 0) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">+ {emptyMessage ?? "No files match the current filters."}+ </div>+ );+ }+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">+ <table className="w-full text-sm">+ <thead className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider sticky top-0">+ <tr>+ {COLS.map((c) => {+ const isActive = c.sortable && c.key === sortField;+ const alignCls =+ c.align === "right" ? "text-right" : c.align === "center" ? "text-center" : "text-left";+ return (+ <th+ key={c.key}+ className={`px-3 py-2 font-medium ${alignCls} ${c.sortable ? "cursor-pointer select-none" : ""}`}+ onClick={c.sortable && onSort ? () => onSort(c.key as FileSortField) : undefined}+ >+ <span className="inline-flex items-center gap-1">+ {c.label}+ {isActive ? (+ sortOrder === "asc" ? (+ <ArrowUp className="h-3 w-3" />+ ) : (+ <ArrowDown className="h-3 w-3" />+ )+ ) : null}+ </span>+ </th>+ );+ })}+ </tr>+ </thead>+ <tbody>+ {files.map((f) => {+ const isSelected = selectedPath === f.file_path;+ const rowCls = `border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] ${+ isSelected ? "bg-[var(--color-accent-muted)]/30" : ""+ } ${onSelect ? "cursor-pointer" : ""}`;+ return (+ <tr+ key={f.file_path}+ className={rowCls}+ onClick={onSelect ? () => onSelect(f) : undefined}+ >+ <td className="px-3 py-2 text-[var(--color-text-primary)] font-mono text-xs truncate max-w-[440px]">+ <span className="inline-flex items-center gap-1.5">+ <FileText className="h-3 w-3 text-[var(--color-text-tertiary)]" />+ <span className="truncate" title={f.file_path}>+ {f.file_path}+ </span>+ </span>+ </td>+ <td className="px-3 py-2 text-right">+ <span+ className={`inline-block rounded px-2 py-0.5 text-xs font-semibold tabular-nums ${scoreBadgeClass(f.score)}`}+ >+ {f.score.toFixed(1)}+ </span>+ </td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">{f.max_ccn}</td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">{f.max_nesting}</td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">{f.nloc}</td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">+ {f.duplication_pct == null ? "—" : `${f.duplication_pct.toFixed(0)}%`}+ </td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">+ {f.line_coverage_pct == null ? "—" : `${f.line_coverage_pct.toFixed(0)}%`}+ </td>+ <td className="px-3 py-2 text-center text-xs">+ {f.has_test_file ? (+ <span className="text-emerald-500">✓</span>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}diff --git a/packages/ui/src/health/health-badge.tsx b/packages/ui/src/health/health-badge.tsxnew file mode 100644index 000000000..286cede98--- /dev/null+++ b/packages/ui/src/health/health-badge.tsx@@ -0,0 +1,31 @@+export interface HealthBadgeProps {+ score: number | null | undefined;+ size?: "xs" | "sm";+}++function scoreColor(score: number): string {+ if (score < 4) return "bg-red-500/15 text-red-500";+ if (score < 6) return "bg-amber-500/15 text-amber-500";+ if (score < 8) return "bg-yellow-500/15 text-yellow-500";+ return "bg-emerald-500/15 text-emerald-500";+}++/** Compact health-score pill, designed to inline next to a file path+ * on Hotspot / Ownership / Graph rows without changing those shared+ * components' shapes. Renders nothing when the score is missing. */+export function HealthBadge({ score, size = "xs" }: HealthBadgeProps) {+ if (score == null) return null;+ const cls = scoreColor(score);+ const sizing =+ size === "xs"+ ? "text-[10px] px-1.5 py-0.5"+ : "text-xs px-2 py-0.5";+ return (+ <span+ className={`inline-flex items-center rounded font-semibold tabular-nums ${cls} ${sizing}`}+ title={`Health ${score.toFixed(1)}/10`}+ >+ {score.toFixed(1)}+ </span>+ );+}diff --git a/packages/ui/src/health/health-file-drawer.tsx b/packages/ui/src/health/health-file-drawer.tsxnew file mode 100644index 000000000..1ea799964--- /dev/null+++ b/packages/ui/src/health/health-file-drawer.tsx@@ -0,0 +1,230 @@+"use client";++import { useEffect } from "react";+import { ExternalLink, X } from "lucide-react";+import { biomarkerLabel, biomarkerInfo, CATEGORY_LABEL } from "./biomarker-glossary";+import { ScoreBreakdown, type ScoreBreakdownCategory } from "./score-breakdown";+import {+ SEVERITY_CHIP,+ SEVERITY_LABEL,+ scoreBadgeClass,+ type Severity,+} from "./tokens";++export interface HealthDrawerFinding {+ id: string;+ biomarker_type: string;+ severity: Severity;+ function_name: string | null;+ line_start: number | null;+ line_end: number | null;+ health_impact: number;+ reason: string;+ status?: string;+}++export interface HealthDrawerMetric {+ file_path: string;+ score: number;+ max_ccn: number;+ max_nesting: number;+ nloc: number;+ module: string | null;+ duplication_pct?: number | null;+ line_coverage_pct?: number | null;+ has_test_file: boolean;+}++export interface HealthFileDrawerProps {+ open: boolean;+ onClose: () => void;+ loading?: boolean;+ metric?: HealthDrawerMetric | null;+ breakdown?: {+ score: number;+ total_deduction: number;+ categories: ScoreBreakdownCategory[];+ } | null;+ findings?: HealthDrawerFinding[];+ suggestions?: Record<string, string>;+ fileViewHref?: string;+ permalinkHref?: string;+}++export function HealthFileDrawer({+ open,+ onClose,+ loading,+ metric,+ breakdown,+ findings = [],+ suggestions = {},+ fileViewHref,+ permalinkHref,+}: HealthFileDrawerProps) {+ // ESC to close+ useEffect(() => {+ if (!open) return;+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, [open, onClose]);++ if (!open) return null;+ return (+ <div className="fixed inset-0 z-50 flex" role="dialog" aria-modal="true">+ <button+ type="button"+ aria-label="Close drawer"+ onClick={onClose}+ className="flex-1 bg-black/50 backdrop-blur-[1px]"+ />+ <aside className="w-full max-w-[640px] bg-[var(--color-bg-surface)] border-l border-[var(--color-border-default)] overflow-y-auto shadow-xl">+ <header className="sticky top-0 z-10 flex items-start justify-between gap-3 border-b border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-4 py-3">+ <div className="min-w-0 flex-1">+ <p className="text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">File health</p>+ <p className="font-mono text-sm text-[var(--color-text-primary)] truncate" title={metric?.file_path}>+ {metric?.file_path ?? "Loading…"}+ </p>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ {permalinkHref ? (+ <a+ href={permalinkHref}+ className="text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] inline-flex items-center gap-1"+ title="Open as a shareable page"+ >+ <ExternalLink className="h-3.5 w-3.5" />+ Permalink+ </a>+ ) : null}+ <button+ type="button"+ onClick={onClose}+ aria-label="Close"+ className="rounded p-1 text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"+ >+ <X className="h-4 w-4" />+ </button>+ </div>+ </header>++ <div className="px-4 py-4 space-y-5">+ {loading ? (+ <div className="text-sm text-[var(--color-text-tertiary)]">Loading…</div>+ ) : !metric ? (+ <div className="rounded border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">+ No metric for this file yet. Run <code>repowise init</code> or <code>repowise health</code>.+ </div>+ ) : (+ <>+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">+ <Stat label="Score" value={+ <span className={`inline-flex items-baseline rounded px-2 py-0.5 font-bold tabular-nums ${scoreBadgeClass(metric.score)}`}>+ {metric.score.toFixed(1)}+ <span className="ml-0.5 text-[10px] font-normal opacity-70">/10</span>+ </span>+ } />+ <Stat label="Max CCN" value={<span className="text-base font-semibold tabular-nums">{metric.max_ccn}</span>} />+ <Stat label="Nest" value={<span className="text-base font-semibold tabular-nums">{metric.max_nesting}</span>} />+ <Stat label="NLOC" value={<span className="text-base font-semibold tabular-nums">{metric.nloc}</span>} />+ <Stat label="Module" value={<span className="text-xs">{metric.module ?? "—"}</span>} />+ <Stat label="Tests" value={<span className="text-xs">{metric.has_test_file ? "Paired" : "None"}</span>} />+ <Stat label="Coverage" value={+ <span className="text-xs tabular-nums">+ {metric.line_coverage_pct == null ? "—" : `${metric.line_coverage_pct.toFixed(0)}%`}+ </span>+ } />+ <Stat label="Duplication" value={+ <span className="text-xs tabular-nums">+ {metric.duplication_pct == null ? "—" : `${metric.duplication_pct.toFixed(0)}%`}+ </span>+ } />+ </div>++ {fileViewHref ? (+ <a+ href={fileViewHref}+ className="inline-flex items-center gap-1.5 text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ <ExternalLink className="h-3 w-3" />+ Open in file explorer+ </a>+ ) : null}++ {breakdown ? (+ <section className="space-y-2">+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Why this score?+ </h3>+ <ScoreBreakdown+ score={breakdown.score}+ totalDeduction={breakdown.total_deduction}+ categories={breakdown.categories}+ />+ </section>+ ) : null}++ {findings.length > 0 ? (+ <section className="space-y-2">+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ All findings ({findings.length})+ </h3>+ <ul className="space-y-2">+ {findings.map((f) => {+ const info = biomarkerInfo(f.biomarker_type);+ return (+ <li+ key={f.id}+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-1"+ >+ <div className="flex items-center gap-2 flex-wrap">+ <span className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}>+ {SEVERITY_LABEL[f.severity]}+ </span>+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">+ {biomarkerLabel(f.biomarker_type)}+ </span>+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {CATEGORY_LABEL[info.category]}+ </span>+ {f.function_name ? (+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">+ {f.function_name}+ {f.line_start ? `:${f.line_start}` : ""}+ </span>+ ) : null}+ <span className="ml-auto text-xs tabular-nums text-red-500">−{f.health_impact.toFixed(2)}</span>+ </div>+ <p className="text-xs text-[var(--color-text-secondary)]">{f.reason}</p>+ {suggestions[f.biomarker_type] ? (+ <p className="text-xs text-[var(--color-text-tertiary)] italic">+ {suggestions[f.biomarker_type]}+ </p>+ ) : null}+ </li>+ );+ })}+ </ul>+ </section>+ ) : null}+ </>+ )}+ </div>+ </aside>+ </div>+ );+}++function Stat({ label, value }: { label: string; value: React.ReactNode }) {+ return (+ <div className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-2.5">+ <p className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] mb-0.5">+ {label}+ </p>+ <div className="text-[var(--color-text-primary)]">{value}</div>+ </div>+ );+}diff --git a/packages/ui/src/health/health-tabs.tsx b/packages/ui/src/health/health-tabs.tsxnew file mode 100644index 000000000..76ccfeaab--- /dev/null+++ b/packages/ui/src/health/health-tabs.tsx@@ -0,0 +1,60 @@+"use client";++import { HeartPulse, TestTubeDiagonal, Wrench, TrendingUp } from "lucide-react";++export type HealthTabKey = "overview" | "trend" | "coverage" | "refactoring";++export interface HealthTabsProps {+ repoId: string;+ active: HealthTabKey;+ /** Optional render-prop that produces a `<a href>` / `<Link>`. Lets the+ * caller plug Next's `<Link>` without dragging the next dep into ui/. */+ renderLink?: (props: {+ href: string;+ label: string;+ active: boolean;+ icon: React.ReactNode;+ key: string;+ }) => React.ReactNode;+}++const TABS: { key: HealthTabKey; label: string; suffix: string; Icon: React.ComponentType<{ className?: string }> }[] = [+ { key: "overview", label: "Overview", suffix: "", Icon: HeartPulse },+ { key: "trend", label: "Trend", suffix: "/trend", Icon: TrendingUp },+ { key: "coverage", label: "Coverage", suffix: "/coverage", Icon: TestTubeDiagonal },+ { key: "refactoring", label: "Refactoring", suffix: "/refactoring-targets", Icon: Wrench },+];++export function HealthTabs({ repoId, active, renderLink }: HealthTabsProps) {+ return (+ <div className="border-b border-[var(--color-border-default)]">+ <nav className="-mb-px flex flex-wrap gap-1" aria-label="Code health views">+ {TABS.map((t) => {+ const href = `/repos/${repoId}/health${t.suffix}`;+ const isActive = active === t.key;+ const baseCls =+ "inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors";+ const activeCls = isActive+ ? "border-emerald-500 text-[var(--color-text-primary)]"+ : "border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-default)]";+ const icon = <t.Icon className="h-4 w-4" />;+ if (renderLink) {+ return renderLink({+ href,+ label: t.label,+ active: isActive,+ icon,+ key: t.key,+ });+ }+ return (+ <a key={t.key} href={href} className={`${baseCls} ${activeCls}`}>+ {icon}+ {t.label}+ </a>+ );+ })}+ </nav>+ </div>+ );+}diff --git a/packages/ui/src/health/impact-effort-quadrant.tsx b/packages/ui/src/health/impact-effort-quadrant.tsxnew file mode 100644index 000000000..e488521f0--- /dev/null+++ b/packages/ui/src/health/impact-effort-quadrant.tsx@@ -0,0 +1,137 @@+"use client";++import { useMemo, useState } from "react";+import type { EffortBucket } from "./refactoring-card";++export interface ImpactEffortPoint {+ file_path: string;+ total_impact: number;+ effort_bucket: EffortBucket;+ nloc: number;+ score: number;+}++export interface ImpactEffortQuadrantProps {+ points: ImpactEffortPoint[];+ onSelect?: (point: ImpactEffortPoint) => void;+ height?: number;+}++const EFFORT_X: Record<EffortBucket, number> = { S: 12, M: 38, L: 62, XL: 88 };++export function ImpactEffortQuadrant({+ points,+ onSelect,+ height = 280,+}: ImpactEffortQuadrantProps) {+ const [hovered, setHovered] = useState<ImpactEffortPoint | null>(null);+ const data = useMemo(() => points.filter((p) => p.total_impact > 0), [points]);++ if (data.length === 0) {+ return (+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)]">+ No refactoring targets to plot yet.+ </div>+ );+ }++ const W = 640;+ const H = height;+ const padL = 40;+ const padR = 12;+ const padT = 20;+ const padB = 36;+ const plotW = W - padL - padR;+ const plotH = H - padT - padB;+ const maxImpact = Math.max(...data.map((d) => d.total_impact), 1);++ const xScale = (pct: number) => padL + (pct / 100) * plotW;+ const yScale = (impact: number) => padT + ((maxImpact - impact) / maxImpact) * plotH;++ // Quadrant midpoints — between M (38) and L (62), and at half impact.+ const midX = xScale(50);+ const midY = yScale(maxImpact / 2);++ // Jitter helper so dots within the same effort bucket don't perfectly stack.+ const jitter = (s: string) => {+ let h = 0;+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;+ return ((h % 14) - 7) * 1.4;+ };++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <div className="mb-2 flex items-baseline gap-2">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Impact × effort+ </h3>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {data.length} targets · click a dot to open+ </span>+ </div>+ <div className="relative">+ <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Impact vs effort scatter plot">+ <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-emerald-500/8" />+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-amber-500/5" />+ <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-yellow-500/5" />+ <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-red-500/5" />++ <line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />+ <line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />+ <line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />+ <line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />++ {(["S", "M", "L", "XL"] as EffortBucket[]).map((b) => (+ <text key={b} x={xScale(EFFORT_X[b])} y={H - padB + 14} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>+ {b}+ </text>+ ))}+ <text x={W / 2} y={H - 4} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>+ Effort (NLOC bucket)+ </text>+ <text x={10} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 10 ${H / 2})`}>+ Total impact+ </text>++ <text x={padL + 6} y={padT + 12} fontSize={10} fill="currentColor" opacity={0.6}>Quick wins</text>+ <text x={W - padR - 6} y={padT + 12} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.6}>Major projects</text>+ <text x={padL + 6} y={H - padB - 6} fontSize={10} fill="currentColor" opacity={0.5}>Minor cleanups</text>+ <text x={W - padR - 6} y={H - padB - 6} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Time sinks</text>++ {data.map((p) => {+ const baseX = xScale(EFFORT_X[p.effort_bucket]);+ const cx = baseX + jitter(p.file_path);+ const cy = yScale(p.total_impact);+ const isHovered = hovered?.file_path === p.file_path;+ const fillCls = p.score < 4 ? "fill-red-500" : p.score < 7 ? "fill-amber-500" : "fill-emerald-500";+ return (+ <circle+ key={p.file_path}+ cx={cx}+ cy={cy}+ r={isHovered ? 6 : 4}+ className={`${fillCls} ${onSelect ? "cursor-pointer" : ""}`}+ fillOpacity={0.75}+ stroke={isHovered ? "white" : "none"}+ strokeWidth={1.5}+ onMouseEnter={() => setHovered(p)}+ onMouseLeave={() => setHovered(null)}+ onClick={onSelect ? () => onSelect(p) : undefined}+ >+ <title>{`${p.file_path}\n−${p.total_impact.toFixed(2)} · ${p.effort_bucket} effort · score ${p.score.toFixed(1)}`}</title>+ </circle>+ );+ })}+ </svg>+ {hovered ? (+ <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] shadow-md">+ <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>+ <span className="ml-2 text-[var(--color-text-tertiary)]">+ −{hovered.total_impact.toFixed(2)} · {hovered.effort_bucket} · {hovered.score.toFixed(1)}+ </span>+ </div>+ ) : null}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsnew file mode 100644index 000000000..554b007d2--- /dev/null+++ b/packages/ui/src/health/index.ts@@ -0,0 +1,23 @@+export * from "./tokens";+export * from "./biomarker-glossary";+export * from "./biomarker-chip";+export * from "./kpi-cards";+export * from "./file-table";+export * from "./biomarker-list";+export * from "./coverage-bar";+export * from "./module-coverage-list";+export * from "./untested-hotspot-warning";+export * from "./refactoring-card";+export * from "./refactoring-target-list";+export * from "./health-badge";+export * from "./module-rollup-list";+export * from "./severity-distribution";+export * from "./score-breakdown";+export * from "./sparkline";+export * from "./health-tabs";+export * from "./trend-chart";+export * from "./risk-coverage-scatter";+export * from "./impact-effort-quadrant";+export * from "./health-file-drawer";+export * from "./ai-prompt-builder";+export * from "./ai-prompt-modal";diff --git a/packages/ui/src/health/kpi-cards.tsx b/packages/ui/src/health/kpi-cards.tsxnew file mode 100644index 000000000..ab70c1f03--- /dev/null+++ b/packages/ui/src/health/kpi-cards.tsx@@ -0,0 +1,128 @@+import { formatNumber } from "../lib/format";+import { scoreTextColor, formatDelta, deltaColor } from "./tokens";+import { Sparkline } from "./sparkline";+import { SeverityDistribution, type SeverityBreakdown } from "./severity-distribution";++export interface HealthSummary {+ file_count: number;+ average_health: number;+ hotspot_health?: number | null;+ worst_performer_path: string | null;+ worst_performer_score: number | null;+ open_findings: number;+ severity_breakdown?: SeverityBreakdown;+}++export interface HealthKpiCardsProps {+ summary: HealthSummary;+ /** Optional series for sparklines, newest-last. */+ averageHistory?: number[];+ hotspotHistory?: number[];+ worstHistory?: number[];+ averageDelta?: number | null;+ hotspotDelta?: number | null;+}++export function HealthKpiCards({+ summary,+ averageHistory,+ hotspotHistory,+ worstHistory,+ averageDelta,+ hotspotDelta,+}: HealthKpiCardsProps) {+ return (+ <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">+ <Card label="Files Analyzed">+ <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(summary.file_count)}+ </p>+ </Card>+ <Card label="Average Health" sparkline={averageHistory} delta={averageDelta}>+ <p+ className={`text-2xl font-bold tabular-nums ${scoreTextColor(summary.average_health)}`}+ >+ {summary.average_health.toFixed(1)}+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>+ </p>+ </Card>+ <Card+ label="Hotspot Health"+ sparkline={hotspotHistory}+ delta={hotspotDelta}+ hint="NLOC-weighted score over the repo's high-churn files."+ >+ <p+ className={`text-2xl font-bold tabular-nums ${scoreTextColor(summary.hotspot_health ?? null)}`}+ >+ {summary.hotspot_health == null ? "—" : summary.hotspot_health.toFixed(1)}+ {summary.hotspot_health == null ? null : (+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>+ )}+ </p>+ </Card>+ <Card label="Worst Performer" sparkline={worstHistory}>+ <p+ className={`text-2xl font-bold tabular-nums ${scoreTextColor(summary.worst_performer_score)}`}+ >+ {summary.worst_performer_score?.toFixed(1) ?? "—"}+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>+ </p>+ <p className="text-xs text-[var(--color-text-tertiary)] mt-1 truncate font-mono">+ {summary.worst_performer_path ?? "no data"}+ </p>+ </Card>+ <Card label="Open Findings">+ <p className="text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {formatNumber(summary.open_findings)}+ </p>+ {summary.severity_breakdown ? (+ <div className="mt-2">+ <SeverityDistribution+ breakdown={summary.severity_breakdown}+ showCounts={false}+ />+ </div>+ ) : null}+ </Card>+ </div>+ );+}++function Card({+ label,+ children,+ sparkline,+ delta,+ hint,+}: {+ label: string;+ children: React.ReactNode;+ sparkline?: number[] | undefined;+ delta?: number | null | undefined;+ hint?: string | undefined;+}) {+ return (+ <div+ className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4"+ title={hint}+ >+ <div className="flex items-start justify-between gap-2 mb-1">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ {label}+ </p>+ {sparkline && sparkline.length > 0 ? (+ <div className="text-[var(--color-text-tertiary)]">+ <Sparkline values={sparkline} width={56} height={16} />+ </div>+ ) : null}+ </div>+ {children}+ {delta != null ? (+ <p className={`mt-1 text-[11px] tabular-nums ${deltaColor(delta)}`}>+ {formatDelta(delta)} vs. prior+ </p>+ ) : null}+ </div>+ );+}diff --git a/packages/ui/src/health/module-coverage-list.tsx b/packages/ui/src/health/module-coverage-list.tsxnew file mode 100644index 000000000..a0aa154a8--- /dev/null+++ b/packages/ui/src/health/module-coverage-list.tsx@@ -0,0 +1,40 @@+import { CoverageBar } from "./coverage-bar";++export interface ModuleCoverageRow {+ module: string;+ files: number;+ covered_lines: number;+ total_lines: number;+ line_coverage_pct: number;+}++export interface ModuleCoverageListProps {+ modules: ModuleCoverageRow[];+}++export function ModuleCoverageList({ modules }: ModuleCoverageListProps) {+ if (modules.length === 0) {+ return (+ <p className="text-sm text-[var(--color-text-tertiary)]">+ No coverage data for any module.+ </p>+ );+ }+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] divide-y divide-[var(--color-border-default)]">+ {modules.map((m) => (+ <div key={m.module} className="px-4 py-3">+ <div className="flex items-center justify-between gap-3 mb-1.5">+ <span className="font-mono text-sm text-[var(--color-text-primary)] truncate">+ {m.module}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">+ {m.files} files · {m.covered_lines}/{m.total_lines} lines+ </span>+ </div>+ <CoverageBar value={m.line_coverage_pct} />+ </div>+ ))}+ </div>+ );+}diff --git a/packages/ui/src/health/module-rollup-list.tsx b/packages/ui/src/health/module-rollup-list.tsxnew file mode 100644index 000000000..52a700610--- /dev/null+++ b/packages/ui/src/health/module-rollup-list.tsx@@ -0,0 +1,135 @@+"use client";++import { useMemo, useState } from "react";+import { ArrowDown, ArrowUp } from "lucide-react";+import { HealthBadge } from "./health-badge";++export interface ModuleRollupRow {+ module: string;+ file_count: number;+ nloc: number;+ average_health: number;+ worst_performer_path: string;+ worst_performer_score: number;+}++export interface ModuleRollupListProps {+ modules: ModuleRollupRow[];+ emptyMessage?: string;+ onSelect?: (row: ModuleRollupRow) => void;+ pageSize?: number;+}++type SortKey = "average_health" | "file_count" | "nloc" | "module";++export function ModuleRollupList({+ modules,+ emptyMessage = "No modules detected yet — community labels populate after the first `repowise init`.",+ onSelect,+ pageSize = 15,+}: ModuleRollupListProps) {+ const [sort, setSort] = useState<SortKey>("average_health");+ const [order, setOrder] = useState<"asc" | "desc">("asc");+ const [expanded, setExpanded] = useState(false);++ const sorted = useMemo(() => {+ const copy = [...modules];+ copy.sort((a, b) => {+ const av = a[sort] as number | string;+ const bv = b[sort] as number | string;+ if (typeof av === "string" && typeof bv === "string") {+ return order === "asc" ? av.localeCompare(bv) : bv.localeCompare(av);+ }+ return order === "asc" ? (av as number) - (bv as number) : (bv as number) - (av as number);+ });+ return copy;+ }, [modules, sort, order]);++ if (!modules || modules.length === 0) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)]">+ {emptyMessage}+ </div>+ );+ }++ const visible = expanded ? sorted : sorted.slice(0, pageSize);+ const toggle = (key: SortKey) => {+ if (sort === key) setOrder((o) => (o === "asc" ? "desc" : "asc"));+ else {+ setSort(key);+ setOrder(key === "average_health" ? "asc" : "desc");+ }+ };++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">+ <table className="w-full text-sm">+ <thead className="bg-[var(--color-bg-elevated)] text-[var(--color-text-tertiary)] text-xs uppercase tracking-wider">+ <tr>+ <Th label="Module" active={sort === "module"} order={order} onClick={() => toggle("module")} />+ <Th label="Files" active={sort === "file_count"} order={order} onClick={() => toggle("file_count")} />+ <Th label="NLOC" active={sort === "nloc"} order={order} onClick={() => toggle("nloc")} />+ <Th label="Avg health" active={sort === "average_health"} order={order} onClick={() => toggle("average_health")} />+ <th className="text-left px-3 py-2">Worst file</th>+ </tr>+ </thead>+ <tbody>+ {visible.map((m) => (+ <tr+ key={m.module}+ className={`border-t border-[var(--color-border-default)] ${onSelect ? "cursor-pointer hover:bg-[var(--color-bg-elevated)]" : ""}`}+ onClick={onSelect ? () => onSelect(m) : undefined}+ >+ <td className="px-3 py-2 font-medium text-[var(--color-text-primary)]">{m.module}</td>+ <td className="px-3 py-2 tabular-nums text-[var(--color-text-secondary)]">{m.file_count}</td>+ <td className="px-3 py-2 tabular-nums text-[var(--color-text-secondary)]">{m.nloc.toLocaleString()}</td>+ <td className="px-3 py-2">+ <HealthBadge score={m.average_health} />+ </td>+ <td className="px-3 py-2 font-mono text-xs text-[var(--color-text-secondary)] truncate max-w-[280px]" title={m.worst_performer_path}>+ {m.worst_performer_path}{" "}+ <span className="text-[var(--color-text-tertiary)]">({m.worst_performer_score.toFixed(1)})</span>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ {modules.length > pageSize ? (+ <div className="border-t border-[var(--color-border-default)] px-3 py-2 text-xs text-[var(--color-text-tertiary)]">+ <button+ type="button"+ onClick={() => setExpanded((e) => !e)}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ {expanded ? "Show fewer" : `Show all ${modules.length}`}+ </button>+ </div>+ ) : null}+ </div>+ );+}++function Th({+ label,+ active,+ order,+ onClick,+}: {+ label: string;+ active: boolean;+ order: "asc" | "desc";+ onClick: () => void;+}) {+ return (+ <th+ className="text-left px-3 py-2 font-medium cursor-pointer select-none"+ onClick={onClick}+ >+ <span className="inline-flex items-center gap-1">+ {label}+ {active ? (order === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />) : null}+ </span>+ </th>+ );+}diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsxnew file mode 100644index 000000000..3535705f9--- /dev/null+++ b/packages/ui/src/health/refactoring-card.tsx@@ -0,0 +1,223 @@+"use client";++import { useState } from "react";+import { ArrowUpRight, ChevronDown, ChevronRight, Sparkles } from "lucide-react";+import { biomarkerLabel } from "./biomarker-glossary";+import { SEVERITY_CHIP, SEVERITY_LABEL, type Severity } from "./tokens";++export type EffortBucket = "S" | "M" | "L" | "XL";++export interface RefactoringTargetFinding {+ id: string;+ biomarker_type: string;+ severity: Severity;+ function_name: string | null;+ health_impact: number;+ reason: string;+ status?: string;+}++export interface RefactoringTarget {+ file_path: string;+ score: number;+ nloc: number;+ module?: string | null;+ primary_biomarker: string;+ primary_severity: Severity;+ primary_reason: string;+ primary_function: string | null;+ primary_line_start: number | null;+ primary_line_end: number | null;+ primary_suggestion?: string;+ primary_finding_id?: string;+ total_impact: number;+ finding_count: number;+ biomarkers: string[];+ effort_bucket: EffortBucket;+ impact_per_effort: number;+ all_findings?: RefactoringTargetFinding[];+}++export type FindingStatus = "open" | "acknowledged" | "resolved" | "false_positive";++export interface RefactoringCardProps {+ target: RefactoringTarget;+ onSelect?: ((target: RefactoringTarget) => void) | undefined;+ onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;+ onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;+ expandable?: boolean;+}++const effortLabel: Record<EffortBucket, string> = {+ S: "Small",+ M: "Medium",+ L: "Large",+ XL: "Extra large",+};++const effortColor: Record<EffortBucket, string> = {+ S: "bg-emerald-500/15 text-emerald-500",+ M: "bg-yellow-500/15 text-yellow-600",+ L: "bg-amber-500/15 text-amber-500",+ XL: "bg-red-500/15 text-red-500",+};++export function RefactoringCard({+ target,+ onSelect,+ onStatusChange,+ onGeneratePrompt,+ expandable = true,+}: RefactoringCardProps) {+ const [expanded, setExpanded] = useState(false);+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">+ <div className="p-4 space-y-2">+ <div className="flex items-center gap-2 flex-wrap">+ <span+ className={`inline-block rounded px-2 py-0.5 text-[10px] uppercase font-semibold ${SEVERITY_CHIP[target.primary_severity]}`}+ >+ {SEVERITY_LABEL[target.primary_severity]}+ </span>+ <span className="text-xs font-semibold text-[var(--color-text-primary)]">+ {biomarkerLabel(target.primary_biomarker)}+ </span>+ {target.module ? (+ <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)] rounded px-1.5 py-0.5 border border-[var(--color-border-default)]">+ {target.module}+ </span>+ ) : null}+ <span+ className={`inline-block rounded px-1.5 py-0.5 text-[10px] uppercase font-semibold ${effortColor[target.effort_bucket]}`}+ title={`Effort: ${effortLabel[target.effort_bucket]} (NLOC ${target.nloc})`}+ >+ {target.effort_bucket}+ </span>+ <span className="ml-auto text-xs tabular-nums text-red-500" title="Total health impact across this file's findings">+ −{target.total_impact.toFixed(2)}+ </span>+ </div>+ <button+ type="button"+ onClick={onSelect ? () => onSelect(target) : undefined}+ className="group/file flex w-full items-center gap-1.5 text-left rounded-md -mx-1 px-1 py-0.5 hover:bg-[var(--color-bg-elevated)] disabled:cursor-default disabled:hover:bg-transparent"+ disabled={!onSelect}+ title={onSelect ? "Open file health drawer" : undefined}+ >+ <p className="min-w-0 flex-1 text-sm font-mono text-[var(--color-text-primary)] truncate group-hover/file:text-[var(--color-accent-primary)]">+ {target.file_path}+ {target.primary_function ? (+ <span className="text-[var(--color-text-secondary)]">+ {" :: "}+ {target.primary_function}+ </span>+ ) : null}+ </p>+ {onSelect ? (+ <ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-[var(--color-text-tertiary)] group-hover/file:text-[var(--color-accent-primary)] transition-transform group-hover/file:-translate-y-px group-hover/file:translate-x-px" />+ ) : null}+ </button>+ <p className="text-xs text-[var(--color-text-secondary)] line-clamp-2">{target.primary_reason}</p>+ {target.primary_suggestion ? (+ <p className="text-xs text-[var(--color-text-tertiary)] italic line-clamp-3">+ {target.primary_suggestion}+ </p>+ ) : null}+ <div className="flex items-center gap-3 pt-1 text-[11px] text-[var(--color-text-tertiary)] flex-wrap">+ <span>Score {target.score.toFixed(1)}/10</span>+ <span>· {target.nloc} NLOC</span>+ <span>· {effortLabel[target.effort_bucket]} effort</span>+ <span>· {target.finding_count} findings</span>+ <span className="ml-auto tabular-nums">leverage {target.impact_per_effort.toFixed(2)}</span>+ </div>+ {onGeneratePrompt ? (+ <div className="pt-2">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onGeneratePrompt(target);+ }}+ className="group/ai inline-flex items-center gap-1.5 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-600 hover:bg-emerald-500/20 hover:border-emerald-500/60 transition-colors"+ title="Generate a ready-to-paste prompt for an AI coding agent"+ >+ <Sparkles className="h-3.5 w-3.5 transition-transform group-hover/ai:rotate-12" />+ AI fix prompt+ </button>+ </div>+ ) : null}+ </div>+ {expandable && target.all_findings && target.all_findings.length > 0 ? (+ <>+ <button+ type="button"+ onClick={() => setExpanded((e) => !e)}+ className="flex w-full items-center gap-2 px-4 py-2 text-xs text-[var(--color-text-secondary)] border-t border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)]"+ >+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}+ {expanded ? "Hide" : "Show"} all {target.all_findings.length} findings+ </button>+ {expanded ? (+ <ul className="divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)]">+ {target.all_findings.map((f) => (+ <li key={f.id} className="px-4 py-2 space-y-1">+ <div className="flex items-center gap-2 flex-wrap">+ <span+ className={`inline-block rounded px-1.5 py-px text-[10px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}+ >+ {SEVERITY_LABEL[f.severity]}+ </span>+ <span className="text-xs font-medium text-[var(--color-text-primary)]">+ {biomarkerLabel(f.biomarker_type)}+ </span>+ {f.function_name ? (+ <span className="text-xs font-mono text-[var(--color-text-tertiary)]">{f.function_name}</span>+ ) : null}+ <span className="ml-auto text-[11px] tabular-nums text-red-500">+ −{f.health_impact.toFixed(2)}+ </span>+ </div>+ <p className="text-[11px] text-[var(--color-text-tertiary)] line-clamp-2">{f.reason}</p>+ {onStatusChange ? (+ <div className="flex flex-wrap gap-1 pt-1">+ <StatusButton current={f.status} value="acknowledged" onClick={() => onStatusChange(f.id, "acknowledged")} label="Acknowledge" />+ <StatusButton current={f.status} value="resolved" onClick={() => onStatusChange(f.id, "resolved")} label="Resolved" />+ <StatusButton current={f.status} value="false_positive" onClick={() => onStatusChange(f.id, "false_positive")} label="False positive" />+ </div>+ ) : null}+ </li>+ ))}+ </ul>+ ) : null}+ </>+ ) : null}+ </div>+ );+}++function StatusButton({+ current,+ value,+ label,+ onClick,+}: {+ current?: string | undefined;+ value: FindingStatus;+ label: string;+ onClick: () => void;+}) {+ const isActive = current === value;+ return (+ <button+ type="button"+ onClick={onClick}+ className={`text-[10px] rounded px-1.5 py-0.5 border transition-colors ${+ isActive+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"+ : "border-[var(--color-border-default)] text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"+ }`}+ >+ {label}+ </button>+ );+}diff --git a/packages/ui/src/health/refactoring-target-list.tsx b/packages/ui/src/health/refactoring-target-list.tsxnew file mode 100644index 000000000..d15328d6a--- /dev/null+++ b/packages/ui/src/health/refactoring-target-list.tsx@@ -0,0 +1,40 @@+import { RefactoringCard, type RefactoringTarget, type FindingStatus } from "./refactoring-card";++export interface RefactoringTargetListProps {+ targets: RefactoringTarget[];+ onSelect?: ((target: RefactoringTarget) => void) | undefined;+ onStatusChange?: ((findingId: string, status: FindingStatus) => void) | undefined;+ onGeneratePrompt?: ((target: RefactoringTarget) => void) | undefined;+ emptyMessage?: string;+}++export function RefactoringTargetList({+ targets,+ onSelect,+ onStatusChange,+ onGeneratePrompt,+ emptyMessage = "No refactoring targets match the current filters.",+}: RefactoringTargetListProps) {+ if (targets.length === 0) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">+ {emptyMessage}+ </div>+ );+ }+ return (+ <div className="grid gap-3">+ {targets.map((t) => (+ <RefactoringCard+ key={t.file_path}+ target={t}+ onSelect={onSelect}+ onStatusChange={onStatusChange}+ onGeneratePrompt={onGeneratePrompt}+ />+ ))}+ </div>+ );+}++export type { RefactoringTarget, FindingStatus } from "./refactoring-card";diff --git a/packages/ui/src/health/risk-coverage-scatter.tsx b/packages/ui/src/health/risk-coverage-scatter.tsxnew file mode 100644index 000000000..2ece43952--- /dev/null+++ b/packages/ui/src/health/risk-coverage-scatter.tsx@@ -0,0 +1,156 @@+"use client";++import { useMemo, useState } from "react";++export interface RiskCoveragePoint {+ file_path: string;+ health_score: number;+ line_coverage_pct: number | null;+ nloc: number;+}++export interface RiskCoverageScatterProps {+ points: RiskCoveragePoint[];+ onSelect?: (point: RiskCoveragePoint) => void;+ height?: number;+}++/**+ * Health × Coverage quadrant chart. Y axis = health (0–10, higher is better),+ * X axis = line coverage % (0–100). Each dot is one file; radius encodes NLOC.+ *+ * Quadrant labels:+ * - Top-right (high health, high cov): Sweet spot+ * - Top-left (high health, low cov): Risky — fix tests first+ * - Bot-right (low health, high cov): Tested but messy+ * - Bot-left (low health, low cov): Critical untested hotspot+ */+export function RiskCoverageScatter({+ points,+ onSelect,+ height = 320,+}: RiskCoverageScatterProps) {+ const [hovered, setHovered] = useState<RiskCoveragePoint | null>(null);+ const data = useMemo(+ () => points.filter((p) => p.line_coverage_pct != null && Number.isFinite(p.health_score)),+ [points],+ );++ if (data.length === 0) {+ return (+ <div+ className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-tertiary)] text-center"+ style={{ minHeight: height }}+ >+ Ingest a coverage report to see the risk × coverage map for every file.+ </div>+ );+ }++ const W = 640;+ const H = height;+ const padL = 40;+ const padR = 12;+ const padT = 24;+ const padB = 30;+ const plotW = W - padL - padR;+ const plotH = H - padT - padB;++ const maxNloc = Math.max(...data.map((d) => d.nloc), 1);++ const xScale = (pct: number) => padL + (pct / 100) * plotW;+ const yScale = (score: number) => padT + ((10 - score) / 10) * plotH;+ const r = (nloc: number) => 2 + Math.min(7, Math.sqrt(nloc / maxNloc) * 7);++ const midX = xScale(60); // 60% coverage threshold+ const midY = yScale(7); // 7.0 health threshold++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <div className="mb-2 flex items-baseline gap-2">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Risk × coverage map+ </h3>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {data.length} files · dot size = NLOC+ </span>+ </div>+ <div className="relative">+ <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Risk vs coverage scatter plot">+ {/* Quadrant tinting */}+ <rect x={padL} y={padT} width={midX - padL} height={midY - padT} fill="currentColor" className="text-amber-500/5" />+ <rect x={midX} y={padT} width={W - padR - midX} height={midY - padT} fill="currentColor" className="text-emerald-500/5" />+ <rect x={padL} y={midY} width={midX - padL} height={H - padB - midY} fill="currentColor" className="text-red-500/8" />+ <rect x={midX} y={midY} width={W - padR - midX} height={H - padB - midY} fill="currentColor" className="text-yellow-500/5" />++ {/* Axes */}+ <line x1={padL} y1={padT} x2={padL} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />+ <line x1={padL} y1={H - padB} x2={W - padR} y2={H - padB} stroke="currentColor" strokeOpacity={0.2} />+ <line x1={midX} y1={padT} x2={midX} y2={H - padB} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />+ <line x1={padL} y1={midY} x2={W - padR} y2={midY} stroke="currentColor" strokeOpacity={0.1} strokeDasharray="3 3" />++ {/* Axis labels */}+ {[0, 25, 50, 75, 100].map((v) => (+ <g key={`x${v}`}>+ <text x={xScale(v)} y={H - padB + 14} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.5}>+ {v}%+ </text>+ </g>+ ))}+ {[0, 2, 4, 6, 8, 10].map((v) => (+ <g key={`y${v}`}>+ <text x={padL - 6} y={yScale(v) + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>+ {v}+ </text>+ </g>+ ))}+ <text x={W / 2} y={H - 4} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6}>+ Line coverage %+ </text>+ <text x={10} y={H / 2} fontSize={10} textAnchor="middle" fill="currentColor" opacity={0.6} transform={`rotate(-90 10 ${H / 2})`}>+ Health score+ </text>++ {/* Quadrant captions */}+ <text x={padL + 6} y={padT + 14} fontSize={10} fill="currentColor" opacity={0.5}>Risky — needs tests</text>+ <text x={W - padR - 6} y={padT + 14} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Sweet spot</text>+ <text x={padL + 6} y={H - padB - 6} fontSize={10} fill="currentColor" opacity={0.5}>Critical hotspot</text>+ <text x={W - padR - 6} y={H - padB - 6} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>Tested but messy</text>++ {/* Points */}+ {data.map((p) => {+ const cx = xScale(p.line_coverage_pct ?? 0);+ const cy = yScale(p.health_score);+ const isHovered = hovered?.file_path === p.file_path;+ const fillCls = p.health_score < 4 ? "fill-red-500" : p.health_score < 7 ? "fill-amber-500" : "fill-emerald-500";+ return (+ <circle+ key={p.file_path}+ cx={cx}+ cy={cy}+ r={r(p.nloc) * (isHovered ? 1.4 : 1)}+ className={`${fillCls} ${onSelect ? "cursor-pointer" : ""}`}+ fillOpacity={0.7}+ stroke={isHovered ? "white" : "none"}+ strokeWidth={1.5}+ onMouseEnter={() => setHovered(p)}+ onMouseLeave={() => setHovered(null)}+ onClick={onSelect ? () => onSelect(p) : undefined}+ >+ <title>{`${p.file_path}\nHealth ${p.health_score.toFixed(1)} · Cov ${p.line_coverage_pct?.toFixed(0)}% · NLOC ${p.nloc}`}</title>+ </circle>+ );+ })}+ </svg>+ {hovered ? (+ <div className="pointer-events-none absolute bottom-2 left-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1 text-[11px] shadow-md">+ <span className="font-mono text-[var(--color-text-primary)]">{hovered.file_path}</span>+ <span className="ml-2 text-[var(--color-text-tertiary)]">+ {hovered.health_score.toFixed(1)} · {hovered.line_coverage_pct?.toFixed(0)}% · {hovered.nloc} NLOC+ </span>+ </div>+ ) : null}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/health/score-breakdown.tsx b/packages/ui/src/health/score-breakdown.tsxnew file mode 100644index 000000000..699162de9--- /dev/null+++ b/packages/ui/src/health/score-breakdown.tsx@@ -0,0 +1,118 @@+import {+ CATEGORY_CAP,+ CATEGORY_LABEL,+ biomarkerLabel,+ type BiomarkerCategory,+} from "./biomarker-glossary";+import { SEVERITY_CHIP, SEVERITY_LABEL, scoreBadgeClass, type Severity } from "./tokens";++export interface ScoreBreakdownCategoryFinding {+ id: string;+ biomarker_type: string;+ severity: Severity;+ raw_impact: number;+ applied_impact: number;+ function_name: string | null;+ reason: string;+}++export interface ScoreBreakdownCategory {+ category: BiomarkerCategory | string;+ cap: number;+ raw_deduction: number;+ applied_deduction: number;+ capped: boolean;+ finding_count: number;+ findings: ScoreBreakdownCategoryFinding[];+}++export interface ScoreBreakdownProps {+ score: number;+ totalDeduction: number;+ categories: ScoreBreakdownCategory[];+}++export function ScoreBreakdown({+ score,+ totalDeduction,+ categories,+}: ScoreBreakdownProps) {+ return (+ <div className="space-y-3">+ <div className="flex items-baseline gap-3">+ <span+ className={`inline-flex items-center rounded-md px-2 py-1 text-lg font-bold tabular-nums ${scoreBadgeClass(score)}`}+ >+ {score.toFixed(1)}+ <span className="ml-0.5 text-xs font-normal opacity-70">/10</span>+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ 10.0 − {totalDeduction.toFixed(2)} = {score.toFixed(2)}+ </span>+ </div>++ <div className="space-y-2.5">+ {categories.map((c) => {+ const label =+ CATEGORY_LABEL[c.category as BiomarkerCategory] ?? c.category;+ const cap = CATEGORY_CAP[c.category as BiomarkerCategory] ?? c.cap;+ const pct = Math.min(100, (c.applied_deduction / Math.max(cap, 0.01)) * 100);+ return (+ <div+ key={c.category}+ className="rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3"+ >+ <div className="flex items-center justify-between gap-2 text-xs">+ <span className="font-medium text-[var(--color-text-primary)]">+ {label}+ </span>+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ −{c.applied_deduction.toFixed(2)} / cap −{cap.toFixed(1)}+ {c.capped ? <span className="ml-1 text-amber-500" title="Capped">(capped)</span> : null}+ </span>+ </div>+ <div className="mt-1.5 h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-muted)]">+ <div+ className="h-full bg-red-500/70"+ style={{ width: `${pct}%` }}+ />+ </div>+ {c.findings.length > 0 && (+ <ul className="mt-2 space-y-1">+ {c.findings.slice(0, 6).map((f) => (+ <li+ key={f.id}+ className="flex flex-wrap items-baseline gap-x-2 text-[11px]"+ >+ <span+ className={`inline-block rounded px-1.5 py-px text-[9px] uppercase font-semibold ${SEVERITY_CHIP[f.severity]}`}+ >+ {SEVERITY_LABEL[f.severity]}+ </span>+ <span className="font-medium text-[var(--color-text-primary)]">+ {biomarkerLabel(f.biomarker_type)}+ </span>+ {f.function_name ? (+ <span className="font-mono text-[var(--color-text-tertiary)]">+ {f.function_name}+ </span>+ ) : null}+ <span className="ml-auto tabular-nums text-red-500">+ −{f.applied_impact.toFixed(2)}+ </span>+ </li>+ ))}+ {c.findings.length > 6 ? (+ <li className="text-[11px] text-[var(--color-text-tertiary)]">+ + {c.findings.length - 6} more+ </li>+ ) : null}+ </ul>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+}diff --git a/packages/ui/src/health/severity-distribution.tsx b/packages/ui/src/health/severity-distribution.tsxnew file mode 100644index 000000000..0c54bc41d--- /dev/null+++ b/packages/ui/src/health/severity-distribution.tsx@@ -0,0 +1,63 @@+import { SEVERITY_BAR, SEVERITY_LABEL, type Severity } from "./tokens";++export interface SeverityBreakdown {+ critical: number;+ high: number;+ medium: number;+ low: number;+}++export interface SeverityDistributionProps {+ breakdown: SeverityBreakdown;+ /** When true, also renders the per-severity counts below the bar. */+ showCounts?: boolean;+ height?: "sm" | "md";+}++const ORDER: Severity[] = ["critical", "high", "medium", "low"];++export function SeverityDistribution({+ breakdown,+ showCounts = true,+ height = "sm",+}: SeverityDistributionProps) {+ const total =+ breakdown.critical + breakdown.high + breakdown.medium + breakdown.low;+ if (total === 0) {+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">No findings.</p>+ );+ }+ const h = height === "sm" ? "h-1.5" : "h-2";+ return (+ <div className="space-y-1.5">+ <div+ className={`flex w-full ${h} overflow-hidden rounded-full bg-[var(--color-bg-muted)]`}+ title={ORDER.map((s) => `${SEVERITY_LABEL[s]} ${breakdown[s]}`).join(" · ")}+ >+ {ORDER.map((s) => {+ const pct = (breakdown[s] / total) * 100;+ if (pct === 0) return null;+ return (+ <div+ key={s}+ className={SEVERITY_BAR[s]}+ style={{ width: `${pct}%` }}+ aria-label={`${SEVERITY_LABEL[s]} ${breakdown[s]}`}+ />+ );+ })}+ </div>+ {showCounts && (+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-[var(--color-text-tertiary)]">+ {ORDER.map((s) => (+ <span key={s} className="inline-flex items-center gap-1 tabular-nums">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${SEVERITY_BAR[s]}`} />+ {breakdown[s]} {SEVERITY_LABEL[s].toLowerCase()}+ </span>+ ))}+ </div>+ )}+ </div>+ );+}diff --git a/packages/ui/src/health/sparkline.tsx b/packages/ui/src/health/sparkline.tsxnew file mode 100644index 000000000..90469e60c--- /dev/null+++ b/packages/ui/src/health/sparkline.tsx@@ -0,0 +1,58 @@+export interface SparklineProps {+ values: number[];+ width?: number;+ height?: number;+ stroke?: string;+ fill?: string;+ /** Optional fixed Y-axis range. Defaults to min/max of values. */+ domain?: [number, number];+}++export function Sparkline({+ values,+ width = 80,+ height = 24,+ stroke = "currentColor",+ fill = "none",+ domain,+}: SparklineProps) {+ if (!values || values.length === 0) {+ return (+ <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden>+ <line+ x1={0}+ x2={width}+ y1={height / 2}+ y2={height / 2}+ stroke="currentColor"+ strokeOpacity={0.15}+ strokeDasharray="2 2"+ />+ </svg>+ );+ }+ if (values.length === 1) {+ return (+ <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden>+ <circle cx={width / 2} cy={height / 2} r={2} fill={stroke} />+ </svg>+ );+ }+ const [domMin, domMax] = domain ?? [Math.min(...values), Math.max(...values)];+ const range = domMax - domMin || 1;+ const stepX = width / (values.length - 1);+ const pts = values.map((v, i) => {+ const x = i * stepX;+ const y = height - ((v - domMin) / range) * height;+ return [x, y] as const;+ });+ const d = pts.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(" ");+ const area = `${d} L${width},${height} L0,${height} Z`;+ return (+ <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} aria-hidden>+ {fill !== "none" ? <path d={area} fill={fill} /> : null}+ <path d={d} stroke={stroke} strokeWidth={1.5} fill="none" strokeLinecap="round" strokeLinejoin="round" />+ <circle cx={pts[pts.length - 1]![0]} cy={pts[pts.length - 1]![1]} r={1.8} fill={stroke} />+ </svg>+ );+}diff --git a/packages/ui/src/health/tokens.ts b/packages/ui/src/health/tokens.tsnew file mode 100644index 000000000..6759d04c9--- /dev/null+++ b/packages/ui/src/health/tokens.ts@@ -0,0 +1,67 @@+/**+ * Shared color tokens + helpers for the code-health surface.+ *+ * Single source of truth so the score pill on a file row, the severity+ * chip on a finding card, and the KPI card text colors all agree.+ */++export type Severity = "critical" | "high" | "medium" | "low";++export const SEVERITY_ORDER: Record<Severity, number> = {+ low: 0,+ medium: 1,+ high: 2,+ critical: 3,+};++export const SEVERITY_LABEL: Record<Severity, string> = {+ critical: "Critical",+ high: "High",+ medium: "Medium",+ low: "Low",+};++export const SEVERITY_CHIP: Record<Severity, string> = {+ critical: "bg-red-500/15 text-red-500 border border-red-500/30",+ high: "bg-amber-500/15 text-amber-500 border border-amber-500/30",+ medium: "bg-yellow-500/15 text-yellow-600 border border-yellow-500/30",+ low: "bg-zinc-500/15 text-zinc-500 border border-zinc-500/30",+};++export const SEVERITY_BAR: Record<Severity, string> = {+ critical: "bg-red-500",+ high: "bg-amber-500",+ medium: "bg-yellow-500",+ low: "bg-zinc-500",+};++export function scoreTextColor(score: number | null | undefined): string {+ if (score == null) return "text-[var(--color-text-primary)]";+ if (score < 4) return "text-red-500";+ if (score < 7) return "text-amber-500";+ return "text-emerald-500";+}++export function scoreBadgeClass(score: number): string {+ if (score < 4) return "bg-red-500/15 text-red-500 border border-red-500/30";+ if (score < 7) return "bg-amber-500/15 text-amber-500 border border-amber-500/30";+ return "bg-emerald-500/15 text-emerald-500 border border-emerald-500/30";+}++export function coverageColor(pct: number): string {+ if (pct < 30) return "bg-red-500";+ if (pct < 60) return "bg-amber-500";+ if (pct < 80) return "bg-yellow-400";+ return "bg-emerald-500";+}++export function deltaColor(delta: number | null | undefined): string {+ if (delta == null || delta === 0) return "text-[var(--color-text-tertiary)]";+ return delta > 0 ? "text-emerald-500" : "text-red-500";+}++export function formatDelta(delta: number | null | undefined): string {+ if (delta == null) return "—";+ const sign = delta > 0 ? "+" : "";+ return `${sign}${delta.toFixed(2)}`;+}diff --git a/packages/ui/src/health/trend-chart.tsx b/packages/ui/src/health/trend-chart.tsxnew file mode 100644index 000000000..934c995db--- /dev/null+++ b/packages/ui/src/health/trend-chart.tsx@@ -0,0 +1,107 @@+"use client";++export interface TrendSeriesPoint {+ taken_at: string | null;+ hotspot_health: number;+ average_health: number;+ worst_performer_score: number | null;+}++export interface TrendChartProps {+ /** Oldest-first list of snapshots. */+ history: TrendSeriesPoint[];+ height?: number;+}++export function TrendChart({ history, height = 220 }: TrendChartProps) {+ if (!history || history.length === 0) {+ return (+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-center text-sm text-[var(--color-text-tertiary)]">+ No snapshots yet. Run <code>repowise init</code> twice (or once + an+ update) to start building a trend.+ </div>+ );+ }++ const W = 720;+ const H = height;+ const padL = 36;+ const padR = 12;+ const padT = 12;+ const padB = 26;+ const plotW = W - padL - padR;+ const plotH = H - padT - padB;++ const xScale = (i: number) =>+ history.length === 1 ? padL + plotW / 2 : padL + (i / (history.length - 1)) * plotW;+ const yScale = (v: number) => padT + ((10 - v) / 10) * plotH;++ const path = (key: "average_health" | "hotspot_health" | "worst_performer_score") => {+ const pts: [number, number][] = [];+ history.forEach((p, i) => {+ const v = p[key];+ if (v == null) return;+ pts.push([xScale(i), yScale(v as number)]);+ });+ return pts.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(" ");+ };++ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3">+ <div className="flex items-center justify-between gap-4 mb-2">+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ KPI trend+ </h3>+ <div className="flex items-center gap-3 text-[11px] text-[var(--color-text-tertiary)]">+ <Legend dot="bg-emerald-500" label="Average" />+ <Legend dot="bg-amber-500" label="Hotspot" />+ <Legend dot="bg-red-500" label="Worst" />+ </div>+ </div>+ <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} role="img" aria-label="Health KPI trend">+ {/* Y grid */}+ {[0, 2, 4, 6, 8, 10].map((v) => (+ <g key={v}>+ <line x1={padL} x2={W - padR} y1={yScale(v)} y2={yScale(v)} stroke="currentColor" strokeOpacity={0.08} />+ <text x={padL - 6} y={yScale(v) + 3} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>+ {v}+ </text>+ </g>+ ))}+ <path d={path("average_health")} stroke="#10b981" strokeWidth={1.8} fill="none" />+ <path d={path("hotspot_health")} stroke="#f59e0b" strokeWidth={1.8} fill="none" />+ <path d={path("worst_performer_score")} stroke="#ef4444" strokeWidth={1.4} fill="none" strokeDasharray="3 3" />+ {history.map((p, i) => (+ <g key={i}>+ <circle cx={xScale(i)} cy={yScale(p.average_health)} r={2.5} fill="#10b981" />+ <circle cx={xScale(i)} cy={yScale(p.hotspot_health)} r={2.5} fill="#f59e0b" />+ {p.worst_performer_score != null ? (+ <circle cx={xScale(i)} cy={yScale(p.worst_performer_score)} r={2} fill="#ef4444" />+ ) : null}+ </g>+ ))}+ {history.length > 1 ? (+ <>+ <text x={padL} y={H - 8} fontSize={10} fill="currentColor" opacity={0.5}>+ {history[0]?.taken_at ? new Date(history[0]!.taken_at!).toLocaleDateString() : ""}+ </text>+ <text x={W - padR} y={H - 8} fontSize={10} textAnchor="end" fill="currentColor" opacity={0.5}>+ {history[history.length - 1]?.taken_at+ ? new Date(history[history.length - 1]!.taken_at!).toLocaleDateString()+ : ""}+ </text>+ </>+ ) : null}+ </svg>+ </div>+ );+}++function Legend({ dot, label }: { dot: string; label: string }) {+ return (+ <span className="inline-flex items-center gap-1">+ <span className={`inline-block h-2 w-2 rounded-full ${dot}`} />+ {label}+ </span>+ );+}diff --git a/packages/ui/src/health/untested-hotspot-warning.tsx b/packages/ui/src/health/untested-hotspot-warning.tsxnew file mode 100644index 000000000..6a1166eb6--- /dev/null+++ b/packages/ui/src/health/untested-hotspot-warning.tsx@@ -0,0 +1,63 @@+import { AlertTriangle } from "lucide-react";++export interface UntestedHotspotEntry {+ file_path: string;+ line_coverage_pct: number | null;+ dependents_count?: number;+ commit_count_90d?: number | null;+ health_score?: number;+}++export interface UntestedHotspotWarningProps {+ entries: UntestedHotspotEntry[];+ limit?: number;+}++export function UntestedHotspotWarning({+ entries,+ limit = 5,+}: UntestedHotspotWarningProps) {+ if (entries.length === 0) return null;+ const shown = entries.slice(0, limit);+ return (+ <div className="rounded-lg border border-amber-500/40 bg-amber-500/5 p-4">+ <div className="flex items-start gap-2 mb-2">+ <AlertTriangle className="h-4 w-4 text-amber-500 mt-0.5" />+ <div>+ <h3 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Untested hotspots+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)]">+ High-churn, centrally depended-on files with little or no test coverage.+ </p>+ </div>+ </div>+ <ul className="space-y-1.5">+ {shown.map((e) => (+ <li+ key={e.file_path}+ className="flex flex-wrap items-baseline gap-x-3 text-sm"+ >+ <span className="font-mono text-[var(--color-text-primary)] truncate">+ {e.file_path}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)] tabular-nums">+ {e.line_coverage_pct == null+ ? "no coverage data"+ : `${e.line_coverage_pct.toFixed(0)}% covered`}+ {e.dependents_count != null && ` · ${e.dependents_count} dependents`}+ {e.commit_count_90d != null &&+ e.commit_count_90d > 0 &&+ ` · ${e.commit_count_90d} commits/90d`}+ </span>+ </li>+ ))}+ </ul>+ {entries.length > limit && (+ <p className="text-xs text-[var(--color-text-tertiary)] mt-2">+ + {entries.length - limit} more+ </p>+ )}+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/graph/page.tsx b/packages/web/src/app/repos/[id]/graph/page.tsxindex e03529eb5..95f961647 100644--- a/packages/web/src/app/repos/[id]/graph/page.tsx+++ b/packages/web/src/app/repos/[id]/graph/page.tsx@@ -9,6 +9,7 @@ import { GraphDocPanel } from "@/components/graph/graph-doc-panel";import { GraphTruncationBanner } from "@repowise-dev/ui/graph/graph-truncation-banner";import { getGraph } from "@/lib/api/graph";import type { GraphExportResponse } from "@/lib/api/types";+import { HealthRisksPanel } from "@/components/health/health-risks-panel";const VALID_VIEW_MODES = new Set(["module", "full", "architecture", "dead", "hotfiles", "unified"]);@@ -111,6 +112,15 @@ export default function GraphPage({onClose={() => setDocNodeId(null)}/>)}+ {!docNodeId && (+ <div className="absolute bottom-3 right-3 w-72 pointer-events-auto">+ <HealthRisksPanel+ repoId={repoId}+ title="Health risks"+ limit={5}+ />+ </div>+ )}</div></div></div>diff --git a/packages/web/src/app/repos/[id]/health/coverage/page.tsx b/packages/web/src/app/repos/[id]/health/coverage/page.tsxnew file mode 100644index 000000000..09a06b2e9--- /dev/null+++ b/packages/web/src/app/repos/[id]/health/coverage/page.tsx@@ -0,0 +1,372 @@+"use client";++import { useMemo, useState } from "react";+import { ArrowUpRight, Sparkles, TestTubeDiagonal } from "lucide-react";+import { useParams } from "next/navigation";+import useSWR from "swr";++import {+ AiPromptModal,+ CoverageBar,+ ModuleCoverageList,+ UntestedHotspotWarning,+ RiskCoverageScatter,+ buildCoverageAiPrompt,+ scoreBadgeClass,+ type CoverageFilePromptInput,+} from "@repowise-dev/ui/health";+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";++import {+ getHealthCoverage,+ type HealthCoverageResponse,+ getHealthOverview,+ type HealthOverviewResponse,+} from "@/lib/api/code-health";+import { HealthPageChrome } from "@/components/health/health-page-chrome";+import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";++export default function HealthCoveragePage() {+ const params = useParams<{ id: string }>();+ const id = params.id;+ const [selectedFile, setSelectedFile] = useState<string | null>(null);+ const [promptRow, setPromptRow] = useState<CoverageFilePromptInput | null>(null);++ const { data, isLoading, error } = useSWR<HealthCoverageResponse>(+ `code-health-coverage:${id}`,+ () => getHealthCoverage(id, { limit: 1000 }),+ { revalidateOnFocus: false },+ );++ const { data: overview } = useSWR<HealthOverviewResponse>(+ `code-health-overview:${id}`,+ () => getHealthOverview(id, 25),+ { revalidateOnFocus: false },+ );++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">+ <HealthPageChrome+ repoId={id}+ active="coverage"+ title="Test Coverage"+ icon={<TestTubeDiagonal className="h-5 w-5 text-emerald-500" />}+ subtitle={+ <>+ Ingest LCOV / Cobertura / Clover with{" "}+ <code className="px-1 rounded bg-[var(--color-bg-muted)]">+ repowise health --coverage <path>+ </code>+ </>+ }+ meta={overview?.meta}+ />++ {isLoading ? (+ <CoverageSkeleton />+ ) : error ? (+ <p className="text-sm text-red-500">Failed to load coverage data.</p>+ ) : !data || data.summary.file_count === 0 ? (+ <EmptyState />+ ) : (+ <CoverageView+ data={data}+ onSelect={(p) => setSelectedFile(p)}+ selectedFile={selectedFile}+ onGeneratePrompt={(r) => setPromptRow(r)}+ />+ )}++ <HealthFileDrawerHost+ repoId={id}+ filePath={selectedFile}+ onClose={() => setSelectedFile(null)}+ />++ <AiPromptModal+ open={promptRow !== null}+ onOpenChange={(open) => {+ if (!open) setPromptRow(null);+ }}+ filePath={promptRow?.file_path}+ title="AI test prompt"+ description="A ready-to-paste prompt that asks your AI coding agent to add tests for this file's uncovered lines and branches."+ getPrompt={+ promptRow+ ? (flavor) => buildCoverageAiPrompt({ row: promptRow, flavor })+ : null+ }+ />+ </div>+ );+}++function CoverageView({+ data,+ onSelect,+ selectedFile,+ onGeneratePrompt,+}: {+ data: HealthCoverageResponse;+ onSelect: (path: string) => void;+ selectedFile: string | null;+ onGeneratePrompt: (row: CoverageFilePromptInput) => void;+}) {+ const { summary, files, modules } = data;+ const [search, setSearch] = useState("");++ // Only flag a file as "untested hotspot" when it actually has coverage+ // data — defaulting missing coverage to 100% would hide the genuinely+ // uncovered files. We pair the health score and coverage so the chip+ // only fires on real risk-and-uncovered overlap.+ const untested = useMemo(+ () =>+ files+ .filter(+ (f) =>+ f.line_coverage_pct != null &&+ f.line_coverage_pct < 30 &&+ (f.health_score == null || f.health_score < 6),+ )+ .slice(0, 10)+ .map((f) => ({+ file_path: f.file_path,+ line_coverage_pct: f.line_coverage_pct,+ health_score: f.health_score,+ })),+ [files],+ );++ const scatterPoints = useMemo(+ () =>+ files+ .filter((f) => f.health_score != null && f.line_coverage_pct != null)+ .map((f) => ({+ file_path: f.file_path,+ health_score: f.health_score!,+ line_coverage_pct: f.line_coverage_pct,+ nloc: f.nloc ?? 0,+ })),+ [files],+ );++ const filteredFiles = useMemo(() => {+ if (!search) return files;+ const s = search.toLowerCase();+ return files.filter((f) => f.file_path.toLowerCase().includes(s));+ }, [files, search]);++ return (+ <div className="space-y-6">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">+ <SummaryCard label="Files">+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">+ {summary.file_count.toLocaleString()}+ </span>+ </SummaryCard>+ <SummaryCard label="Line coverage">+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">+ {summary.line_coverage_pct == null+ ? "—"+ : `${summary.line_coverage_pct.toFixed(1)}%`}+ </span>+ <p className="text-xs text-[var(--color-text-tertiary)] mt-1 tabular-nums">+ {summary.covered_lines.toLocaleString()} /{" "}+ {summary.total_lines.toLocaleString()} lines+ </p>+ </SummaryCard>+ <SummaryCard label="Branch coverage">+ <span className="text-2xl font-bold tabular-nums text-[var(--color-text-primary)]">+ {summary.branch_coverage_pct == null+ ? "—"+ : `${summary.branch_coverage_pct.toFixed(1)}%`}+ </span>+ </SummaryCard>+ <SummaryCard label="Source">+ <span className="text-lg font-semibold text-[var(--color-text-primary)] uppercase">+ {summary.source_format ?? "—"}+ </span>+ <p className="text-xs text-[var(--color-text-tertiary)] mt-1">+ {summary.ingested_at ? new Date(summary.ingested_at).toLocaleString() : "never"}+ </p>+ </SummaryCard>+ </div>++ <RiskCoverageScatter points={scatterPoints} onSelect={(p) => onSelect(p.file_path)} />++ {untested.length > 0 ? <UntestedHotspotWarning entries={untested} /> : null}++ <section className="space-y-2">+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">+ Module coverage ({modules.length})+ </h2>+ <ModuleCoverageList modules={modules} />+ </section>++ <section className="space-y-2">+ <div className="flex items-center gap-2">+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)] mr-auto">+ Files ({filteredFiles.length.toLocaleString()})+ </h2>+ <input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Filter path…"+ className="text-xs px-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"+ />+ </div>+ <FileCoverageTable+ files={filteredFiles}+ onSelect={onSelect}+ selectedFile={selectedFile}+ onGeneratePrompt={onGeneratePrompt}+ />+ </section>+ </div>+ );+}++function FileCoverageTable({+ files,+ onSelect,+ selectedFile,+ onGeneratePrompt,+}: {+ files: HealthCoverageResponse["files"];+ onSelect: (path: string) => void;+ selectedFile: string | null;+ onGeneratePrompt: (row: CoverageFilePromptInput) => void;+}) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden max-h-[600px] overflow-y-auto">+ <table className="w-full text-sm">+ <thead className="border-b border-[var(--color-border-default)] text-xs uppercase tracking-wide text-[var(--color-text-tertiary)] bg-[var(--color-bg-elevated)] sticky top-0">+ <tr>+ <th className="px-4 py-2 text-left font-medium">File</th>+ <th className="px-4 py-2 text-left font-medium w-64">Line coverage</th>+ <th className="px-4 py-2 text-right font-medium">Branch</th>+ <th className="px-4 py-2 text-right font-medium">Lines</th>+ <th className="px-4 py-2 text-right font-medium">Health</th>+ <th className="px-4 py-2 text-right font-medium w-12"></th>+ </tr>+ </thead>+ <tbody className="divide-y divide-[var(--color-border-default)]">+ {files.map((f) => {+ const isSelected = selectedFile === f.file_path;+ return (+ <tr+ key={f.file_path}+ className={`cursor-pointer hover:bg-[var(--color-bg-muted)] ${isSelected ? "bg-[var(--color-accent-muted)]/20" : ""}`}+ onClick={() => onSelect(f.file_path)}+ >+ <td className="px-4 py-2 font-mono text-xs text-[var(--color-text-primary)] truncate max-w-[480px]" title={f.file_path}>+ <span className="inline-flex items-center gap-1.5">+ <span className="truncate">{f.file_path}</span>+ <ArrowUpRight className="h-3 w-3 shrink-0 text-[var(--color-text-tertiary)]" />+ </span>+ </td>+ <td className="px-4 py-2">+ <CoverageBar value={f.line_coverage_pct} size="sm" />+ </td>+ <td className="px-4 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">+ {f.branch_coverage_pct == null+ ? "—"+ : `${f.branch_coverage_pct.toFixed(0)}%`}+ </td>+ <td className="px-4 py-2 text-right tabular-nums text-[var(--color-text-tertiary)]">+ {f.total_coverable_lines}+ </td>+ <td className="px-4 py-2 text-right tabular-nums">+ {f.health_score == null ? (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ ) : (+ <span className={`inline-block rounded px-1.5 py-0.5 text-xs font-semibold ${scoreBadgeClass(f.health_score)}`}>+ {f.health_score.toFixed(1)}+ </span>+ )}+ </td>+ <td className="px-2 py-2 text-right">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onGeneratePrompt({+ file_path: f.file_path,+ line_coverage_pct: f.line_coverage_pct,+ branch_coverage_pct: f.branch_coverage_pct,+ total_coverable_lines: f.total_coverable_lines,+ covered_lines: f.covered_lines,+ source_format: f.source_format,+ health_score: f.health_score ?? null,+ nloc: f.nloc ?? null,+ });+ }}+ title="Generate AI test prompt for this file"+ className="inline-flex items-center justify-center rounded-md p-1 text-[var(--color-text-tertiary)] hover:text-emerald-500 hover:bg-emerald-500/10 transition-colors"+ >+ <Sparkles className="h-3.5 w-3.5" />+ </button>+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++function SummaryCard({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider mb-1">+ {label}+ </p>+ {children}+ </div>+ );+}++function EmptyState() {+ return (+ <div className="rounded-lg border border-dashed border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-8">+ <div className="max-w-xl mx-auto text-center space-y-3">+ <h2 className="text-base font-semibold text-[var(--color-text-primary)]">+ No coverage data ingested yet+ </h2>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Run your test suite with coverage enabled, then ingest the report.+ You'll see a risk × coverage map, untested-hotspot warnings, and a+ per-module breakdown.+ </p>+ <pre className="inline-block px-4 py-2 rounded bg-[var(--color-bg-muted)] text-left text-xs font-mono">+ pytest --cov --cov-report=lcov{"\n"}+ repowise health --coverage coverage.lcov+ </pre>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Supported formats: LCOV · Cobertura · Clover.+ </p>+ </div>+ </div>+ );+}++function CoverageSkeleton() {+ return (+ <div className="space-y-6">+ <div className="grid grid-cols-4 gap-3">+ {Array.from({ length: 4 }).map((_, i) => (+ <Skeleton key={i} className="h-24 w-full rounded-lg" />+ ))}+ </div>+ <Skeleton className="h-72 w-full rounded-lg" />+ <Skeleton className="h-48 w-full rounded-lg" />+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/health/page.tsx b/packages/web/src/app/repos/[id]/health/page.tsxnew file mode 100644index 000000000..28917a665--- /dev/null+++ b/packages/web/src/app/repos/[id]/health/page.tsx@@ -0,0 +1,280 @@+"use client";++import { useMemo, useState } from "react";+import useSWR from "swr";+import { useParams } from "next/navigation";+import { HeartPulse, RotateCw, Search } from "lucide-react";+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+import { Button } from "@repowise-dev/ui/ui/button";+import {+ HealthKpiCards,+ HealthFileTable,+ BiomarkerList,+ ModuleRollupList,+ type FileSortField,+ type Severity,+} from "@repowise-dev/ui/health";+import {+ getHealthOverview,+ getHealthTrend,+ listHealthFiles,+ type HealthOverviewResponse,+ type HealthTrendResponse,+ type HealthFilesResponse,+} from "@/lib/api/code-health";+import { HealthPageChrome } from "@/components/health/health-page-chrome";+import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";++const PAGE_SIZE = 50;++export default function HealthPage() {+ const params = useParams<{ id: string }>();+ const id = params.id;++ const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(+ `code-health-overview:${id}`,+ () => getHealthOverview(id, 25),+ { revalidateOnFocus: false },+ );+ const { data: trend } = useSWR<HealthTrendResponse>(+ `code-health-trend:${id}`,+ () => getHealthTrend(id, 20),+ { revalidateOnFocus: false },+ );++ // File table state+ const [sortField, setSortField] = useState<FileSortField>("score");+ const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");+ const [search, setSearch] = useState("");+ const [onlyHotspots, setOnlyHotspots] = useState(false);+ const [onlyUntested, setOnlyUntested] = useState(false);+ const [onlyFailing, setOnlyFailing] = useState(false);+ const [offset, setOffset] = useState(0);+ const [minSeverity, setMinSeverity] = useState<Severity | "all">("all");+ const [selectedFile, setSelectedFile] = useState<string | null>(null);++ const filesKey = useMemo(+ () =>+ JSON.stringify({+ id,+ sortField,+ sortOrder,+ search,+ onlyHotspots,+ onlyUntested,+ onlyFailing,+ offset,+ }),+ [id, sortField, sortOrder, search, onlyHotspots, onlyUntested, onlyFailing, offset],+ );++ const { data: files, isLoading: filesLoading } = useSWR<HealthFilesResponse>(+ overview ? `code-health-files:${filesKey}` : null,+ () =>+ listHealthFiles(id, {+ sort: sortField,+ order: sortOrder,+ search: search || undefined,+ only_hotspots: onlyHotspots || undefined,+ only_untested: onlyUntested || undefined,+ only_failing: onlyFailing || undefined,+ offset,+ limit: PAGE_SIZE,+ }),+ { revalidateOnFocus: false, keepPreviousData: true },+ );++ const handleSort = (field: FileSortField) => {+ if (field === sortField) {+ setSortOrder((o) => (o === "asc" ? "desc" : "asc"));+ } else {+ setSortField(field);+ // Score: asc (worst first). Counts: desc. Path: asc.+ setSortOrder(["score", "line_coverage_pct", "file_path"].includes(field) ? "asc" : "desc");+ }+ setOffset(0);+ };++ const avgSeries = trend?.history?.slice().reverse().map((p) => p.average_health);+ const hotspotSeries = trend?.history?.slice().reverse().map((p) => p.hotspot_health);+ const worstSeries = trend?.history+ ?.slice()+ .reverse()+ .map((p) => p.worst_performer_score ?? 0);++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1600px]">+ <HealthPageChrome+ repoId={id}+ active="overview"+ title="Code Health"+ icon={<HeartPulse className="h-5 w-5 text-emerald-500" />}+ subtitle="Per-file health scores from CCN, nesting, duplication, coverage, and ownership biomarkers."+ meta={overview?.meta}+ actions={+ <Button size="sm" variant="outline" onClick={() => mutate()}>+ <RotateCw className="h-3.5 w-3.5 mr-1.5" /> Refresh+ </Button>+ }+ />++ {isLoading ? (+ <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-24 w-full rounded-lg" />+ ))}+ </div>+ ) : error ? (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] p-4 text-sm text-[var(--color-text-secondary)] flex items-center justify-between gap-2">+ <span>Couldn't load health data. Run <code>repowise init</code> to populate.</span>+ <Button size="sm" variant="outline" onClick={() => mutate()}>Retry</Button>+ </div>+ ) : overview ? (+ <>+ <HealthKpiCards+ summary={overview.summary}+ averageHistory={avgSeries}+ hotspotHistory={hotspotSeries}+ worstHistory={worstSeries}+ averageDelta={trend?.summary?.average_delta ?? undefined}+ hotspotDelta={trend?.summary?.hotspot_delta ?? undefined}+ />++ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">+ <div className="lg:col-span-2 space-y-3">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">+ Files {files?.total != null ? `(${files.total.toLocaleString()})` : ""}+ </h2>+ <div className="relative">+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-[var(--color-text-tertiary)]" />+ <input+ value={search}+ onChange={(e) => {+ setSearch(e.target.value);+ setOffset(0);+ }}+ placeholder="Filter path…"+ className="text-xs pl-7 pr-2 py-1.5 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] w-56 focus:outline-none focus:border-[var(--color-border-strong)]"+ />+ </div>+ <FilterChip active={onlyHotspots} onClick={() => { setOnlyHotspots((v) => !v); setOffset(0); }}>+ Hotspots+ </FilterChip>+ <FilterChip active={onlyUntested} onClick={() => { setOnlyUntested((v) => !v); setOffset(0); }}>+ Untested+ </FilterChip>+ <FilterChip active={onlyFailing} onClick={() => { setOnlyFailing((v) => !v); setOffset(0); }}>+ Failing+ </FilterChip>+ </div>++ {filesLoading && !files ? (+ <Skeleton className="h-64 w-full rounded-lg" />+ ) : (+ <HealthFileTable+ files={files?.files ?? []}+ sortField={sortField}+ sortOrder={sortOrder}+ onSort={handleSort}+ onSelect={(f) => setSelectedFile(f.file_path)}+ selectedPath={selectedFile}+ />+ )}++ {files && files.total > PAGE_SIZE ? (+ <div className="flex items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">+ <span>+ Showing {offset + 1}–{Math.min(offset + PAGE_SIZE, files.total)} of {files.total}+ </span>+ <div className="flex gap-1">+ <Button+ size="sm"+ variant="outline"+ disabled={offset === 0}+ onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))}+ >+ Prev+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={offset + PAGE_SIZE >= files.total}+ onClick={() => setOffset(offset + PAGE_SIZE)}+ >+ Next+ </Button>+ </div>+ </div>+ ) : null}+ </div>++ <div className="space-y-3">+ <div className="flex items-center gap-2">+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)] mr-auto">+ Findings+ </h2>+ <select+ value={minSeverity}+ onChange={(e) => setMinSeverity(e.target.value as Severity | "all")}+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"+ >+ <option value="all">All severities</option>+ <option value="low">Low+</option>+ <option value="medium">Medium+</option>+ <option value="high">High+</option>+ <option value="critical">Critical</option>+ </select>+ </div>+ <BiomarkerList+ findings={overview.top_findings}+ grouped+ minSeverity={minSeverity === "all" ? undefined : minSeverity}+ onSelect={(f) => setSelectedFile(f.file_path)}+ />+ </div>+ </div>++ {overview.modules && overview.modules.length > 0 ? (+ <div className="space-y-2">+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ By module+ </h2>+ <ModuleRollupList modules={overview.modules} />+ </div>+ ) : null}+ </>+ ) : null}++ <HealthFileDrawerHost+ repoId={id}+ filePath={selectedFile}+ onClose={() => setSelectedFile(null)}+ />+ </div>+ );+}++function FilterChip({+ active,+ onClick,+ children,+}: {+ active: boolean;+ onClick: () => void;+ children: React.ReactNode;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={`text-xs rounded-md px-2 py-1 border transition-colors ${+ active+ ? "bg-[var(--color-accent-muted)] text-[var(--color-accent-primary)] border-[var(--color-accent-primary)]/50"+ : "border-[var(--color-border-default)] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-strong)]"+ }`}+ >+ {children}+ </button>+ );+}diff --git a/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsx b/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsxnew file mode 100644index 000000000..c98850f5d--- /dev/null+++ b/packages/web/src/app/repos/[id]/health/refactoring-targets/page.tsx@@ -0,0 +1,275 @@+"use client";++import { useMemo, useState } from "react";+import { Wrench } from "lucide-react";+import { useParams } from "next/navigation";+import useSWR from "swr";++import {+ AiPromptModal,+ ImpactEffortQuadrant,+ RefactoringTargetList,+ biomarkerLabel,+ buildAiPrompt,+} from "@repowise-dev/ui/health";+import type { FindingStatus, RefactoringTarget } from "@repowise-dev/ui/health";+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";++import {+ getHealthOverview,+ getRefactoringTargets,+ updateFindingStatus,+ type HealthOverviewResponse,+ type RefactoringTargetsResponse,+ type RefactoringQuery,+} from "@/lib/api/code-health";+import { HealthPageChrome } from "@/components/health/health-page-chrome";+import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";++type GroupBy = "none" | "biomarker" | "module" | "effort";++const EFFORT_LABEL: Record<string, string> = {+ S: "Small (≤40 NLOC)",+ M: "Medium (≤150 NLOC)",+ L: "Large (≤400 NLOC)",+ XL: "Extra large (>400 NLOC)",+};++export default function RefactoringTargetsPage() {+ const params = useParams<{ id: string }>();+ const id = params.id;++ const [biomarker, setBiomarker] = useState<string | "all">("all");+ const [minSeverity, setMinSeverity] = useState<string>("all");+ const [maxEffort, setMaxEffort] = useState<string>("all");+ const [sort, setSort] = useState<RefactoringQuery["sort"]>("impact_per_effort");+ const [groupBy, setGroupBy] = useState<GroupBy>("none");+ const [selectedFile, setSelectedFile] = useState<string | null>(null);+ const [promptTarget, setPromptTarget] = useState<RefactoringTarget | null>(null);++ const queryKey = useMemo(+ () => JSON.stringify({ id, biomarker, minSeverity, maxEffort, sort }),+ [id, biomarker, minSeverity, maxEffort, sort],+ );++ const { data, isLoading, error, mutate } = useSWR<RefactoringTargetsResponse>(+ `code-health-refactoring:${queryKey}`,+ () =>+ getRefactoringTargets(id, {+ limit: 200,+ biomarker: biomarker === "all" ? undefined : biomarker,+ min_severity: minSeverity === "all" ? undefined : minSeverity,+ max_effort: maxEffort === "all" ? undefined : maxEffort,+ sort,+ }),+ { revalidateOnFocus: false },+ );++ const { data: overview } = useSWR<HealthOverviewResponse>(+ `code-health-overview:${id}`,+ () => getHealthOverview(id, 25),+ { revalidateOnFocus: false },+ );++ const handleStatus = async (findingId: string, status: FindingStatus) => {+ await updateFindingStatus(id, findingId, status);+ mutate();+ };++ const biomarkerOptions = useMemo(() => {+ const set = new Set<string>();+ (overview?.biomarkers ?? []).forEach((b) => set.add(b.biomarker_type));+ (data?.targets ?? []).forEach((t) => t.biomarkers.forEach((b) => set.add(b)));+ return [...set].sort();+ }, [overview, data]);++ const grouped = useMemo(() => {+ if (!data) return [];+ const targets = data.targets;+ if (groupBy === "none") return [{ key: "All", targets }];+ const groups = new Map<string, typeof targets>();+ for (const t of targets) {+ let key = "—";+ if (groupBy === "biomarker") key = biomarkerLabel(t.primary_biomarker);+ else if (groupBy === "module") key = t.module ?? "(no module)";+ else if (groupBy === "effort") key = EFFORT_LABEL[t.effort_bucket] ?? t.effort_bucket;+ if (!groups.has(key)) groups.set(key, []);+ groups.get(key)!.push(t);+ }+ return [...groups.entries()]+ .sort((a, b) => b[1].length - a[1].length)+ .map(([key, targets]) => ({ key, targets }));+ }, [data, groupBy]);++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1400px]">+ <HealthPageChrome+ repoId={id}+ active="refactoring"+ title="Refactoring targets"+ icon={<Wrench className="h-5 w-5 text-orange-500" />}+ subtitle="Files ranked by total health impact divided by an effort proxy (NLOC bucket). High leverage = high impact, low effort."+ meta={overview?.meta}+ />++ <div className="flex flex-wrap items-center gap-2">+ <Select+ label="Biomarker"+ value={biomarker}+ onChange={(v) => setBiomarker(v)}+ options={[+ { value: "all", label: "All biomarkers" },+ ...biomarkerOptions.map((b) => ({ value: b, label: biomarkerLabel(b) })),+ ]}+ />+ <Select+ label="Min severity"+ value={minSeverity}+ onChange={setMinSeverity}+ options={[+ { value: "all", label: "Any severity" },+ { value: "low", label: "Low+" },+ { value: "medium", label: "Medium+" },+ { value: "high", label: "High+" },+ { value: "critical", label: "Critical only" },+ ]}+ />+ <Select+ label="Max effort"+ value={maxEffort}+ onChange={setMaxEffort}+ options={[+ { value: "all", label: "Any effort" },+ { value: "S", label: "Small only" },+ { value: "M", label: "Medium+" },+ { value: "L", label: "Large+" },+ ]}+ />+ <Select+ label="Sort"+ value={sort ?? "impact_per_effort"}+ onChange={(v) => setSort(v as RefactoringQuery["sort"])}+ options={[+ { value: "impact_per_effort", label: "Leverage (impact ÷ effort)" },+ { value: "total_impact", label: "Total impact" },+ { value: "score", label: "Worst score" },+ { value: "finding_count", label: "Finding count" },+ ]}+ />+ <Select+ label="Group"+ value={groupBy}+ onChange={(v) => setGroupBy(v as GroupBy)}+ options={[+ { value: "none", label: "Flat list" },+ { value: "biomarker", label: "By biomarker" },+ { value: "module", label: "By module" },+ { value: "effort", label: "By effort" },+ ]}+ />+ </div>++ {isLoading ? (+ <div className="grid gap-3">+ {Array.from({ length: 5 }).map((_, i) => (+ <Skeleton key={i} className="h-28 w-full" />+ ))}+ </div>+ ) : error ? (+ <p className="text-sm text-red-500">Failed to load refactoring targets.</p>+ ) : !data || data.targets.length === 0 ? (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-6 text-sm text-[var(--color-text-secondary)]">+ No refactoring targets match the current filters. Try widening the+ severity or effort filters, or run{" "}+ <code className="px-1 rounded bg-[var(--color-bg-muted)]">repowise health</code>{" "}+ to populate findings.+ </div>+ ) : (+ <>+ <ImpactEffortQuadrant+ points={data.targets.map((t) => ({+ file_path: t.file_path,+ total_impact: t.total_impact,+ effort_bucket: t.effort_bucket,+ nloc: t.nloc,+ score: t.score,+ }))}+ onSelect={(p) => setSelectedFile(p.file_path)}+ />++ <p className="text-xs text-[var(--color-text-tertiary)]">+ Showing {data.targets.length} of {data.total} candidates.+ </p>++ <div className="space-y-6">+ {grouped.map((g) => (+ <section key={g.key} className="space-y-2">+ {groupBy !== "none" ? (+ <h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {g.key} <span className="text-[var(--color-text-secondary)]">({g.targets.length})</span>+ </h3>+ ) : null}+ <RefactoringTargetList+ targets={g.targets}+ onSelect={(t) => setSelectedFile(t.file_path)}+ onStatusChange={handleStatus}+ onGeneratePrompt={(t) => setPromptTarget(t)}+ />+ </section>+ ))}+ </div>+ </>+ )}++ <HealthFileDrawerHost+ repoId={id}+ filePath={selectedFile}+ onClose={() => setSelectedFile(null)}+ />++ <AiPromptModal+ open={promptTarget !== null}+ onOpenChange={(open) => {+ if (!open) setPromptTarget(null);+ }}+ filePath={promptTarget?.file_path}+ title="AI fix prompt"+ description="A ready-to-paste prompt that gives your AI coding agent every biomarker, line range, score deduction, and constraint needed to refactor this file in one focused pass."+ getPrompt={+ promptTarget+ ? (flavor) => buildAiPrompt({ target: promptTarget, flavor })+ : null+ }+ />+ </div>+ );+}++function Select({+ label,+ value,+ onChange,+ options,+}: {+ label: string;+ value: string;+ onChange: (v: string) => void;+ options: { value: string; label: string }[];+}) {+ return (+ <label className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-tertiary)]">+ <span className="uppercase tracking-wider">{label}</span>+ <select+ value={value}+ onChange={(e) => onChange(e.target.value)}+ className="text-xs px-2 py-1 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] text-[var(--color-text-primary)]"+ >+ {options.map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </select>+ </label>+ );+}diff --git a/packages/web/src/app/repos/[id]/health/trend/page.tsx b/packages/web/src/app/repos/[id]/health/trend/page.tsxnew file mode 100644index 000000000..381755e40--- /dev/null+++ b/packages/web/src/app/repos/[id]/health/trend/page.tsx@@ -0,0 +1,175 @@+"use client";++import { TrendingUp, AlertTriangle, TrendingDown } from "lucide-react";+import { useParams } from "next/navigation";+import useSWR from "swr";++import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+import { TrendChart, deltaColor, formatDelta } from "@repowise-dev/ui/health";++import {+ getHealthTrend,+ type HealthTrendResponse,+} from "@/lib/api/code-health";+import { HealthPageChrome } from "@/components/health/health-page-chrome";++export default function HealthTrendPage() {+ const params = useParams<{ id: string }>();+ const id = params.id;++ const { data, isLoading, error } = useSWR<HealthTrendResponse>(+ `code-health-trend:${id}`,+ () => getHealthTrend(id, 20),+ { revalidateOnFocus: false },+ );++ return (+ <div className="p-4 sm:p-6 space-y-6 max-w-[1400px]">+ <HealthPageChrome+ repoId={id}+ active="trend"+ title="Health trend"+ icon={<TrendingUp className="h-5 w-5 text-emerald-500" />}+ subtitle="KPI history over the most recent indexes. Snapshots are rolling — the latest 50 per repo."+ />++ {isLoading ? (+ <Skeleton className="h-64 w-full rounded-lg" />+ ) : error || !data ? (+ <p className="text-sm text-red-500">Failed to load trend data.</p>+ ) : (+ <>+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3">+ <DeltaCard+ label="Average health"+ current={data.summary.current_average_health}+ previous={data.summary.previous_average_health}+ delta={data.summary.average_delta}+ />+ <DeltaCard+ label="Hotspot health"+ current={data.summary.current_hotspot_health}+ previous={data.summary.previous_hotspot_health}+ delta={data.summary.hotspot_delta}+ />+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ Snapshots+ </p>+ <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {data.snapshot_count}+ </p>+ <p className="text-[11px] text-[var(--color-text-tertiary)] mt-1">+ rolling window: 50 max+ </p>+ </div>+ </div>++ {data.alerts.length > 0 ? (+ <div className="space-y-2">+ {data.alerts.map((a, i) => (+ <div+ key={i}+ className={`rounded-lg border p-3 flex items-start gap-2 ${+ a.kind === "declining"+ ? "border-red-500/40 bg-red-500/5"+ : "border-amber-500/40 bg-amber-500/5"+ }`}+ >+ <AlertTriangle+ className={`h-4 w-4 mt-0.5 ${a.kind === "declining" ? "text-red-500" : "text-amber-500"}`}+ />+ <div className="text-sm">+ <p className="font-medium text-[var(--color-text-primary)]">+ {a.kind === "declining" ? "Declining health" : "Predicted decline"}+ </p>+ <p className="text-xs text-[var(--color-text-secondary)]">{a.message}</p>+ </div>+ </div>+ ))}+ </div>+ ) : null}++ <TrendChart history={[...data.history].reverse()} />++ <section className="space-y-2">+ <h2 className="text-sm font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">+ Files that moved most since last index+ </h2>+ {data.file_deltas.length === 0 ? (+ <p className="text-sm text-[var(--color-text-tertiary)]">+ No per-file changes between the last two snapshots.+ </p>+ ) : (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] overflow-hidden">+ <table className="w-full text-sm">+ <thead className="bg-[var(--color-bg-elevated)] text-xs uppercase tracking-wider text-[var(--color-text-tertiary)]">+ <tr>+ <th className="text-left px-3 py-2 font-medium">File</th>+ <th className="text-right px-3 py-2 font-medium">Before</th>+ <th className="text-right px-3 py-2 font-medium">After</th>+ <th className="text-right px-3 py-2 font-medium">Δ</th>+ </tr>+ </thead>+ <tbody>+ {data.file_deltas.map((d) => (+ <tr+ key={d.file_path}+ className="border-t border-[var(--color-border-default)]"+ >+ <td className="px-3 py-2 font-mono text-xs text-[var(--color-text-primary)] truncate max-w-[480px]" title={d.file_path}>+ {d.file_path}+ </td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">+ {d.before.toFixed(1)}+ </td>+ <td className="px-3 py-2 text-right tabular-nums text-[var(--color-text-secondary)]">+ {d.after.toFixed(1)}+ </td>+ <td className={`px-3 py-2 text-right tabular-nums ${deltaColor(d.delta)}`}>+ <span className="inline-flex items-center gap-1">+ {d.delta < 0 ? <TrendingDown className="h-3 w-3" /> : null}+ {formatDelta(d.delta)}+ </span>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </section>+ </>+ )}+ </div>+ );+}++function DeltaCard({+ label,+ current,+ previous,+ delta,+}: {+ label: string;+ current: number;+ previous: number | null;+ delta: number | null;+}) {+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-4">+ <p className="text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider">+ {label}+ </p>+ <p className="mt-1 text-2xl font-bold text-[var(--color-text-primary)] tabular-nums">+ {current.toFixed(1)}+ <span className="text-base font-normal text-[var(--color-text-secondary)]">/10</span>+ </p>+ <p className={`text-[11px] tabular-nums mt-0.5 ${deltaColor(delta)}`}>+ {delta == null+ ? "no prior snapshot"+ : `${formatDelta(delta)} vs. ${previous?.toFixed(1) ?? "—"}`}+ </p>+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/hotspots/page.tsx b/packages/web/src/app/repos/[id]/hotspots/page.tsxindex 1b873b2b4..82c0ca949 100644--- a/packages/web/src/app/repos/[id]/hotspots/page.tsx+++ b/packages/web/src/app/repos/[id]/hotspots/page.tsx@@ -9,6 +9,7 @@ import { CommitCategoryDonut } from "@repowise-dev/ui/git/commit-category-donut"import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { getHotspots, getGitSummary } from "@/lib/api/git";+import { HealthRisksPanel } from "@/components/health/health-risks-panel";import { formatNumber } from "@repowise-dev/ui/lib/format";export const metadata: Metadata = { title: "Hotspots" };@@ -141,6 +142,8 @@ export default async function HotspotsPage({<HotspotTable hotspots={hotspots} repoId={id} /></div>+ <div className="space-y-4">+ <HealthRisksPanel repoId={id} title="Health risks in this list" limit={6} />{/* Top owners leaderboard */}{summary && summary.top_owners.length > 0 && (<Card>@@ -167,6 +170,7 @@ export default async function HotspotsPage({</CardContent></Card>)}+ </div></div></div>);diff --git a/packages/web/src/app/repos/[id]/ownership/page.tsx b/packages/web/src/app/repos/[id]/ownership/page.tsxindex 74315b855..8da07693a 100644--- a/packages/web/src/app/repos/[id]/ownership/page.tsx+++ b/packages/web/src/app/repos/[id]/ownership/page.tsx@@ -13,6 +13,7 @@ import { BusFactorPanel } from "@repowise-dev/ui/git/bus-factor-panel";import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";import { Skeleton } from "@repowise-dev/ui/ui/skeleton";import { getOwnership, getGitSummary, getHotspots } from "@/lib/api/git";+import { HealthRisksPanel } from "@/components/health/health-risks-panel";import { formatNumber } from "@repowise-dev/ui/lib/format";import { cn } from "@/lib/utils/cn";import type { OwnershipEntry, GitSummaryResponse, HotspotResponse } from "@/lib/api/types";@@ -152,16 +153,21 @@ export default function OwnershipPage() {)}</div>- {/* Detail table */}- {loadingEntries ? (- <div className="space-y-2">- {Array.from({ length: 8 }).map((_, i) => (- <Skeleton key={i} className="h-10 w-full" />- ))}+ {/* Detail table + health sidecar */}+ <div className="grid grid-cols-1 gap-6 xl:grid-cols-4">+ <div className="xl:col-span-3">+ {loadingEntries ? (+ <div className="space-y-2">+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className="h-10 w-full" />+ ))}+ </div>+ ) : (+ <OwnershipTable entries={entries ?? []} repoId={id} />+ )}</div>- ) : (- <OwnershipTable entries={entries ?? []} repoId={id} />- )}+ <HealthRisksPanel repoId={id} title="Lowest-health files" limit={6} />+ </div></div>);}diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsxnew file mode 100644index 000000000..e882df26f--- /dev/null+++ b/packages/web/src/components/health/health-file-drawer-host.tsx@@ -0,0 +1,36 @@+"use client";++import { HealthFileDrawer } from "@repowise-dev/ui/health";+import { useFileBreakdown } from "./use-file-breakdown";++export function HealthFileDrawerHost({+ repoId,+ filePath,+ onClose,+}: {+ repoId: string;+ filePath: string | null;+ onClose: () => void;+}) {+ const { data, isLoading } = useFileBreakdown(repoId, filePath);+ return (+ <HealthFileDrawer+ open={filePath !== null}+ onClose={onClose}+ loading={isLoading}+ metric={data?.metric ?? null}+ breakdown={+ data+ ? {+ score: data.breakdown.score,+ total_deduction: data.breakdown.total_deduction,+ categories: data.breakdown.categories,+ }+ : null+ }+ findings={data?.findings ?? []}+ suggestions={data?.suggestions ?? {}}+ fileViewHref={filePath ? `/repos/${repoId}/files?path=${encodeURIComponent(filePath)}` : undefined}+ />+ );+}diff --git a/packages/web/src/components/health/health-page-chrome.tsx b/packages/web/src/components/health/health-page-chrome.tsxnew file mode 100644index 000000000..91bf147d7--- /dev/null+++ b/packages/web/src/components/health/health-page-chrome.tsx@@ -0,0 +1,90 @@+"use client";++import Link from "next/link";+import { HealthTabs, type HealthTabKey } from "@repowise-dev/ui/health";++interface HealthPageChromeProps {+ repoId: string;+ active: HealthTabKey;+ title: string;+ subtitle?: React.ReactNode;+ icon?: React.ReactNode;+ meta?: {+ last_indexed_at: string | null;+ head_commit: string | null;+ snapshot_count: number;+ } | null;+ actions?: React.ReactNode;+}++function formatIndexedAt(iso: string | null): string {+ if (!iso) return "never";+ const d = new Date(iso);+ const diff = Date.now() - d.getTime();+ const minutes = Math.round(diff / 60_000);+ if (minutes < 1) return "just now";+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.round(minutes / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.round(hours / 24);+ if (days < 30) return `${days}d ago`;+ return d.toLocaleDateString();+}++export function HealthPageChrome({+ repoId,+ active,+ title,+ subtitle,+ icon,+ meta,+ actions,+}: HealthPageChromeProps) {+ return (+ <div className="space-y-3">+ <div className="flex flex-wrap items-start justify-between gap-4">+ <div className="min-w-0">+ <h1 className="text-xl font-semibold text-[var(--color-text-primary)] mb-1 flex items-center gap-2">+ {icon}+ {title}+ </h1>+ {subtitle ? (+ <p className="text-sm text-[var(--color-text-secondary)]">{subtitle}</p>+ ) : null}+ {meta ? (+ <p className="mt-1 text-[11px] text-[var(--color-text-tertiary)]">+ Indexed {formatIndexedAt(meta.last_indexed_at)}+ {meta.head_commit ? (+ <>+ {" "}+ · <span className="font-mono">{meta.head_commit.slice(0, 7)}</span>+ </>+ ) : null}+ {meta.snapshot_count > 0 ? <> · {meta.snapshot_count} snapshots</> : null}+ </p>+ ) : null}+ </div>+ {actions ? <div className="flex items-center gap-2 shrink-0">{actions}</div> : null}+ </div>+ <HealthTabs+ repoId={repoId}+ active={active}+ renderLink={({ href, label, active: isActive, icon, key }) => (+ <Link+ key={key}+ href={href}+ className={+ "inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors " ++ (isActive+ ? "border-emerald-500 text-[var(--color-text-primary)]"+ : "border-transparent text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] hover:border-[var(--color-border-default)]")+ }+ >+ {icon}+ {label}+ </Link>+ )}+ />+ </div>+ );+}diff --git a/packages/web/src/components/health/health-risks-panel.tsx b/packages/web/src/components/health/health-risks-panel.tsxnew file mode 100644index 000000000..31d75d458--- /dev/null+++ b/packages/web/src/components/health/health-risks-panel.tsx@@ -0,0 +1,64 @@+"use client";++import Link from "next/link";+import useSWR from "swr";+import { HealthBadge } from "@repowise-dev/ui/health";+import {+ getHealthOverview,+ type HealthOverviewResponse,+} from "@/lib/api/code-health";++export interface HealthRisksPanelProps {+ repoId: string;+ title?: string;+ limit?: number;+}++/** Inline health-risk sidecar: lowest-scoring files with badges.+ * Page-level only — does not modify any shared list/table component. */+export function HealthRisksPanel({+ repoId,+ title = "Health risks",+ limit = 6,+}: HealthRisksPanelProps) {+ const { data } = useSWR<HealthOverviewResponse>(+ `health-overview-panel:${repoId}`,+ () => getHealthOverview(repoId, limit),+ { revalidateOnFocus: false },+ );+ if (!data || data.files.length === 0) return null;+ const rows = [...data.files]+ .sort((a, b) => a.score - b.score)+ .slice(0, limit);+ return (+ <div className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 space-y-2">+ <div className="flex items-center justify-between text-xs">+ <span className="font-semibold text-[var(--color-text-primary)]">+ {title}+ </span>+ <Link+ href={`/repos/${repoId}/health`}+ className="text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)]"+ >+ See all →+ </Link>+ </div>+ <ul className="space-y-1.5">+ {rows.map((f) => (+ <li+ key={f.file_path}+ className="flex items-center gap-2 text-xs"+ >+ <HealthBadge score={f.score} />+ <span+ className="font-mono truncate text-[var(--color-text-secondary)]"+ title={f.file_path}+ >+ {f.file_path}+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/packages/web/src/components/health/use-file-breakdown.ts b/packages/web/src/components/health/use-file-breakdown.tsnew file mode 100644index 000000000..077654880--- /dev/null+++ b/packages/web/src/components/health/use-file-breakdown.ts@@ -0,0 +1,15 @@+"use client";++import useSWR from "swr";+import {+ getHealthFileBreakdown,+ type HealthFileBreakdownResponse,+} from "@/lib/api/code-health";++export function useFileBreakdown(repoId: string, filePath: string | null) {+ return useSWR<HealthFileBreakdownResponse>(+ filePath ? `code-health-breakdown:${repoId}:${filePath}` : null,+ () => getHealthFileBreakdown(repoId, filePath!),+ { revalidateOnFocus: false },+ );+}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex f750eddc0..d84d719b4 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -24,6 +24,10 @@ import {GitMerge,Users,Boxes,+ HeartPulse,+ TestTubeDiagonal,+ Wrench,+ TrendingUp,} from "lucide-react";import { cn } from "@/lib/utils/cn";import { ScrollArea } from "@repowise-dev/ui/ui/scroll-area";@@ -56,6 +60,10 @@ function repoNavItems(repoId: string): NavItem[] {{ label: "Overview", href: `/repos/${repoId}/overview`, icon: Activity },{ label: "Chat", href: `/repos/${repoId}`, icon: MessageSquare, exact: true },{ label: "Risk", href: `/repos/${repoId}/risk`, icon: ShieldAlert },+ { label: "Health", href: `/repos/${repoId}/health`, icon: HeartPulse, exact: true },+ { label: "Trend", href: `/repos/${repoId}/health/trend`, icon: TrendingUp },+ { label: "Coverage", href: `/repos/${repoId}/health/coverage`, icon: TestTubeDiagonal },+ { label: "Refactoring", href: `/repos/${repoId}/health/refactoring-targets`, icon: Wrench },{ label: "Graph", href: `/repos/${repoId}/graph`, icon: GitBranch },{ label: "C4 Diagram", href: `/repos/${repoId}/c4`, icon: Boxes },{ label: "Symbols", href: `/repos/${repoId}/symbols`, icon: Code2 },diff --git a/packages/web/src/lib/api/code-health.ts b/packages/web/src/lib/api/code-health.tsnew file mode 100644index 000000000..d5a42415b--- /dev/null+++ b/packages/web/src/lib/api/code-health.ts@@ -0,0 +1,303 @@+import { apiGet, apiPatch } from "./client";++export interface HealthFileMetric {+ file_path: string;+ score: number;+ max_ccn: number;+ max_nesting: number;+ nloc: number;+ has_test_file: boolean;+ line_coverage_pct: number | null;+ module: string | null;+ duplication_pct?: number | null;+}++export interface HealthFinding {+ id: string;+ file_path: string;+ biomarker_type: string;+ severity: "low" | "medium" | "high" | "critical";+ function_name: string | null;+ line_start: number | null;+ line_end: number | null;+ health_impact: number;+ reason: string;+ details: Record<string, unknown>;+ status: string;+}++export interface HealthModuleRow {+ module: string;+ file_count: number;+ nloc: number;+ average_health: number;+ worst_performer_path: string;+ worst_performer_score: number;+}++export interface BiomarkerBreakdownRow {+ biomarker_type: string;+ critical: number;+ high: number;+ medium: number;+ low: number;+ total: number;+}++export interface HealthOverviewResponse {+ summary: {+ file_count: number;+ average_health: number;+ hotspot_health?: number | null;+ worst_performer_path: string | null;+ worst_performer_score: number | null;+ open_findings: number;+ severity_breakdown?: { critical: number; high: number; medium: number; low: number };+ };+ files: HealthFileMetric[];+ top_findings: HealthFinding[];+ modules?: HealthModuleRow[];+ biomarkers?: BiomarkerBreakdownRow[];+ meta?: {+ last_indexed_at: string | null;+ head_commit: string | null;+ snapshot_count: number;+ };+}++export async function getHealthOverview(+ repoId: string,+ limit = 25,+): Promise<HealthOverviewResponse> {+ return apiGet<HealthOverviewResponse>(+ `/api/repos/${repoId}/health/overview`,+ { limit },+ );+}++export async function listHealthFindings(+ repoId: string,+ opts?: {+ biomarker_type?: string;+ file_path?: string;+ min_severity?: string;+ limit?: number;+ },+): Promise<HealthFinding[]> {+ return apiGet<HealthFinding[]>(`/api/repos/${repoId}/health/findings`, opts);+}++export interface HealthFilesResponse {+ total: number;+ offset: number;+ limit: number;+ files: HealthFileMetric[];+}++export interface HealthFilesQuery {+ limit?: number;+ offset?: number;+ sort?: string;+ order?: "asc" | "desc";+ search?: string;+ module?: string;+ only_hotspots?: boolean;+ only_untested?: boolean;+ only_failing?: boolean;+}++export async function listHealthFiles(+ repoId: string,+ opts?: HealthFilesQuery,+): Promise<HealthFilesResponse> {+ return apiGet<HealthFilesResponse>(+ `/api/repos/${repoId}/health/files`,+ opts as Record<string, string | number | boolean | undefined>,+ );+}++export interface FileBreakdownFinding {+ id: string;+ biomarker_type: string;+ severity: "low" | "medium" | "high" | "critical";+ raw_impact: number;+ applied_impact: number;+ function_name: string | null;+ reason: string;+}++export interface FileBreakdownCategory {+ category: string;+ cap: number;+ raw_deduction: number;+ applied_deduction: number;+ capped: boolean;+ finding_count: number;+ findings: FileBreakdownFinding[];+}++export interface HealthFileBreakdownResponse {+ file_path: string;+ metric: HealthFileMetric | null;+ breakdown: {+ score: number;+ total_deduction: number;+ categories: FileBreakdownCategory[];+ };+ findings: HealthFinding[];+ suggestions: Record<string, string>;+}++export async function getHealthFileBreakdown(+ repoId: string,+ filePath: string,+): Promise<HealthFileBreakdownResponse> {+ return apiGet<HealthFileBreakdownResponse>(+ `/api/repos/${repoId}/health/files/breakdown`,+ { file_path: filePath },+ );+}++export interface HealthTrendResponse {+ history: Array<{+ taken_at: string | null;+ hotspot_health: number;+ average_health: number;+ worst_performer_path: string | null;+ worst_performer_score: number | null;+ }>;+ summary: {+ current_hotspot_health: number;+ current_average_health: number;+ previous_hotspot_health: number | null;+ previous_average_health: number | null;+ hotspot_delta: number | null;+ average_delta: number | null;+ };+ alerts: Array<{+ kind: string;+ metric: string;+ current: number;+ baseline: number | null;+ delta: number;+ message: string;+ }>;+ file_deltas: Array<{ file_path: string; before: number; after: number; delta: number }>;+ snapshot_count: number;+}++export async function getHealthTrend(repoId: string, limit = 20): Promise<HealthTrendResponse> {+ return apiGet<HealthTrendResponse>(`/api/repos/${repoId}/health/trend`, { limit });+}++export async function updateFindingStatus(+ repoId: string,+ findingId: string,+ status: "open" | "acknowledged" | "resolved" | "false_positive",+): Promise<HealthFinding> {+ return apiPatch<HealthFinding>(+ `/api/repos/${repoId}/health/findings/${findingId}`,+ { status },+ );+}++export interface CoverageFileRow {+ file_path: string;+ source_format: string;+ line_coverage_pct: number;+ branch_coverage_pct: number | null;+ total_coverable_lines: number;+ ingested_at: string | null;+ ingested_commit_sha: string | null;+ covered_lines?: number[];+ health_score?: number;+ nloc?: number;+}++export interface ModuleCoverageRow {+ module: string;+ files: number;+ covered_lines: number;+ total_lines: number;+ line_coverage_pct: number;+}++export interface CoverageSummary {+ file_count: number;+ covered_lines: number;+ total_lines: number;+ line_coverage_pct: number | null;+ branch_coverage_pct: number | null;+ source_format: string | null;+ ingested_at: string | null;+ ingested_commit_sha: string | null;+}++export interface HealthCoverageResponse {+ summary: CoverageSummary;+ files: CoverageFileRow[];+ modules: ModuleCoverageRow[];+}++export async function getHealthCoverage(+ repoId: string,+ opts?: { file_path?: string; limit?: number },+): Promise<HealthCoverageResponse> {+ return apiGet<HealthCoverageResponse>(+ `/api/repos/${repoId}/health/coverage`,+ opts,+ );+}++export interface RefactoringTarget {+ file_path: string;+ score: number;+ nloc: number;+ module?: string | null;+ primary_biomarker: string;+ primary_severity: "low" | "medium" | "high" | "critical";+ primary_reason: string;+ primary_function: string | null;+ primary_line_start: number | null;+ primary_line_end: number | null;+ primary_suggestion?: string;+ primary_finding_id?: string;+ total_impact: number;+ finding_count: number;+ biomarkers: string[];+ effort_bucket: "S" | "M" | "L" | "XL";+ impact_per_effort: number;+ all_findings?: Array<{+ id: string;+ biomarker_type: string;+ severity: "low" | "medium" | "high" | "critical";+ function_name: string | null;+ health_impact: number;+ reason: string;+ status?: string;+ }>;+}++export interface RefactoringTargetsResponse {+ targets: RefactoringTarget[];+ total: number;+}++export interface RefactoringQuery {+ limit?: number;+ module?: string;+ biomarker?: string;+ min_severity?: string;+ max_effort?: string;+ sort?: "impact_per_effort" | "total_impact" | "score" | "finding_count";+}++export async function getRefactoringTargets(+ repoId: string,+ opts?: RefactoringQuery,+): Promise<RefactoringTargetsResponse> {+ return apiGet<RefactoringTargetsResponse>(+ `/api/repos/${repoId}/health/refactoring-targets`,+ opts as Record<string, string | number | boolean | undefined>,+ );+}diff --git a/tests/fixtures/coverage/sample.clover.xml b/tests/fixtures/coverage/sample.clover.xmlnew file mode 100644index 000000000..ff860d860--- /dev/null+++ b/tests/fixtures/coverage/sample.clover.xml@@ -0,0 +1,17 @@+<?xml version="1.0" encoding="UTF-8"?>+<coverage generated="1700000000">+ <project timestamp="1700000000">+ <package name="src">+ <file path="src/y.ts">+ <line num="1" count="3" type="stmt"/>+ <line num="2" count="0" type="stmt"/>+ <line num="3" count="2" type="cond" truecount="1" falsecount="0"/>+ <line num="4" count="1" type="stmt"/>+ </file>+ <file path="src/z.ts">+ <line num="1" count="5" type="stmt"/>+ <line num="2" count="5" type="stmt"/>+ </file>+ </package>+ </project>+</coverage>diff --git a/tests/fixtures/coverage/sample.cobertura.xml b/tests/fixtures/coverage/sample.cobertura.xmlnew file mode 100644index 000000000..cc78f2ab1--- /dev/null+++ b/tests/fixtures/coverage/sample.cobertura.xml@@ -0,0 +1,24 @@+<?xml version="1.0" ?>+<coverage line-rate="0.75" branch-rate="0.5" version="6.5.0">+ <sources><source>/repo</source></sources>+ <packages>+ <package name="src" line-rate="0.75" branch-rate="0.5">+ <classes>+ <class name="foo" filename="src/foo.py" line-rate="0.75" branch-rate="0.5">+ <lines>+ <line number="1" hits="2" branch="false"/>+ <line number="2" hits="0" branch="false"/>+ <line number="3" hits="5" branch="true" condition-coverage="50% (1/2)"/>+ <line number="4" hits="1" branch="false"/>+ </lines>+ </class>+ <class name="bar" filename="src/bar.py" line-rate="1.0" branch-rate="1.0">+ <lines>+ <line number="10" hits="3" branch="false"/>+ <line number="11" hits="3" branch="false"/>+ </lines>+ </class>+ </classes>+ </package>+ </packages>+</coverage>diff --git a/tests/fixtures/coverage/sample.lcov b/tests/fixtures/coverage/sample.lcovnew file mode 100644index 000000000..50533dade--- /dev/null+++ b/tests/fixtures/coverage/sample.lcov@@ -0,0 +1,22 @@+TN:+SF:src/foo.py+DA:1,2+DA:2,0+DA:3,5+DA:4,1+BRDA:3,0,0,1+BRDA:3,0,1,0+LF:4+LH:3+BRF:2+BRH:1+end_of_record+SF:src/bar.py+DA:10,1+DA:11,1+DA:12,1+end_of_record+SF:src/empty.py+DA:1,0+DA:2,0+end_of_recorddiff --git a/tests/fixtures/lang_samples/go/nested.go b/tests/fixtures/lang_samples/go/nested.gonew file mode 100644index 000000000..698cec783--- /dev/null+++ b/tests/fixtures/lang_samples/go/nested.go@@ -0,0 +1,21 @@+package sample++func DeeplyNested(x int) int {+ if x > 0 {+ for i := 0; i < x; i++ {+ if i%2 == 0 {+ for i > 0 {+ if i == 5 {+ return i+ }+ i--+ }+ }+ }+ }+ return 0+}++func Shallow(x int) int {+ return x + 1+}diff --git a/tests/fixtures/lang_samples/java/Nested.java b/tests/fixtures/lang_samples/java/Nested.javanew file mode 100644index 000000000..d2e6f9fda--- /dev/null+++ b/tests/fixtures/lang_samples/java/Nested.java@@ -0,0 +1,24 @@+class Nested {+ int deeplyNested(int x) {+ if (x > 0) {+ for (int i = 0; i < x; i++) {+ if (i % 2 == 0) {+ while (i > 0) {+ try {+ if (i == 5) {+ return i;+ }+ } catch (Exception e) {+ }+ i--;+ }+ }+ }+ }+ return 0;+ }++ int shallow(int x) {+ return x + 1;+ }+}diff --git a/tests/fixtures/lang_samples/javascript/nested.js b/tests/fixtures/lang_samples/javascript/nested.jsnew file mode 100644index 000000000..08fa70e91--- /dev/null+++ b/tests/fixtures/lang_samples/javascript/nested.js@@ -0,0 +1,21 @@+function deeplyNested(x) {+ if (x > 0) {+ for (let i = 0; i < x; i++) {+ if (i % 2 === 0) {+ while (i > 0) {+ try {+ if (i === 5) {+ return i;+ }+ } catch (e) {}+ i--;+ }+ }+ }+ }+ return 0;+}++function shallow(x) {+ return x + 1;+}diff --git a/tests/fixtures/lang_samples/python/complex.py b/tests/fixtures/lang_samples/python/complex.pynew file mode 100644index 000000000..f7bfa4f02--- /dev/null+++ b/tests/fixtures/lang_samples/python/complex.py@@ -0,0 +1,21 @@+def many_branches(a, b, c, d, e):+ if a:+ return 1+ elif b:+ return 2+ elif c:+ return 3+ elif d:+ return 4+ elif e:+ return 5+ if a and b:+ return 6+ if c or d:+ return 7+ if a and c and e:+ return 8+ for i in range(10):+ if i:+ continue+ return 0diff --git a/tests/fixtures/lang_samples/python/nested.py b/tests/fixtures/lang_samples/python/nested.pynew file mode 100644index 000000000..87006f8be--- /dev/null+++ b/tests/fixtures/lang_samples/python/nested.py@@ -0,0 +1,16 @@+def deeply_nested(x):+ if x > 0:+ for i in range(x):+ if i % 2 == 0:+ while i > 0:+ try:+ if i == 5:+ return i+ except Exception:+ pass+ i -= 1+ return 0+++def shallow(x):+ return x + 1diff --git a/tests/fixtures/lang_samples/rust/nested.rs b/tests/fixtures/lang_samples/rust/nested.rsnew file mode 100644index 000000000..8d354a544--- /dev/null+++ b/tests/fixtures/lang_samples/rust/nested.rs@@ -0,0 +1,20 @@+fn deeply_nested(x: i32) -> i32 {+ if x > 0 {+ for i in 0..x {+ if i % 2 == 0 {+ let mut j = i;+ while j > 0 {+ if j == 5 {+ return j;+ }+ j -= 1;+ }+ }+ }+ }+ 0+}++fn shallow(x: i32) -> i32 {+ x + 1+}diff --git a/tests/fixtures/lang_samples/typescript/nested.ts b/tests/fixtures/lang_samples/typescript/nested.tsnew file mode 100644index 000000000..1a2587598--- /dev/null+++ b/tests/fixtures/lang_samples/typescript/nested.ts@@ -0,0 +1,23 @@+export function deeplyNested(x: number): number {+ if (x > 0) {+ for (let i = 0; i < x; i++) {+ if (i % 2 === 0) {+ while (i > 0) {+ try {+ if (i === 5) {+ return i;+ }+ } catch (e) {+ // noop+ }+ i--;+ }+ }+ }+ }+ return 0;+}++export function shallow(x: number): number {+ return x + 1;+}diff --git a/tests/integration/test_health_coverage_integration.py b/tests/integration/test_health_coverage_integration.pynew file mode 100644index 000000000..157607bb4--- /dev/null+++ b/tests/integration/test_health_coverage_integration.py@@ -0,0 +1,107 @@+"""Phase 2 integration test: LCOV ingest → analyzer → coverage biomarkers.++Runs the full HealthAnalyzer over the existing ``sample_repo`` fixture+with a handcrafted LCOV report. Asserts:++- The coverage parser produces FileCoverage rows.+- Coverage flows onto HealthFileMetric.line_coverage_pct.+- The coverage_gap biomarker fires for a deliberately-low-coverage file.+"""++from __future__ import annotations++from pathlib import Path++from repowise.core.analysis.health import HealthAnalyzer+from repowise.core.analysis.health.coverage import parse as parse_coverage+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder+++def _build_parsed_files(repo_path: Path) -> tuple[list, GraphBuilder]:+ traverser = FileTraverser(repo_path)+ file_infos = list(traverser.traverse())+ parser = ASTParser()+ graph_builder = GraphBuilder()+ parsed_files = []+ for fi in file_infos:+ try:+ source = Path(fi.abs_path).read_bytes()+ parsed = parser.parse_file(fi, source)+ graph_builder.add_file(parsed)+ parsed_files.append(parsed)+ except Exception:+ continue+ graph_builder.build()+ return parsed_files, graph_builder+++def _python_file_paths(parsed_files: list) -> list[str]:+ return [pf.file_info.path for pf in parsed_files if pf.file_info.language == "python"]+++def test_coverage_ingest_flows_through_analyzer(sample_repo_path: Path) -> None:+ parsed_files, graph_builder = _build_parsed_files(sample_repo_path)+ py_paths = _python_file_paths(parsed_files)+ assert py_paths, "sample_repo should have Python files"++ # Pick two known files: give one full coverage, the other very low+ # coverage with a lot of uncovered lines so coverage_gap fires.+ high_cov_path = next(p for p in py_paths if p.endswith("calculator.py"))+ low_cov_path = next(p for p in py_paths if p.endswith("models.py"))++ lcov = f"""TN:+SF:{high_cov_path}+DA:1,1+DA:2,1+DA:3,1+DA:4,1+LF:4+LH:4+end_of_record+SF:{low_cov_path}+{chr(10).join(f'DA:{i},0' for i in range(1, 81))}+DA:81,1+DA:82,1+LF:82+LH:2+end_of_record+"""+ report_cov = parse_coverage(lcov)+ assert report_cov.source_format == "lcov"+ cov_paths = {f.file_path for f in report_cov.files}+ assert high_cov_path in cov_paths+ assert low_cov_path in cov_paths++ coverage_map = {+ fc.file_path: {+ "line_coverage_pct": fc.line_coverage_pct,+ "branch_coverage_pct": fc.branch_coverage_pct,+ "covered_lines": list(fc.covered_lines),+ "total_coverable_lines": fc.total_coverable_lines,+ }+ for fc in report_cov.files+ }++ analyzer = HealthAnalyzer(+ graph_builder.graph(),+ git_meta_map={},+ parsed_files=parsed_files,+ coverage_map=coverage_map,+ )+ report = analyzer.analyze()++ metrics_by_path = {m.file_path: m for m in report.metrics}+ assert metrics_by_path[high_cov_path].line_coverage_pct == 100.0+ low_metric = metrics_by_path[low_cov_path]+ assert low_metric.line_coverage_pct is not None+ assert low_metric.line_coverage_pct < 5.0++ # coverage_gap should fire for the low-coverage file.+ gap_findings = [+ f+ for f in report.findings+ if f.biomarker_type == "coverage_gap" and f.file_path == low_cov_path+ ]+ assert gap_findings, "expected coverage_gap biomarker for the under-tested file"+ assert gap_findings[0].details["line_coverage_pct"] < 5.0+ assert gap_findings[0].details["uncovered_lines"] >= 25diff --git a/tests/integration/test_health_perf_benchmark.py b/tests/integration/test_health_perf_benchmark.pynew file mode 100644index 000000000..70bf5bed0--- /dev/null+++ b/tests/integration/test_health_perf_benchmark.py@@ -0,0 +1,85 @@+"""Phase 4 performance budget: <30s on a 3,000-file synthetic repo.++Generates a synthetic repo of tiny Python modules on disk, builds the+graph, and runs the parallel HealthAnalyzer. The wall-clock budget is+generous on purpose — local laptops and CI runners differ, but a 30s+floor still flags regressions like ``O(N²)`` regressions in the+duplication detector or biomarker registry.++Marked ``slow`` so it can be skipped via ``pytest -m 'not slow'``. The+synthetic repo is laid out once per test session under a temp dir.+"""++from __future__ import annotations++import asyncio+import time+from pathlib import Path++import pytest++from repowise.core.analysis.health import HealthAnalyzer+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder++PERF_FILE_COUNT = 3_000+PERF_BUDGET_SECS = 30.0+++def _make_synthetic_repo(root: Path, count: int) -> None:+ """Write *count* tiny but realistic Python modules under *root*."""+ root.mkdir(parents=True, exist_ok=True)+ template = (+ "def f_{i}(x):\n"+ " if x > 0:\n"+ " for j in range(x):\n"+ " if j % 2 == 0:\n"+ " x += j\n"+ " else:\n"+ " x -= j\n"+ " return x\n"+ )+ per_dir = 50+ for i in range(count):+ bucket = i // per_dir+ d = root / f"pkg_{bucket:03d}"+ d.mkdir(exist_ok=True)+ (d / f"mod_{i:04d}.py").write_text(template.format(i=i), encoding="utf-8")++[email protected](scope="module")+def synthetic_repo(tmp_path_factory: pytest.TempPathFactory) -> Path:+ root = tmp_path_factory.mktemp("health_perf_repo")+ _make_synthetic_repo(root, PERF_FILE_COUNT)+ return root+++def test_health_analyzer_meets_30s_budget(synthetic_repo: Path) -> None:+ """End-to-end: parse → graph → parallel health analyze under 30s."""+ traverser = FileTraverser(synthetic_repo)+ file_infos = list(traverser.traverse())+ assert len(file_infos) >= PERF_FILE_COUNT, "synthetic repo missing files"++ parser = ASTParser()+ gb = GraphBuilder()+ parsed_files = []+ for fi in file_infos:+ try:+ parsed = parser.parse_file(fi, Path(fi.abs_path).read_bytes())+ except Exception:+ continue+ gb.add_file(parsed)+ parsed_files.append(parsed)+ gb.build()++ analyzer = HealthAnalyzer(gb.graph(), parsed_files=parsed_files)++ t0 = time.monotonic()+ report = asyncio.run(analyzer.analyze_async())+ elapsed = time.monotonic() - t0++ assert report.metrics, "expected per-file metrics"+ assert elapsed < PERF_BUDGET_SECS, (+ f"Health analyzer over {len(parsed_files)} files took {elapsed:.1f}s "+ f"(budget {PERF_BUDGET_SECS}s)"+ )diff --git a/tests/unit/health/__init__.py b/tests/unit/health/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/health/test_biomarkers.py b/tests/unit/health/test_biomarkers.pynew file mode 100644index 000000000..34095235e--- /dev/null+++ b/tests/unit/health/test_biomarkers.py@@ -0,0 +1,71 @@+"""Unit tests for the v1 biomarker detectors."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers import FileContext, detect_all+from repowise.core.analysis.health.biomarkers.brain_method import BrainMethodDetector+from repowise.core.analysis.health.biomarkers.complex_method import ComplexMethodDetector+from repowise.core.analysis.health.biomarkers.nested_complexity import (+ NestedComplexityDetector,+)+from repowise.core.analysis.health.complexity import FunctionComplexity+++def _ctx(fns: list[FunctionComplexity], *, dependents: int = 0) -> FileContext:+ return FileContext(+ file_path="src/example.py",+ language="python",+ nloc=sum(f.nloc for f in fns),+ has_test_file=False,+ module=None,+ function_metrics={f.name: f for f in fns},+ git_meta={},+ dependents_count=dependents,+ pagerank_score=0.0,+ )+++def test_complex_method_flags_high_ccn():+ fn = FunctionComplexity("biggie", 1, 80, ccn=20, max_nesting=2, cognitive=30, nloc=50)+ results = ComplexMethodDetector().detect(_ctx([fn]))+ assert len(results) == 1+ assert results[0].severity in ("medium", "high", "critical")+ assert results[0].details["ccn"] == 20+++def test_complex_method_skips_low_ccn():+ fn = FunctionComplexity("tiny", 1, 5, ccn=3, max_nesting=1, cognitive=2, nloc=4)+ assert ComplexMethodDetector().detect(_ctx([fn])) == []+++def test_nested_complexity_flags_deep_function():+ fn = FunctionComplexity("spiral", 1, 60, ccn=6, max_nesting=6, cognitive=20, nloc=40)+ results = NestedComplexityDetector().detect(_ctx([fn]))+ assert len(results) == 1+ assert results[0].severity in ("high", "critical")+++def test_nested_complexity_skips_shallow():+ fn = FunctionComplexity("flat", 1, 3, ccn=2, max_nesting=1, cognitive=1, nloc=3)+ assert NestedComplexityDetector().detect(_ctx([fn])) == []+++def test_brain_method_requires_centrality():+ fn = FunctionComplexity("lonely_brain", 1, 200, ccn=20, max_nesting=4, cognitive=40, nloc=150)+ # Too few dependents → not a brain method.+ assert BrainMethodDetector().detect(_ctx([fn], dependents=2)) == []+ # Hub file → flagged.+ results = BrainMethodDetector().detect(_ctx([fn], dependents=12))+ assert len(results) == 1+ assert results[0].details["dependents_count"] == 12+++def test_detect_all_runs_every_biomarker():+ fn = FunctionComplexity("monster", 1, 200, ccn=20, max_nesting=6, cognitive=60, nloc=150)+ ctx = _ctx([fn], dependents=15)+ results = detect_all(ctx)+ types = {r.biomarker_type for r in results}+ # All three v1 biomarkers should fire on this constructed monster.+ assert "complex_method" in types+ assert "nested_complexity" in types+ assert "brain_method" in typesdiff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pynew file mode 100644index 000000000..1af6bff3f--- /dev/null+++ b/tests/unit/health/test_complexity_walker.py@@ -0,0 +1,78 @@+"""Unit tests for the tree-sitter complexity walker.++These tests are best-effort: tree-sitter language packs may not all be+installed in CI. The walker returns ``[]`` when a language pack is+missing, so each assertion guards with ``pytest.skip`` rather than fail.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.analysis.health.complexity import walk_file_complexity++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 _find(results, name):+ matches = [r for r in results if r.name == name]+ return matches[0] if matches else None+++def test_python_nested_depth():+ results = _walk("python/nested.py", "python")+ deep = _find(results, "deeply_nested")+ shallow = _find(results, "shallow")+ assert deep is not None+ assert shallow is not None+ assert deep.max_nesting >= 4, f"expected ≥4 nesting, got {deep.max_nesting}"+ assert shallow.max_nesting == 0+ assert deep.ccn > shallow.ccn+++def test_python_complex_method_ccn():+ results = _walk("python/complex.py", "python")+ many = _find(results, "many_branches")+ assert many is not None+ assert many.ccn >= 9, f"expected CCN ≥ 9, got {many.ccn}"+++def test_typescript_nested_depth():+ results = _walk("typescript/nested.ts", "typescript")+ deep = _find(results, "deeplyNested")+ if deep is None:+ pytest.skip("typescript nested function not detected")+ assert deep.max_nesting >= 4+++def test_go_nested_depth():+ results = _walk("go/nested.go", "go")+ deep = _find(results, "DeeplyNested")+ if deep is None:+ pytest.skip("go function not detected")+ assert deep.max_nesting >= 4+++def test_javascript_nested_depth():+ results = _walk("javascript/nested.js", "javascript")+ deep = _find(results, "deeplyNested")+ if deep is None:+ pytest.skip("js function not detected")+ assert deep.max_nesting >= 4+++def test_unsupported_language_returns_empty():+ results = walk_file_complexity("/tmp/x.unknown", "klingon", b"")+ assert results == []diff --git a/tests/unit/health/test_coverage_biomarkers.py b/tests/unit/health/test_coverage_biomarkers.pynew file mode 100644index 000000000..b99200096--- /dev/null+++ b/tests/unit/health/test_coverage_biomarkers.py@@ -0,0 +1,126 @@+"""Unit tests for the Phase 2 coverage-aware biomarkers."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers import FileContext+from repowise.core.analysis.health.biomarkers.coverage_gap import CoverageGapDetector+from repowise.core.analysis.health.biomarkers.untested_hotspot import (+ UntestedHotspotDetector,+)+++def _ctx(+ *,+ path: str = "src/example.py",+ dependents: int = 0,+ has_test_file: bool = False,+ git_meta: dict | None = None,+ line_cov: float | None = None,+ branch_cov: float | None = None,+ covered_lines: set[int] | None = None,+ total_lines: int = 0,+) -> FileContext:+ return FileContext(+ file_path=path,+ language="python",+ nloc=100,+ has_test_file=has_test_file,+ module=None,+ git_meta=git_meta or {},+ dependents_count=dependents,+ line_coverage_pct=line_cov,+ branch_coverage_pct=branch_cov,+ covered_lines=covered_lines or set(),+ total_coverable_lines=total_lines,+ )+++# ---------------------------------------------------------------------------+# untested_hotspot+# ---------------------------------------------------------------------------+++def test_untested_hotspot_fires_when_low_coverage_and_hotspot() -> None:+ ctx = _ctx(+ git_meta={"is_hotspot": True},+ dependents=10,+ line_cov=12.0,+ total_lines=50,+ )+ results = UntestedHotspotDetector().detect(ctx)+ assert len(results) == 1+ assert results[0].severity == "critical"+++def test_untested_hotspot_silent_when_not_hotspot() -> None:+ ctx = _ctx(git_meta={"is_hotspot": False}, dependents=20, line_cov=5.0, total_lines=100)+ assert UntestedHotspotDetector().detect(ctx) == []+++def test_untested_hotspot_silent_when_dependents_low() -> None:+ ctx = _ctx(git_meta={"is_hotspot": True}, dependents=1, line_cov=5.0, total_lines=100)+ assert UntestedHotspotDetector().detect(ctx) == []+++def test_untested_hotspot_silent_when_well_covered() -> None:+ ctx = _ctx(git_meta={"is_hotspot": True}, dependents=10, line_cov=85.0, total_lines=100)+ assert UntestedHotspotDetector().detect(ctx) == []+++def test_untested_hotspot_falls_back_when_no_coverage_data() -> None:+ ctx = _ctx(+ git_meta={"commit_count_90d": 12},+ dependents=6,+ has_test_file=False,+ )+ results = UntestedHotspotDetector().detect(ctx)+ assert len(results) == 1+ assert "no coverage data" in results[0].reason+++def test_untested_hotspot_skips_when_paired_test_present() -> None:+ ctx = _ctx(+ git_meta={"commit_count_90d": 12},+ dependents=6,+ has_test_file=True,+ )+ assert UntestedHotspotDetector().detect(ctx) == []+++# ---------------------------------------------------------------------------+# coverage_gap+# ---------------------------------------------------------------------------+++def test_coverage_gap_fires_on_regular_gap() -> None:+ ctx = _ctx(line_cov=50.0, total_lines=100, covered_lines=set(range(1, 51)))+ results = CoverageGapDetector().detect(ctx)+ assert len(results) == 1+ assert results[0].severity == "low"+ assert results[0].details["uncovered_lines"] == 50+++def test_coverage_gap_fires_on_deep_gap() -> None:+ ctx = _ctx(line_cov=20.0, total_lines=200, covered_lines=set(range(1, 41)))+ results = CoverageGapDetector().detect(ctx)+ assert len(results) == 1+ assert results[0].severity == "high"+++def test_coverage_gap_skips_test_files() -> None:+ ctx = _ctx(+ path="tests/test_thing.py",+ line_cov=10.0,+ total_lines=200,+ )+ assert CoverageGapDetector().detect(ctx) == []+++def test_coverage_gap_skips_when_no_coverage_data() -> None:+ ctx = _ctx(line_cov=None, total_lines=0)+ assert CoverageGapDetector().detect(ctx) == []+++def test_coverage_gap_skips_well_covered() -> None:+ ctx = _ctx(line_cov=85.0, total_lines=200, covered_lines=set(range(1, 171)))+ assert CoverageGapDetector().detect(ctx) == []diff --git a/tests/unit/health/test_coverage_parsers.py b/tests/unit/health/test_coverage_parsers.pynew file mode 100644index 000000000..6303a45a4--- /dev/null+++ b/tests/unit/health/test_coverage_parsers.py@@ -0,0 +1,139 @@+"""Parser tests against handcrafted real-world-shaped fixtures."""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.analysis.health.coverage import (+ detect_format,+ is_test_file,+ paired_test_file,+ parse,+ parse_clover,+ parse_cobertura,+ parse_lcov,+)++FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "coverage"+++def _read(name: str) -> str:+ return (FIXTURES / name).read_text(encoding="utf-8")+++def test_lcov_parses_files_and_branches() -> None:+ report = parse_lcov(_read("sample.lcov"))+ assert report.source_format == "lcov"+ paths = {f.file_path: f for f in report.files}+ assert set(paths) == {"src/foo.py", "src/bar.py", "src/empty.py"}++ foo = paths["src/foo.py"]+ assert foo.total_coverable_lines == 4+ assert foo.line_coverage_pct == 75.0+ assert foo.branch_coverage_pct == 50.0+ assert foo.covered_lines == [1, 3, 4]++ bar = paths["src/bar.py"]+ assert bar.line_coverage_pct == 100.0+ assert bar.branch_coverage_pct is None++ empty = paths["src/empty.py"]+ assert empty.line_coverage_pct == 0.0+++def test_lcov_tolerates_missing_end_of_record() -> None:+ text = "SF:src/a.py\nDA:1,1\nDA:2,0\n"+ report = parse_lcov(text)+ assert len(report.files) == 1+ assert report.files[0].line_coverage_pct == 50.0+++def test_cobertura_parses_lines_and_branches() -> None:+ report = parse_cobertura(_read("sample.cobertura.xml"))+ assert report.source_format == "cobertura"+ paths = {f.file_path: f for f in report.files}+ assert set(paths) == {"src/foo.py", "src/bar.py"}+ foo = paths["src/foo.py"]+ assert foo.line_coverage_pct == 75.0+ assert foo.branch_coverage_pct == 50.0+ bar = paths["src/bar.py"]+ assert bar.line_coverage_pct == 100.0+ assert bar.branch_coverage_pct is None+++def test_cobertura_returns_empty_on_bad_xml() -> None:+ report = parse_cobertura("not xml at all")+ assert report.files == []+++def test_clover_parses_cond_lines() -> None:+ report = parse_clover(_read("sample.clover.xml"))+ assert report.source_format == "clover"+ paths = {f.file_path: f for f in report.files}+ y = paths["src/y.ts"]+ assert y.line_coverage_pct == 75.0+ assert y.branch_coverage_pct == 50.0+ z = paths["src/z.ts"]+ assert z.line_coverage_pct == 100.0+ assert z.branch_coverage_pct is None+++ "name, expected",+ [+ ("sample.lcov", "lcov"),+ ("sample.cobertura.xml", "cobertura"),+ ("sample.clover.xml", "clover"),+ ],+)+def test_detect_format(name: str, expected: str) -> None:+ assert detect_format(_read(name)) == expected+++def test_detect_format_unknown() -> None:+ assert detect_format("hello world") is None+ assert detect_format("") is None+++def test_parse_dispatches_via_detect() -> None:+ assert parse(_read("sample.lcov")).source_format == "lcov"+ assert parse(_read("sample.cobertura.xml")).source_format == "cobertura"+ assert parse(_read("sample.clover.xml")).source_format == "clover"+++def test_parse_with_explicit_format_override() -> None:+ # Force lcov parser on weird content — should yield empty rather than crash.+ report = parse("hello world", format="lcov")+ assert report.files == []+++ "path, expected",+ [+ ("src/foo.py", False),+ ("src/test_foo.py", True),+ ("src/foo_test.py", True),+ ("src/foo.test.ts", True),+ ("src/foo.test.tsx", True),+ ("src/foo.spec.js", True),+ ("src/foo_test.go", True),+ ("tests/integration/x.py", True),+ ("packages/core/x.py", False),+ ("__tests__/something.js", True),+ ],+)+def test_is_test_file(path: str, expected: bool) -> None:+ assert is_test_file(path) is expected+++def test_is_test_file_uses_source_imports() -> None:+ src = "import pytest\n\ndef test_x():\n pass\n"+ assert is_test_file("weird/path/name.py", src) is True+++def test_paired_test_file_finds_partner() -> None:+ all_paths = {"src/foo.py", "tests/test_foo.py", "src/bar.py"}+ assert paired_test_file("src/foo.py", all_paths) == "tests/test_foo.py"+ assert paired_test_file("src/bar.py", all_paths) is Nonediff --git a/tests/unit/health/test_dry_violation.py b/tests/unit/health/test_dry_violation.pynew file mode 100644index 000000000..81309219b--- /dev/null+++ b/tests/unit/health/test_dry_violation.py@@ -0,0 +1,75 @@+"""DRY Violation biomarker tests."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers import FileContext+from repowise.core.analysis.health.biomarkers.dry_violation import DryViolationDetector+from repowise.core.analysis.health.duplication import ClonePair+++def _ctx(file_path: str, pairs: list[ClonePair], dup_pct: float | None) -> FileContext:+ return FileContext(+ file_path=file_path,+ language="python",+ nloc=200,+ has_test_file=False,+ module=None,+ function_metrics={},+ git_meta={},+ dependents_count=0,+ pagerank_score=0.0,+ clones=pairs,+ duplication_pct=dup_pct,+ )+++def _pair(a: str, b: str, *, lines: int = 12, co_change: int = 0) -> ClonePair:+ return ClonePair(+ file_a=a,+ file_b=b,+ a_start_line=10,+ a_end_line=10 + lines - 1,+ b_start_line=20,+ b_end_line=20 + lines - 1,+ token_count=80,+ co_change_count=co_change,+ )+++def test_dry_violation_skips_when_no_clones():+ ctx = _ctx("a.py", [], None)+ assert DryViolationDetector().detect(ctx) == []+++def test_dry_violation_skips_low_duplication():+ pair = _pair("a.py", "b.py", lines=10)+ ctx = _ctx("a.py", [pair], dup_pct=3.0)+ assert DryViolationDetector().detect(ctx) == []+++def test_dry_violation_fires_on_significant_duplication():+ pair = _pair("a.py", "b.py", lines=20)+ ctx = _ctx("a.py", [pair], dup_pct=15.0)+ out = DryViolationDetector().detect(ctx)+ assert len(out) == 1+ assert out[0].details["worst_clone_partner"] == "b.py"+ assert out[0].details["clone_pair_count"] == 1+ # Inactive clone, mid-sized → low severity.+ assert out[0].severity == "low"+++def test_dry_violation_promotes_severity_for_active_clones():+ pair = _pair("a.py", "b.py", lines=20, co_change=8)+ ctx = _ctx("a.py", [pair], dup_pct=30.0)+ out = DryViolationDetector().detect(ctx)+ assert out[0].severity == "high"+ assert out[0].details["worst_clone_co_change"] == 8+++def test_dry_violation_picks_worst_clone():+ big_dormant = _pair("a.py", "b.py", lines=30, co_change=0)+ small_active = _pair("a.py", "c.py", lines=10, co_change=10)+ ctx = _ctx("a.py", [big_dormant, small_active], dup_pct=20.0)+ out = DryViolationDetector().detect(ctx)+ # Active clone wins regardless of size.+ assert out[0].details["worst_clone_partner"] == "c.py"diff --git a/tests/unit/health/test_duplication.py b/tests/unit/health/test_duplication.pynew file mode 100644index 000000000..cbc7f912a--- /dev/null+++ b/tests/unit/health/test_duplication.py@@ -0,0 +1,153 @@+"""Unit tests for the native Rabin-Karp duplication detector."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from repowise.core.analysis.health.duplication import (+ DEFAULT_MIN_LINES,+ DEFAULT_WINDOW_TOKENS,+ detect_clones,+ tokenize_file,+)+from repowise.core.analysis.health.duplication.rabin_karp import (+ index_by_hash,+ rolling_hashes,+)+from repowise.core.analysis.health.duplication.tokenizer import Token+++def _pf(path: str, abs_path: str, language: str = "python") -> SimpleNamespace:+ file_info = SimpleNamespace(path=path, abs_path=abs_path, language=language)+ return SimpleNamespace(file_info=file_info, symbols=[])+++def _tok(kind: str, line: int = 1) -> Token:+ return Token(kind=kind, start_line=line, end_line=line, start_byte=0, end_byte=0)+++def test_rolling_hash_matches_identical_streams():+ a = [_tok(k) for k in ["ID", "(", "ID", ",", "ID", ")", "ID"]]+ b = list(a)+ ha = rolling_hashes("a.py", a, window=4)+ hb = rolling_hashes("b.py", b, window=4)+ assert len(ha) == len(a) - 4 + 1+ assert {w.hash_value for w in ha} == {w.hash_value for w in hb}+++def test_rolling_hash_window_too_large_returns_empty():+ a = [_tok("ID")] * 3+ assert rolling_hashes("a.py", a, window=10) == []+++def test_index_by_hash_groups_collisions():+ a = [_tok(k) for k in ["ID"] * 10]+ h = rolling_hashes("a.py", a, window=4)+ bucket = index_by_hash(h)+ # All windows are identical → one bucket, multiple entries.+ assert len(bucket) == 1+ assert sum(len(v) for v in bucket.values()) == len(h)+++def test_tokenize_file_drops_comments_and_normalizes_identifiers():+ source = b"def add(a, b):\n # comment\n return a + b + 42\n"+ toks = tokenize_file("python", source)+ kinds = [t.kind for t in toks]+ assert "ID" in kinds # identifier collapsed+ assert "LIT" in kinds # literal 42 collapsed+ # The comment text never appears.+ assert not any("comment" in k for k in kinds)+++def _write(tmp_path: Path, name: str, src: str) -> Path:+ p = tmp_path / name+ p.write_text(src)+ return p+++def test_detect_clones_finds_duplicate_function(tmp_path: Path):+ body = "\n".join(+ [+ "def doit(x, y, z):",+ " if x:",+ " a = x + y",+ " else:",+ " a = x - y",+ " if z:",+ " b = a * 2",+ " else:",+ " b = a - 1",+ " return a + b + x + y + z",+ "",+ ]+ )+ src_a = body+ # Identical structure, renamed identifiers → must still match.+ src_b = body.replace("doit", "renamed").replace("x", "p").replace("y", "q")+ a = _write(tmp_path, "a.py", src_a)+ b = _write(tmp_path, "b.py", src_b)+ parsed = [+ _pf("a.py", str(a)),+ _pf("b.py", str(b)),+ ]+ report = detect_clones(parsed, window_tokens=20, min_lines=4)+ assert report.pairs, "expected at least one clone pair"+ pair = report.pairs[0]+ assert {pair.file_a, pair.file_b} == {"a.py", "b.py"}+ assert pair.a_line_count >= 4+ # No co-change history was provided → score stays 0.+ assert pair.co_change_count == 0+ # Duplication percentage should be populated for both files.+ assert "a.py" in report.duplication_pct+ assert "b.py" in report.duplication_pct+++def test_detect_clones_attaches_co_change_count(tmp_path: Path):+ body = "\n".join(+ [+ "def doit(x, y, z):",+ " total = 0",+ " for i in range(10):",+ " if i % 2:",+ " total += i + x",+ " else:",+ " total -= i - y",+ " return total + z",+ "",+ ]+ )+ a = _write(tmp_path, "a.py", body)+ b = _write(tmp_path, "b.py", body.replace("doit", "twin"))+ parsed = [_pf("a.py", str(a)), _pf("b.py", str(b))]+ git_meta_map = {+ "a.py": {+ "co_change_partners_json": json.dumps([{"file_path": "b.py", "co_change_count": 7}])+ },+ "b.py": {+ "co_change_partners_json": json.dumps([{"file_path": "a.py", "co_change_count": 5}])+ },+ }+ report = detect_clones(parsed, git_meta_map, window_tokens=20, min_lines=4)+ assert report.pairs+ # Max of the two reported directions wins.+ assert report.pairs[0].co_change_count == 7+++def test_detect_clones_skips_files_without_duplicates(tmp_path: Path):+ a = _write(tmp_path, "a.py", "def f():\n return 1\n")+ b = _write(tmp_path, "b.py", "def g():\n return 2\n")+ parsed = [_pf("a.py", str(a)), _pf("b.py", str(b))]+ report = detect_clones(parsed, window_tokens=DEFAULT_WINDOW_TOKENS, min_lines=DEFAULT_MIN_LINES)+ assert report.pairs == []+ assert report.duplication_pct == {}++[email protected]("language", ["python"])+def test_tokenize_file_returns_empty_for_unsupported_language(language: str):+ # An obviously invalid language code yields an empty stream rather+ # than raising.+ assert tokenize_file("not-a-language", b"x = 1\n") == []diff --git a/tests/unit/health/test_health_config.py b/tests/unit/health/test_health_config.pynew file mode 100644index 000000000..79f6fee20--- /dev/null+++ b/tests/unit/health/test_health_config.py@@ -0,0 +1,84 @@+"""Tests for `.repowise/health-rules.json` overrides."""++from __future__ import annotations++import json+from pathlib import Path++from repowise.core.analysis.health.config import HealthConfig+++def _write(tmp_path: Path, payload: dict) -> Path:+ repowise = tmp_path / ".repowise"+ repowise.mkdir()+ p = repowise / "health-rules.json"+ p.write_text(json.dumps(payload))+ return tmp_path+++def test_load_missing_file_returns_empty(tmp_path: Path):+ cfg = HealthConfig.load(tmp_path)+ assert cfg.disabled_biomarkers == []+ assert cfg.rules == []+++def test_load_parses_repo_wide_disabled(tmp_path: Path):+ _write(tmp_path, {"disabled_biomarkers": ["dry_violation", "primitive_obsession"]})+ cfg = HealthConfig.load(tmp_path)+ assert cfg.disabled_biomarkers == ["dry_violation", "primitive_obsession"]+++def test_per_file_disabled_matches_globs(tmp_path: Path):+ _write(+ tmp_path,+ {+ "rules": [+ {+ "path": "src/legacy/*",+ "disabled_biomarkers": ["complex_method", "large_method"],+ },+ {+ "path": "**/*.generated.ts",+ "disabled_biomarkers": ["dry_violation"],+ },+ ]+ },+ )+ cfg = HealthConfig.load(tmp_path)+ files = [+ "src/legacy/old.py",+ "src/legacy/older.py",+ "src/modern/api.py",+ "frontend/lib/types.generated.ts",+ ]+ pfd = cfg.per_file_disabled(files)+ assert pfd["src/legacy/old.py"] == {"complex_method", "large_method"}+ assert pfd["src/legacy/older.py"] == {"complex_method", "large_method"}+ assert "src/modern/api.py" not in pfd+ assert pfd["frontend/lib/types.generated.ts"] == {"dry_violation"}+++def test_to_analyzer_config_shape(tmp_path: Path):+ _write(+ tmp_path,+ {+ "disabled_biomarkers": ["bumpy_road"],+ "rules": [{"path": "src/*", "disabled_biomarkers": ["large_method"]}],+ },+ )+ cfg = HealthConfig.load(tmp_path)+ out = cfg.to_analyzer_config(["src/foo.py", "test/bar.py"])+ assert out["disabled_biomarkers"] == ["bumpy_road"]+ pfd = out["per_file_disabled"]+ assert isinstance(pfd, dict)+ assert pfd["src/foo.py"] == {"large_method"}+ assert "test/bar.py" not in pfd+++def test_malformed_file_falls_back_silently(tmp_path: Path):+ repowise = tmp_path / ".repowise"+ repowise.mkdir()+ (repowise / "health-rules.json").write_text("{not json")+ cfg = HealthConfig.load(tmp_path)+ assert cfg.disabled_biomarkers == []+ assert cfg.rules == []diff --git a/tests/unit/health/test_organizational_biomarkers.py b/tests/unit/health/test_organizational_biomarkers.pynew file mode 100644index 000000000..11a04e18a--- /dev/null+++ b/tests/unit/health/test_organizational_biomarkers.py@@ -0,0 +1,113 @@+"""Developer Congestion + Knowledge Loss biomarker tests."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers import FileContext+from repowise.core.analysis.health.biomarkers.developer_congestion import (+ DeveloperCongestionDetector,+)+from repowise.core.analysis.health.biomarkers.knowledge_loss import (+ KnowledgeLossDetector,+)+++def _ctx(meta: dict) -> FileContext:+ return FileContext(+ file_path="src/payments.py",+ language="python",+ nloc=120,+ has_test_file=False,+ module=None,+ function_metrics={},+ git_meta=meta,+ dependents_count=4,+ pagerank_score=0.0,+ )+++# ---- developer_congestion ------------------------------------------------+++def test_developer_congestion_fires_on_crowded_hotspot():+ meta = {+ "contributor_count": 12,+ "commit_count_90d": 25,+ "primary_owner_commit_pct": 0.25,+ "primary_owner_name": "Alice",+ }+ out = DeveloperCongestionDetector().detect(_ctx(meta))+ assert len(out) == 1+ assert out[0].severity == "high"+ assert out[0].details["contributor_count"] == 12+++def test_developer_congestion_normalizes_percent_form():+ meta = {+ "contributor_count": 6,+ "commit_count_90d": 8,+ "primary_owner_commit_pct": 30.0, # percent form+ }+ out = DeveloperCongestionDetector().detect(_ctx(meta))+ assert out+ assert out[0].details["primary_owner_share"] == 0.3+++def test_developer_congestion_skips_with_clear_owner():+ meta = {+ "contributor_count": 8,+ "commit_count_90d": 15,+ "primary_owner_commit_pct": 0.65,+ }+ assert DeveloperCongestionDetector().detect(_ctx(meta)) == []+++def test_developer_congestion_skips_low_activity():+ meta = {+ "contributor_count": 8,+ "commit_count_90d": 2,+ "primary_owner_commit_pct": 0.2,+ }+ assert DeveloperCongestionDetector().detect(_ctx(meta)) == []+++# ---- knowledge_loss ------------------------------------------------------+++def test_knowledge_loss_fires_when_primary_owner_left():+ meta = {+ "bus_factor": 1,+ "primary_owner_name": "Alice",+ "recent_owner_name": "Bob",+ "recent_owner_commit_pct": 0.8,+ "is_hotspot": True,+ }+ out = KnowledgeLossDetector().detect(_ctx(meta))+ assert len(out) == 1+ assert out[0].severity == "high" # hotspot escalation+ assert out[0].details["primary_owner"] == "Alice"+++def test_knowledge_loss_fires_when_recent_share_collapses():+ meta = {+ "bus_factor": 1,+ "primary_owner_name": "Alice",+ "recent_owner_name": "Alice",+ "recent_owner_commit_pct": 0.05,+ "is_hotspot": False,+ }+ out = KnowledgeLossDetector().detect(_ctx(meta))+ assert len(out) == 1+++def test_knowledge_loss_skips_when_bus_factor_healthy():+ meta = {+ "bus_factor": 4,+ "primary_owner_name": "Alice",+ "recent_owner_name": "Bob",+ "recent_owner_commit_pct": 0.1,+ }+ assert KnowledgeLossDetector().detect(_ctx(meta)) == []+++def test_knowledge_loss_skips_without_owner_data():+ assert KnowledgeLossDetector().detect(_ctx({})) == []diff --git a/tests/unit/health/test_scoring.py b/tests/unit/health/test_scoring.pynew file mode 100644index 000000000..81d1b25dd--- /dev/null+++ b/tests/unit/health/test_scoring.py@@ -0,0 +1,71 @@+"""Unit tests for ``scoring.score_file`` and KPI helpers."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers.base import BiomarkerResult+from repowise.core.analysis.health.models import HealthFileMetricData, Severity+from repowise.core.analysis.health.scoring import (+ CATEGORY_CAPS,+ compute_kpis,+ score_file,+)+++def _r(name: str, severity: Severity) -> BiomarkerResult:+ return BiomarkerResult(+ biomarker_type=name,+ severity=severity,+ function_name=None,+ line_start=1,+ line_end=10,+ details={},+ reason="",+ )+++def test_score_clean_file_is_ten():+ score, deductions = score_file([])+ assert score == 10.0+ assert deductions == []+++def test_score_clamps_floor_at_one():+ # Twenty critical findings in the same category — should hit the cap+ # but never go below 1.0.+ 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+++def test_category_cap_applied():+ # Two structural-complexity hits that together would deduct 4.0 raw,+ # but the category cap is 3.5.+ results = [+ _r("brain_method", Severity.CRITICAL), # 2.0 raw+ _r("nested_complexity", Severity.CRITICAL), # 2.0 raw+ ]+ score, _ = score_file(results)+ assert score == 10.0 - CATEGORY_CAPS["structural_complexity"]+++def test_compute_kpis_uses_nloc_weighting():+ metrics = [+ HealthFileMetricData(+ "a.py", score=5.0, max_ccn=1, max_nesting=1, nloc=100, has_test_file=False+ ),+ HealthFileMetricData(+ "b.py", score=10.0, max_ccn=1, max_nesting=1, nloc=10, has_test_file=False+ ),+ ]+ kpis = compute_kpis(metrics, hotspot_paths=set())+ # Weighted avg = (5*100 + 10*10) / 110 ≈ 5.45+ assert abs(kpis["average_health"] - 5.45) < 0.02+ assert kpis["worst_performer_path"] == "a.py"+++def test_compute_kpis_empty_returns_defaults():+ kpis = compute_kpis([], hotspot_paths=set())+ assert kpis["average_health"] == 10.0+ assert kpis["file_count"] == 0diff --git a/tests/unit/health/test_scoring_snapshot.py b/tests/unit/health/test_scoring_snapshot.pynew file mode 100644index 000000000..bfe5895bd--- /dev/null+++ b/tests/unit/health/test_scoring_snapshot.py@@ -0,0 +1,100 @@+"""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.++If a deliberate retune lands, regenerate the snapshot by updating the+``_EXPECTED_*`` constants below in the same PR — never silently.+"""++from __future__ import annotations++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,+ _SEVERITY_DEDUCTION,+ CATEGORY_CAPS,+ score_file,+)++_EXPECTED_CATEGORY_CAPS = {+ "structural_complexity": 3.5,+ "size_and_complexity": 2.0,+ "duplication": 1.5,+ "test_coverage": 2.0,+ "organizational": 1.0,+}++_EXPECTED_SEVERITY_DEDUCTION = {+ Severity.LOW: 0.3,+ Severity.MEDIUM: 0.7,+ Severity.HIGH: 1.2,+ Severity.CRITICAL: 2.0,+}++_EXPECTED_BIOMARKER_CATEGORY = {+ "brain_method": "structural_complexity",+ "nested_complexity": "structural_complexity",+ "bumpy_road": "structural_complexity",+ "complex_method": "size_and_complexity",+ "large_method": "size_and_complexity",+ "primitive_obsession": "size_and_complexity",+ "dry_violation": "duplication",+ "untested_hotspot": "test_coverage",+ "coverage_gap": "test_coverage",+ "developer_congestion": "organizational",+ "knowledge_loss": "organizational",+}+++def test_category_caps_locked():+ assert CATEGORY_CAPS == _EXPECTED_CATEGORY_CAPS+++def test_severity_deductions_locked():+ assert _SEVERITY_DEDUCTION == _EXPECTED_SEVERITY_DEDUCTION+++def test_biomarker_to_category_locked():+ assert _BIOMARKER_CATEGORY == _EXPECTED_BIOMARKER_CATEGORY+++def _result(biomarker: str, severity: Severity) -> BiomarkerResult:+ return BiomarkerResult(+ biomarker_type=biomarker,+ severity=severity,+ function_name=None,+ line_start=None,+ line_end=None,+ details={},+ reason="",+ )+++def test_known_fixture_score_is_stable():+ """A handcrafted finding set should produce a known, fixed score."""+ findings = [+ _result("brain_method", Severity.CRITICAL),+ _result("nested_complexity", Severity.HIGH),+ _result("complex_method", Severity.MEDIUM),+ _result("untested_hotspot", Severity.HIGH),+ _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+++def test_category_cap_clamps_score():+ """Many critical structural findings should not exceed the -3.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.+ assert score == 6.5diff --git a/tests/unit/health/test_structural_biomarkers.py b/tests/unit/health/test_structural_biomarkers.pynew file mode 100644index 000000000..21e4ac95c--- /dev/null+++ b/tests/unit/health/test_structural_biomarkers.py@@ -0,0 +1,94 @@+"""Tests for Phase-3 structural / size biomarkers."""++from __future__ import annotations++from repowise.core.analysis.health.biomarkers import FileContext+from repowise.core.analysis.health.biomarkers.bumpy_road import BumpyRoadDetector+from repowise.core.analysis.health.biomarkers.large_method import LargeMethodDetector+from repowise.core.analysis.health.biomarkers.primitive_obsession import (+ PrimitiveObsessionDetector,+)+from repowise.core.analysis.health.complexity import FunctionComplexity+++def _ctx(fns: list[FunctionComplexity]) -> FileContext:+ return FileContext(+ file_path="src/example.py",+ language="python",+ nloc=sum(f.nloc for f in fns),+ has_test_file=False,+ module=None,+ function_metrics={f.name: f for f in fns},+ git_meta={},+ dependents_count=0,+ pagerank_score=0.0,+ )+++# ---- bumpy_road ----------------------------------------------------------+++def test_bumpy_road_flags_multi_hump_function():+ fn = FunctionComplexity("rough", 1, 80, ccn=8, max_nesting=3, cognitive=15, nloc=50, bumps=4)+ results = BumpyRoadDetector().detect(_ctx([fn]))+ assert len(results) == 1+ assert results[0].details["bumps"] == 4+++def test_bumpy_road_skips_flat_function():+ fn = FunctionComplexity("flat", 1, 10, ccn=3, max_nesting=1, cognitive=2, nloc=8, bumps=0)+ assert BumpyRoadDetector().detect(_ctx([fn])) == []+++def test_bumpy_road_requires_ccn_floor():+ # Lots of bumps but very low CCN — could happen on synthetic inputs.+ fn = FunctionComplexity("toy", 1, 20, ccn=2, max_nesting=2, cognitive=2, nloc=18, bumps=4)+ assert BumpyRoadDetector().detect(_ctx([fn])) == []+++# ---- large_method --------------------------------------------------------+++def test_large_method_severity_grades():+ small = FunctionComplexity("small", 1, 50, ccn=3, max_nesting=1, cognitive=4, nloc=40)+ big = FunctionComplexity("big", 1, 150, ccn=5, max_nesting=2, cognitive=10, nloc=130)+ huge = FunctionComplexity("huge", 1, 300, ccn=10, max_nesting=3, cognitive=20, nloc=250)+ d = LargeMethodDetector()+ assert d.detect(_ctx([small])) == []+ big_res = d.detect(_ctx([big]))+ assert len(big_res) == 1+ assert big_res[0].severity == "high"+ huge_res = d.detect(_ctx([huge]))+ assert huge_res[0].severity == "critical"+++# ---- primitive_obsession -------------------------------------------------+++def test_primitive_obsession_flags_wide_signature():+ fn = FunctionComplexity(+ "do_things", 1, 5, ccn=1, max_nesting=0, cognitive=0, nloc=3, param_count=7+ )+ out = PrimitiveObsessionDetector().detect(_ctx([fn]))+ assert len(out) == 1+ assert out[0].details["param_count"] == 7+++def test_primitive_obsession_grace_for_constructors():+ # 6 params on a regular fn fires; on __init__ it doesn't (grace = 2).+ regular = FunctionComplexity(+ "build", 1, 5, ccn=1, max_nesting=0, cognitive=0, nloc=3, param_count=6+ )+ ctor = FunctionComplexity(+ "__init__", 1, 5, ccn=1, max_nesting=0, cognitive=0, nloc=3, param_count=6+ )+ d = PrimitiveObsessionDetector()+ assert d.detect(_ctx([regular]))+ assert d.detect(_ctx([ctor])) == []+++def test_primitive_obsession_ignores_small_signatures():+ fn = FunctionComplexity(+ "narrow", 1, 5, ccn=1, max_nesting=0, cognitive=0, nloc=3, param_count=3+ )+ assert PrimitiveObsessionDetector().detect(_ctx([fn])) == []diff --git a/tests/unit/health/test_suggestions.py b/tests/unit/health/test_suggestions.pynew file mode 100644index 000000000..1f5fedac4--- /dev/null+++ b/tests/unit/health/test_suggestions.py@@ -0,0 +1,26 @@+"""Tests for ``health/suggestions.py`` — deterministic refactoring text."""++from __future__ import annotations++from repowise.core.analysis.health.suggestions import (+ annotate_finding,+ suggestion_for,+)+++def test_suggestion_known_biomarker_is_actionable():+ text = suggestion_for("brain_method")+ assert "split" in text.lower() or "extract" in text.lower()+++def test_suggestion_unknown_biomarker_falls_back():+ text = suggestion_for("not_a_real_biomarker")+ assert text # never empty+ assert "health-rules.json" in text # fallback hints at suppression+++def test_annotate_finding_adds_suggestion_field():+ out = annotate_finding({"biomarker_type": "nested_complexity", "severity": "high"})+ assert out["biomarker_type"] == "nested_complexity"+ assert "suggestion" in out+ assert out["suggestion"] == suggestion_for("nested_complexity")diff --git a/tests/unit/health/test_trends.py b/tests/unit/health/test_trends.pynew file mode 100644index 000000000..3af4ddd7b--- /dev/null+++ b/tests/unit/health/test_trends.py@@ -0,0 +1,82 @@+"""Tests for ``health/trends.py`` — snapshot diff + alert detection."""++from __future__ import annotations++from dataclasses import dataclass+from datetime import UTC, datetime, timedelta++from repowise.core.analysis.health.trends import (+ DECLINE_LOOKBACK,+ DECLINE_THRESHOLD,+ diff_snapshots,+ recent_kpis,+)+++@dataclass+class _S:+ taken_at: datetime+ hotspot_health: float+ average_health: float+ worst_performer_path: str | None = "x"+ worst_performer_score: float | None = 1.0+++def _ts(n: int) -> datetime:+ return datetime(2026, 1, 1, tzinfo=UTC) + timedelta(hours=n)+++def _series(values: list[float]) -> list[_S]:+ return [_S(taken_at=_ts(i), hotspot_health=v, average_health=v) for i, v in enumerate(values)]+++def test_diff_empty_history_neutral():+ summary = diff_snapshots([])+ assert summary.current_hotspot_health == 10.0+ assert summary.hotspot_delta is None+ assert summary.alerts == []+++def test_diff_single_snapshot_no_alerts():+ summary = diff_snapshots(_series([7.5]))+ assert summary.current_hotspot_health == 7.5+ assert summary.previous_hotspot_health is None+ assert summary.alerts == []+++def test_declining_health_alert_triggers_at_threshold():+ # 7 snapshots: oldest 8.0, newest 8.0 - threshold - 0.1+ vals = [8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0 - DECLINE_THRESHOLD - 0.1]+ assert len(vals) > DECLINE_LOOKBACK+ summary = diff_snapshots(_series(vals))+ declining = [a for a in summary.alerts if a.kind == "declining"]+ assert declining, "expected a Declining Health alert"+ # Both metrics share the same series → both should fire.+ metrics = {a.metric for a in declining}+ assert "hotspot_health" in metrics+ assert "average_health" in metrics+++def test_no_declining_alert_below_threshold():+ vals = [8.0, 8.0, 8.0, 8.0, 8.0, 8.0, 8.0 - 0.1] # drop too small+ summary = diff_snapshots(_series(vals))+ assert not [a for a in summary.alerts if a.kind == "declining"]+++def test_predicted_decline_alert_on_three_consecutive_drops():+ # Four points required: each strictly below the previous.+ summary = diff_snapshots(_series([7.5, 7.4, 7.3, 7.2]))+ pred = [a for a in summary.alerts if a.kind == "predicted_decline"]+ assert pred, "expected a Predicted Decline alert"+ assert all(a.delta < 0 for a in pred)+++def test_no_predicted_decline_on_flat_or_recovering():+ summary = diff_snapshots(_series([7.5, 7.4, 7.4, 7.3])) # plateau+ assert not [a for a in summary.alerts if a.kind == "predicted_decline"]+++def test_recent_kpis_orders_newest_first():+ rows = recent_kpis(_series([5.0, 6.0, 7.0]), limit=10)+ scores = [r["hotspot_health"] for r in rows]+ assert scores == [7.0, 6.0, 5.0]diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex a486efe50..5c1f19e5f 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -308,5 +308,9 @@ def test_base_includes_all_models():"security_findings","answer_cache","external_systems",+ "health_findings",+ "health_file_metrics",+ "health_snapshots",+ "coverage_files",}assert expected == table_namesdiff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.pyindex 9acf494f2..0e289d46e 100644--- a/tests/unit/server/test_mcp.py+++ b/tests/unit/server/test_mcp.py@@ -1194,6 +1194,98 @@ async def test_get_dead_code_group_by_owner(setup_mcp):assert "Bob" in owner_names # Bob owns dc2 + dc3+# ---- Tool: get_health ----+++async def health_data(session: AsyncSession, populated_db: str) -> str:+ """Seed health_findings + health_file_metrics for the existing repo."""+ from repowise.core.persistence.crud import (+ save_health_findings,+ save_health_metrics,+ )++ rid = populated_db+ await save_health_metrics(+ session,+ rid,+ [+ {+ "file_path": "src/auth/service.py",+ "score": 4.5,+ "max_ccn": 15,+ "max_nesting": 5,+ "nloc": 200,+ "has_test_file": False,+ "module": "auth",+ },+ {+ "file_path": "src/db/models.py",+ "score": 8.5,+ "max_ccn": 4,+ "max_nesting": 2,+ "nloc": 50,+ "has_test_file": True,+ "module": "db",+ },+ ],+ )+ await save_health_findings(+ session,+ rid,+ [+ {+ "file_path": "src/auth/service.py",+ "biomarker_type": "complex_method",+ "severity": "high",+ "function_name": "authenticate",+ "line_start": 10,+ "line_end": 80,+ "details": {"ccn": 15, "cognitive": 30, "nloc": 70},+ "health_impact": 1.2,+ "reason": "authenticate has cyclomatic complexity 15",+ },+ {+ "file_path": "src/auth/service.py",+ "biomarker_type": "nested_complexity",+ "severity": "medium",+ "function_name": "authenticate",+ "line_start": 10,+ "line_end": 80,+ "details": {"max_nesting": 5, "ccn": 15, "cognitive": 30},+ "health_impact": 0.7,+ "reason": "authenticate nests 5 levels deep",+ },+ ],+ )+ await session.commit()+ return rid+++async def test_get_health_dashboard(setup_mcp, health_data):+ from repowise.server.mcp_server import get_health++ result = await get_health()+ assert result["mode"] == "dashboard"+ assert result["kpis"]["file_count"] == 2+ assert result["kpis"]["worst_performer_path"] == "src/auth/service.py"+ assert len(result["worst_files"]) == 2+ assert result["worst_files"][0]["file_path"] == "src/auth/service.py"+ assert len(result["top_findings"]) == 2+++async def test_get_health_targeted(setup_mcp, health_data):+ from repowise.server.mcp_server import get_health++ result = await get_health(targets=["src/auth/service.py"])+ assert result["mode"] == "targets"+ assert len(result["metrics"]) == 1+ assert result["metrics"][0]["max_ccn"] == 15+ assert all(f["file_path"] == "src/auth/service.py" for f in result["findings"])++# ---- MCP config generation ----