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(symbols): show and filter by per-symbol bug-fix counts (#949)
Raghav Chamadiyaa21bd7b83088
diff --git a/packages/api-client/src/symbols.ts b/packages/api-client/src/symbols.tsindex b6bcc2b0a..8911af98a 100644--- a/packages/api-client/src/symbols.ts+++ b/packages/api-client/src/symbols.ts@@ -13,6 +13,8 @@ export interface SymbolListParams {file_path?: string;in_hot_files?: boolean;in_entry_points?: boolean;+ /** Only symbols a counted bug fix landed in. */+ bug_fixed?: boolean;sort?: SymbolSortKey;limit?: number;offset?: number;diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.tsindex f13c1e06e..65fd05b51 100644--- a/packages/api-client/src/types/git.ts+++ b/packages/api-client/src/types/git.ts@@ -31,6 +31,12 @@ export interface GitMetadataResponse {change_entropy?: number;change_entropy_pct?: number;prior_defect_count?: number;+ /** `symbol_id` -> counted fixes that landed in it, same window as+ * `prior_defect_count`. Approximate: symbol spans are current-tree while+ * each fix's ranges are numbered on its own parent commit. */+ fix_symbol_counts?: Record<string, number>;+ bug_magnet?: boolean;+ last_fix_at?: string | null;temporal_hotspot_score?: number | null;commit_count_capped?: boolean;original_path?: string | null;diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.pyindex e8485a62a..e8a8ad1c6 100644--- a/packages/server/src/repowise/server/routers/symbols.py+++ b/packages/server/src/repowise/server/routers/symbols.py@@ -2,12 +2,14 @@from __future__ import annotations+import jsonfrom typing import Literalfrom fastapi import APIRouter, Depends, HTTPException, Query-from sqlalchemy import func, select+from sqlalchemy import func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.signals import iso_utcfrom repowise.core.persistence import crudfrom repowise.core.persistence.decision_graph import get_governing_decisionsfrom repowise.core.persistence.models import (@@ -32,6 +34,11 @@ router = APIRouter(SortKey = Literal["importance", "name", "complexity", "kind"]+#: Bound parameters per IN-clause. SQLite's ceiling is 32766 on current builds+#: and it raises rather than degrading, so any list that grows with repo size+#: gets split at a comfortable fraction of it.+_IN_CLAUSE_CHUNK = 5000+def _attach_signals(response: SymbolResponse,@@ -84,6 +91,69 @@ async def _attach_blame(return items+async def _fixed_symbol_ids(session: AsyncSession, repo_id: str) -> set[str]:+ """Every symbol id with at least one counted bug fix, across the repo.++ The rollup stores one ``symbol_id -> count`` map per file, so this is a scan+ of the files that have fix history, not the ``fix_events`` table. Returned+ as a set because both callers (the list filter and its counts) want+ membership, and it is bounded by the defect window rather than by repo size.+ """+ rows = await session.execute(+ select(GitMetadata.fix_symbol_counts_json).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.fix_symbol_counts_json.isnot(None),+ GitMetadata.fix_symbol_counts_json != "{}",+ )+ )+ fixed: set[str] = set()+ for (raw,) in rows.all():+ try:+ counts = json.loads(raw or "{}")+ except (TypeError, ValueError):+ continue+ if isinstance(counts, dict):+ fixed.update(k for k, v in counts.items() if v)+ return fixed+++async def _attach_fix_counts(+ session: AsyncSession, repo_id: str, items: list[SymbolResponse]+) -> list[SymbolResponse]:+ """Join the page's symbols against the per-file fix rollup in one query.++ Mirrors :func:`_attach_blame`, and deliberately scoped to the page's files+ so the response carries one integer per symbol rather than whole-file maps.++ ``None`` means the file has no ``git_metadata`` row at all, which is genuinely+ unknown. It does NOT distinguish "the rollup has not run" from "the rollup+ ran and found nothing", because the column stores ``"{}"`` for both; a file+ with a row therefore reports a real ``0``.+ """+ paths = {s.file_path for s in items if s.file_path}+ if not paths:+ return items+ rows = await session.execute(+ select(GitMetadata.file_path, GitMetadata.fix_symbol_counts_json).where(+ GitMetadata.repository_id == repo_id,+ GitMetadata.file_path.in_(paths),+ )+ )+ by_path: dict[str, dict] = {}+ for path, raw in rows.all():+ try:+ counts = json.loads(raw or "{}")+ except (TypeError, ValueError):+ continue+ if isinstance(counts, dict):+ by_path[path] = counts+ for s in items:+ counts = by_path.get(s.file_path)+ if counts is not None:+ s.fix_count = int(counts.get(s.symbol_id, 0))+ return items++async def _file_signals(session: AsyncSession, repo_id: str, paths: set[str]) -> tuple[dict[str, tuple[float, bool]], dict[str, tuple[float | None, bool | None]]]:@@ -133,6 +203,7 @@ async def search_symbols(),in_hot_files: bool = Query(False, description="Only symbols whose file is a hotspot"),in_entry_points: bool = Query(False, description="Only symbols in entry-point files"),+ bug_fixed: bool = Query(False, description="Only symbols with a counted bug fix"),sort: SortKey = Query("importance", description="Sort key"),limit: int = Query(50, ge=1, le=500),offset: int = Query(0, ge=0),@@ -187,6 +258,25 @@ async def search_symbols(ep_set = {r.node_id for r in ep_paths}base = base.where(WikiSymbol.file_path.in_(ep_set or {""}))+ # Symbol-level, unlike the two file-level filters above: a bug-fixed file+ # says little about the one function you are looking at.+ if bug_fixed:+ fixed = await _fixed_symbol_ids(session, repo_id)+ if not fixed:+ base = base.where(WikiSymbol.symbol_id.is_(None))+ else:+ # Chunked: `fixed` is every symbol repo-wide with a counted fix, and+ # on a large actively-fixed repo that is thousands of ids. SQLite+ # caps bound parameters (32766 on current builds) and hard-fails+ # past it, so the IN-list is split rather than left to grow with the+ # repo.+ ids = sorted(fixed)+ clauses = [+ WikiSymbol.symbol_id.in_(ids[i : i + _IN_CLAUSE_CHUNK])+ for i in range(0, len(ids), _IN_CLAUSE_CHUNK)+ ]+ base = base.where(or_(*clauses))+total = await session.scalar(select(func.count()).select_from(base.subquery())) or 0if sort == "importance":@@ -247,6 +337,7 @@ async def search_symbols()items = await _attach_blame(session, repo_id, items)+ items = await _attach_fix_counts(session, repo_id, items)next_offset = offset + limit if offset + limit < total else Nonereturn Paginated[SymbolResponse](items=items,@@ -365,9 +456,35 @@ async def symbol_detail(},"governing_decisions": governing,"file_context": file_context,+ # Symbol-level fix history, read off the file rollup already loaded+ # above, so no extra query and no `fix_events` scan to recompute a+ # number the rollup stores. None on a pre-rollup index.+ "fix_count": _symbol_fix_count(git_meta, symbol_id),+ # Reuses the health signals serializer so the offset is attached the+ # same way here as on every other surface: SQLite hands these back+ # naive, and a naive ISO string is parsed as LOCAL time by JS.+ "fix_last_at": iso_utc(getattr(git_meta, "last_fix_at", None)),}+def _symbol_fix_count(git_meta: object | None, symbol_id: str) -> int | None:+ """How many counted bug fixes landed in *symbol_id*, or ``None`` if unknown.++ The rollup stores the whole file's ``symbol_id -> count`` map, so this is a+ dict lookup. ``None`` means there is no ``git_metadata`` row for the file;+ a row with an empty map reports a real ``0``, since the column cannot tell+ "the rollup has not run" from "it ran and found nothing".+ """+ if git_meta is None:+ return None+ raw = getattr(git_meta, "fix_symbol_counts_json", None) or "{}"+ try:+ counts = json.loads(raw)+ except (TypeError, ValueError):+ return None+ return int(counts.get(symbol_id, 0)) if isinstance(counts, dict) else None++@router.get("/by-name/{name}", response_model=list[SymbolResponse])async def lookup_by_name(name: str,diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 05e74dbf2..7d55690a0 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -39,6 +39,14 @@ class GitMetadataResponse(BaseModel):change_entropy: float = 0.0change_entropy_pct: float = 0.0prior_defect_count: int = 0+ # Fix-event rollup. ``fix_symbol_counts`` maps WikiSymbol.symbol_id to how+ # many counted fixes landed in that symbol, so a caller holding this row can+ # answer "was THIS function bug-fixed?" without a second request.+ # ``last_fix_at`` travels with it because a fix count without recency reads+ # the same at two weeks and two years. Empty/None on a pre-rollup index.+ fix_symbol_counts: dict = {}+ bug_magnet: bool = False+ last_fix_at: datetime | None = Nonetemporal_hotspot_score: float | None = Nonecommit_count_capped: bool = False# Rename lineage: the file's path before its most recent move, if any.@@ -87,6 +95,9 @@ class GitMetadataResponse(BaseModel):# Normalize 0-1 -> 0-100 to match churn_percentile's contract.change_entropy_pct=(obj.change_entropy_pct or 0.0) * 100.0, # type: ignore[attr-defined]prior_defect_count=obj.prior_defect_count or 0, # type: ignore[attr-defined]+ fix_symbol_counts=json.loads(getattr(obj, "fix_symbol_counts_json", None) or "{}"),+ bug_magnet=bool(getattr(obj, "bug_magnet", False)),+ last_fix_at=getattr(obj, "last_fix_at", None),temporal_hotspot_score=obj.temporal_hotspot_score, # type: ignore[attr-defined]commit_count_capped=bool(obj.commit_count_capped), # type: ignore[attr-defined]original_path=obj.original_path, # type: ignore[attr-defined]diff --git a/packages/server/src/repowise/server/schemas/symbols.py b/packages/server/src/repowise/server/schemas/symbols.pyindex 89e19f478..a12e9bd28 100644--- a/packages/server/src/repowise/server/schemas/symbols.py+++ b/packages/server/src/repowise/server/schemas/symbols.py@@ -49,6 +49,9 @@ class SymbolResponse(BaseModel):blame_median_author_time: int | None = Noneblame_owner_name: str | None = Noneblame_owner_line_pct: float | None = None+ # Counted bug fixes attributed to this symbol (from the per-file rollup;+ # null when the index predates it, 0 when it ran and found none here).+ fix_count: int | None = None@classmethoddef from_orm(cls, obj: object) -> SymbolResponse:diff --git a/packages/types/src/git.ts b/packages/types/src/git.tsindex d3ab31ae4..53ce0dfc2 100644--- a/packages/types/src/git.ts+++ b/packages/types/src/git.ts@@ -61,6 +61,14 @@ export interface GitMetadata {change_entropy_pct?: number;/** Bug-fix commits touching this file in the trailing defect window. */prior_defect_count?: number;+ /** `symbol_id` -> counted fixes that landed in it, over the same window.+ * Approximate: symbol spans are current-tree while each fix's ranges are+ * numbered on its own parent commit. Empty on a pre-rollup index. */+ fix_symbol_counts?: Record<string, number>;+ /** Decayed fix mass past its trigger. A recency claim, so any copy showing+ * it must show `last_fix_at` too. */+ bug_magnet?: boolean;+ last_fix_at?: string | null;/** The file's path before its most recent rename, if any. */original_path?: string | null;/** True when the per-file commit-history cap was hit during indexing. */diff --git a/packages/types/src/symbols.ts b/packages/types/src/symbols.tsindex 03dde68a5..b0e2e9f03 100644--- a/packages/types/src/symbols.ts+++ b/packages/types/src/symbols.ts@@ -67,6 +67,10 @@ export interface CodeSymbol {blame_median_author_time?: number | null;blame_owner_name?: string | null;blame_owner_line_pct?: number | null;+ /** Counted bug fixes attributed to this symbol, populated by the list+ * endpoint from the per-file rollup. Null when the index predates it,+ * 0 when it ran and found no fixes here. */+ fix_count?: number | null;}// ---------------------------------------------------------------------------@@ -104,6 +108,10 @@ export interface SymbolDetailResponse {graph: SymbolDetailGraph;governing_decisions: { id: string; title: string; status: string }[];file_context: SymbolFileContext;+ /** Counted bug fixes attributed to this symbol, and the file's last counted+ * fix. Both null on an index that predates the fix-event rollup. */+ fix_count?: number | null;+ fix_last_at?: string | null;}export interface SymbolList {@@ -189,6 +197,14 @@ export interface SymbolDetailData {blame_median_author_time?: number | null;blame_owner_name?: string | null;blame_owner_line_pct?: number | null;+ /** Counted bug fixes whose replaced lines landed in this symbol, over the+ * same 6-month window as `prior_defect_count`. Approximate by construction:+ * symbol spans are current-tree while each fix's ranges are numbered on its+ * own parent commit, so any surface showing it must hedge. `fix_last_at` is+ * the file's most recent counted fix, because a count without recency reads the+ * same at two weeks and two years. */+ fix_count?: number | null;+ fix_last_at?: string | null;graph?: SymbolBodyGraph | null;/** Heritage relations (extends/implements + extended-by). Renders when present. */heritage?: SymbolHeritage | null;diff --git a/packages/ui/__tests__/symbols/symbol-table.test.tsx b/packages/ui/__tests__/symbols/symbol-table.test.tsxindex 9ef4abb14..02726f504 100644--- a/packages/ui/__tests__/symbols/symbol-table.test.tsx+++ b/packages/ui/__tests__/symbols/symbol-table.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi } from "vitest";-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { SymbolTable, type SymbolFilters } from "../../src/symbols/symbol-table.js";import type { CodeSymbol } from "@repowise-dev/types/symbols";@@ -29,6 +29,7 @@ const defaultFilters: SymbolFilters = {kind: "all",language: "all",visibility: "all",+ bugFixed: false,inHotFiles: false,inEntryPoints: false,sort: "importance",@@ -109,3 +110,47 @@ describe("SymbolTable", () => {expect(scroller?.contains(loadMore)).toBe(false);});});++describe("SymbolTable bug-fix signal", () => {+ function renderTable(items: ReturnType<typeof sym>[], onFiltersChange = vi.fn()) {+ render(+ <SymbolTable+ items={items}+ isLoading={false}+ isValidating={false}+ hasMore={false}+ total={items.length}+ filters={defaultFilters}+ onFiltersChange={onFiltersChange}+ onLoadMore={vi.fn()}+ onSelect={vi.fn()}+ />,+ );+ return onFiltersChange;+ }++ it("chips a symbol that bug fixes have landed in", () => {+ renderTable([sym({ fix_count: 3 })]);+ expect(screen.getByText("3 fixes")).toBeTruthy();+ });++ it("says nothing for a symbol nobody has had to fix", () => {+ // 0 is a real answer, not a chip: the chip exists to draw the eye, and a+ // row of "0 fixes" on every clean symbol would draw it nowhere.+ renderTable([sym({ fix_count: 0 })]);+ expect(screen.queryByText(/fixes?$/)).toBeNull();+ });++ it("says nothing when the count is unknown", () => {+ renderTable([sym({ fix_count: null })]);+ expect(screen.queryByText(/fixes?$/)).toBeNull();+ });++ it("toggles the symbol-level bug-fixed facet", () => {+ const onFiltersChange = renderTable([sym()]);+ fireEvent.click(screen.getByRole("button", { name: /Bug-fixed/ }));+ expect(onFiltersChange).toHaveBeenCalledWith(+ expect.objectContaining({ bugFixed: true }),+ );+ });+});diff --git a/packages/ui/src/symbols/symbol-detail-body.tsx b/packages/ui/src/symbols/symbol-detail-body.tsxindex a41674e3e..b57257b1b 100644--- a/packages/ui/src/symbols/symbol-detail-body.tsx+++ b/packages/ui/src/symbols/symbol-detail-body.tsx@@ -15,7 +15,7 @@ import { Badge } from "../ui/badge";import { Button } from "../ui/button";import { StatGrid, StatTile } from "../shared/stat-grid";import { scoreBadgeClass } from "../health/tokens";-import { truncatePath } from "../lib/format";+import { formatRelativeTimeOrNull, truncatePath } from "../lib/format";import { cn } from "../lib/cn";import { SymbolCallGraph } from "./symbol-call-graph";@@ -32,6 +32,18 @@ export interface SymbolDetailBodyProps {className?: string;}+/**+ * The hint under the Bug fixes tile: recency plus the approximation caveat.+ *+ * Recency is not decoration. The count is windowed, but "3 fixes" alone reads+ * the same whether the last one landed a fortnight or five months ago, so the+ * age goes in wherever the file's last-fix timestamp is known.+ */+function fixHint(lastFixAt: string | null | undefined): string {+ const last = formatRelativeTimeOrNull(lastFixAt ?? null, "");+ return last ? `last ${last} · approximate` : "in 6 months · approximate";+}+function ageDays(t: number | null | undefined): number | null {if (!t) return null;return Math.max(0, Math.round((Date.now() / 1000 - t) / 86400));@@ -114,6 +126,18 @@ export function SymbolDetailBody({: {})}/><StatTile label="Median age" value={age != null ? `${age}d` : "—"} />+ {data.fix_count != null && data.fix_count > 0 && (+ // "How often changed" (Modifications) beside "how often broken" is+ // the contrast that earns this tile. It appears only for a positive+ // count, since a symbol nobody has had to fix says nothing worth a cell,+ // and the hint hedges, because fixes are matched to symbols by line+ // range and lines move.+ <StatTile+ label="Bug fixes"+ value={String(data.fix_count)}+ hint={fixHint(data.fix_last_at)}+ />+ )}</StatGrid>{/* ── Graph metrics ── */}diff --git a/packages/ui/src/symbols/symbol-page.tsx b/packages/ui/src/symbols/symbol-page.tsxindex 1c192fb13..17569964e 100644--- a/packages/ui/src/symbols/symbol-page.tsx+++ b/packages/ui/src/symbols/symbol-page.tsx@@ -62,6 +62,8 @@ export function normalizeSymbolDetailResponse(blame_median_author_time: s.blame_median_author_time ?? null,blame_owner_name: s.blame_owner_name ?? null,blame_owner_line_pct: s.blame_owner_line_pct ?? null,+ fix_count: data.fix_count ?? null,+ fix_last_at: data.fix_last_at ?? null,graph: {in_degree: data.graph.in_degree,out_degree: data.graph.out_degree,diff --git a/packages/ui/src/symbols/symbol-table.tsx b/packages/ui/src/symbols/symbol-table.tsxindex 3d5e568a2..a8e48749c 100644--- a/packages/ui/src/symbols/symbol-table.tsx+++ b/packages/ui/src/symbols/symbol-table.tsx@@ -3,6 +3,7 @@import { type ReactNode } from "react";import {BookOpen,+ Bug,Flame,GitBranch,Globe2,@@ -41,6 +42,9 @@ export interface SymbolFilters {visibility: string;inHotFiles: boolean;inEntryPoints: boolean;+ /** Only symbols a counted bug fix landed in. Symbol-level, unlike the two+ * file-level facets above. */+ bugFixed: boolean;sort: SymbolSortKey;}@@ -120,6 +124,16 @@ function SignalChips({ sym }: { sym: CodeSymbol }) {hot</span>)}+ {(sym.fix_count ?? 0) > 0 && (+ <span+ className="inline-flex items-center gap-0.5 rounded bg-[var(--color-error)]/15 px-1 py-0.5 text-[10px] font-medium text-[var(--color-error)]"+ title={`${sym.fix_count} bug fix(es) landed here in the last 6 months (approximate: matched by line range)`}+ >+ <Bug className="h-2.5 w-2.5" />+ {sym.fix_count} fix+ {sym.fix_count === 1 ? "" : "es"}+ </span>+ )}{complex && (<spanclassName="inline-flex items-center gap-0.5 rounded bg-[var(--color-caution)]/15 px-1 py-0.5 text-[10px] font-medium text-[var(--color-caution)]"@@ -246,6 +260,12 @@ export function SymbolTable({label="Entry points"icon={<Rocket className="h-3 w-3" />}/>+ <FacetToggle+ active={filters.bugFixed}+ onClick={() => patch({ bugFixed: !filters.bugFixed })}+ label="Bug-fixed"+ icon={<Bug className="h-3 w-3" />}+ /><Select value={filters.sort} onValueChange={(v) => patch({ sort: v as SymbolSortKey })}><SelectTrigger className="w-40"><SelectValue placeholder="Sort" />diff --git a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsxindex b8e7ddf8e..b1d7e29a2 100644--- a/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-drawer-wrapper.tsx@@ -86,6 +86,16 @@ export function SymbolDrawerWrapper({ symbol, repoId, onClose }: Props) {docstring: symbol.docstring,importance_score: symbol.importance_score ?? null,complexity_estimate: symbol.complexity_estimate,+ // The file rollup carries the whole symbol_id -> fix-count map, so this+ // is a lookup on a response the drawer already fetched, no extra call.+ // Keyed on the row's own symbol_id rather than a rebuilt+ // `${file_path}::${name}`: some extractors mint ids from the QUALIFIED+ // name, and those symbols would silently never match.+ // A symbol with no fixes is simply absent from the map, and the body+ // renders the tile only for a positive count, so null covers both "no+ // rollup yet" and "never fixed here".+ fix_count: git?.fix_symbol_counts?.[symbol.symbol_id] ?? null,+ fix_last_at: git?.last_fix_at ?? null,graph: {in_degree: metrics?.in_degree ?? callData?.caller_count ?? 0,out_degree: metrics?.out_degree ?? callData?.callee_count ?? 0,diff --git a/packages/web/src/components/symbols/symbol-table-wrapper.tsx b/packages/web/src/components/symbols/symbol-table-wrapper.tsxindex dfc6ffc70..a9b354a43 100644--- a/packages/web/src/components/symbols/symbol-table-wrapper.tsx+++ b/packages/web/src/components/symbols/symbol-table-wrapper.tsx@@ -30,6 +30,7 @@ export function SymbolTableWrapper({ repoId }: Props) {visibility: "all",inHotFiles: false,inEntryPoints: false,+ bugFixed: false,sort: "importance",});const debouncedQ = useDebounce(filters.q, 300);@@ -61,6 +62,7 @@ export function SymbolTableWrapper({ repoId }: Props) {file_path: keyPayload.file || undefined,in_hot_files: keyPayload.inHotFiles || undefined,in_entry_points: keyPayload.inEntryPoints || undefined,+ bug_fixed: keyPayload.bugFixed || undefined,sort: keyPayload.sort,limit: LIMIT,offset: pageIndex * LIMIT,diff --git a/tests/unit/server/test_symbol_fix_counts.py b/tests/unit/server/test_symbol_fix_counts.pynew file mode 100644index 000000000..299593e76--- /dev/null+++ b/tests/unit/server/test_symbol_fix_counts.py@@ -0,0 +1,140 @@+"""Symbol-level bug-fix counts on /api/symbols and /api/symbols/detail.++The counts come from the per-file rollup (`git_metadata.fix_symbol_counts_json`),+not from a scan of `fix_events`. The rollup already stores exactly this number,+recomputed on every index and update.++`None` means the file has no git history row at all. It is deliberately NOT a+"the rollup has not run yet" signal: the column stores `"{}"` both before the+rollup and after a run that found nothing, so a tracked file always reports a+real `0`. Claiming otherwise would be a distinction the storage cannot back.++The `bug_fixed` filter is symbol-level, unlike the file-level `in_hot_files`+beside it: a bug-fixed file says little about the one function you are reading.+"""++from __future__ import annotations++import json++import pytest+from httpx import AsyncClient++from repowise.core.persistence.database import get_session+from repowise.core.persistence.models import GitMetadata, WikiSymbol, _new_uuid+from tests.unit.server.conftest import create_test_repo++_PATH = "src/pipeline.py"+++async def _seed(session_factory, repo_id: str, *, fix_counts: dict) -> None:+ """Two symbols in one file; only ``run`` has been bug-fixed."""+ async with get_session(session_factory) as session:+ for name, start in (("run", 1), ("load", 40)):+ session.add(+ WikiSymbol(+ id=_new_uuid(),+ repository_id=repo_id,+ file_path=_PATH,+ symbol_id=f"{_PATH}::{name}",+ name=name,+ qualified_name=f"pipeline.{name}",+ kind="function",+ start_line=start,+ end_line=start + 20,+ visibility="public",+ language="python",+ )+ )+ session.add(+ GitMetadata(+ id=_new_uuid(),+ repository_id=repo_id,+ file_path=_PATH,+ fix_symbol_counts_json=json.dumps(fix_counts),+ )+ )+++async def test_list_carries_per_symbol_fix_counts(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"], fix_counts={f"{_PATH}::run": 3})++ resp = await client.get("/api/symbols", params={"repo_id": repo["id"]})+ assert resp.status_code == 200+ by_name = {s["name"]: s for s in resp.json()["items"]}++ assert by_name["run"]["fix_count"] == 3+ # Rolled up, no fixes here: a real 0, not "unknown".+ assert by_name["load"]["fix_count"] == 0+++async def test_file_without_git_history_reports_unknown(client: AsyncClient, app) -> None:+ """No git_metadata row is the one genuine "we do not know"."""+ repo = await create_test_repo(client)+ async with get_session(app.state.session_factory) as session:+ session.add(+ WikiSymbol(+ id=_new_uuid(),+ repository_id=repo["id"],+ file_path="untracked.py",+ symbol_id="untracked.py::helper",+ name="helper",+ qualified_name="untracked.helper",+ kind="function",+ start_line=1,+ end_line=5,+ visibility="public",+ language="python",+ )+ )++ resp = await client.get("/api/symbols", params={"repo_id": repo["id"]})+ assert all(s["fix_count"] is None for s in resp.json()["items"])+++async def test_empty_rollup_reports_zero_not_unknown(client: AsyncClient, app) -> None:+ """A tracked file whose rollup found nothing reports 0, not None."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"], fix_counts={})++ resp = await client.get("/api/symbols", params={"repo_id": repo["id"]})+ assert all(s["fix_count"] == 0 for s in resp.json()["items"])+++async def test_bug_fixed_filter_is_symbol_level(client: AsyncClient, app) -> None:+ """Both symbols share a bug-fixed file; only the fixed one comes back."""+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"], fix_counts={f"{_PATH}::run": 3})++ resp = await client.get("/api/symbols", params={"repo_id": repo["id"], "bug_fixed": "true"})+ assert resp.status_code == 200+ payload = resp.json()+ assert payload["total"] == 1+ assert [s["name"] for s in payload["items"]] == ["run"]+++async def test_bug_fixed_filter_returns_nothing_without_a_rollup(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"], fix_counts={})++ resp = await client.get("/api/symbols", params={"repo_id": repo["id"], "bug_fixed": "true"})+ assert resp.json()["total"] == 0+++async def test_detail_carries_the_count_without_an_extra_query(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"], fix_counts={f"{_PATH}::run": 3})++ resp = await client.get(+ "/api/symbols/detail",+ params={"repo_id": repo["id"], "symbol_id": f"{_PATH}::run"},+ )+ assert resp.status_code == 200+ assert resp.json()["fix_count"] == 3