Skip to content

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

feat(commits): filter the repository, not the loaded page (#2455)

Raghav Chamadiya338034b4e003
diff --git a/packages/api-client/src/git.ts b/packages/api-client/src/git.ts
index d8430d052..a5d83934a 100644
--- a/packages/api-client/src/git.ts
+++ b/packages/api-client/src/git.ts
@@ -121,14 +121,24 @@ export async function getCommitsPage(
options: {
sort?: "risk" | "date";
authorship?: "all" | "agent" | "human";
+ /** Narrows the whole repository, not the page: the high review-priority
+ * band, or bug-fix commits. */
+ kind?: "all" | "high" | "fixes";
limit?: number;
offset?: number;
} = {},
): Promise<Paginated<CommitResponse>> {
- const { sort = "risk", authorship = "all", limit = 50, offset = 0 } = options;
+ const {
+ sort = "date",
+ authorship = "all",
+ kind = "all",
+ limit = 50,
+ offset = 0,
+ } = options;
return apiGet<Paginated<CommitResponse>>(`/api/repos/${repoId}/commits`, {
sort,
authorship,
+ kind,
limit,
offset,
});
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index dcb2a7f96..e9ccec4f8 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -491,16 +491,40 @@ def _commit_authorship_clause(authorship: str | None):
return None
+def _commit_kind_clause(kind: str | None, high_cut: float | None):
+ """Optional predicate for the review-priority band or bug-fix commits.
+
+ ``high`` compares against the repo's own moderate/high boundary on the
+ score axis, which is where the tercile actually falls; deriving it per row
+ would mean ranking every commit before paging any of them.
+ """
+ if kind == "fixes":
+ return GitCommit.is_fix.is_(True)
+ if kind == "high":
+ if high_cut is None:
+ return None
+ return GitCommit.change_risk_score >= high_cut
+ return None
+
+
async def count_git_commits(
- session: AsyncSession, repository_id: str, *, authorship: str | None = None
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ authorship: str | None = None,
+ kind: str | None = None,
+ high_cut: float | None = None,
) -> int:
- """Count persisted commits for a repository."""
+ """Count persisted commits for a repository, under the same filters."""
stmt = (
select(func.count()).select_from(GitCommit).where(GitCommit.repository_id == repository_id)
)
- clause = _commit_authorship_clause(authorship)
- if clause is not None:
- stmt = stmt.where(clause)
+ for clause in (
+ _commit_authorship_clause(authorship),
+ _commit_kind_clause(kind, high_cut),
+ ):
+ if clause is not None:
+ stmt = stmt.where(clause)
result = await session.execute(stmt)
return int(result.scalar_one() or 0)
@@ -553,18 +577,26 @@ async def get_git_commits(
offset: int = 0,
sort: str = "risk",
authorship: str | None = None,
+ kind: str | None = None,
+ high_cut: float | None = None,
) -> list[GitCommit]:
"""Return a page of commits, sorted by change-risk (default) or recency.
``sort="risk"`` ranks by ``change_risk_score`` descending (the review-
priority order); ``sort="date"`` ranks by ``committed_at`` descending.
- ``authorship`` optionally narrows to ``agent`` / ``human`` commits.
+ ``authorship`` narrows to ``agent`` / ``human``; ``kind`` narrows to the
+ ``high`` review-priority band or to ``fixes``. Both filter the repository
+ rather than the page, so a filter still answers when the page it would
+ have filtered is uniform.
"""
order = GitCommit.committed_at.desc() if sort == "date" else GitCommit.change_risk_score.desc()
stmt = select(GitCommit).where(GitCommit.repository_id == repository_id)
- clause = _commit_authorship_clause(authorship)
- if clause is not None:
- stmt = stmt.where(clause)
+ for clause in (
+ _commit_authorship_clause(authorship),
+ _commit_kind_clause(kind, high_cut),
+ ):
+ if clause is not None:
+ stmt = stmt.where(clause)
result = await session.execute(stmt.order_by(order).limit(limit).offset(offset))
return list(result.scalars().all())
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index 288be7298..54609604a 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -223,25 +223,39 @@ def _commit_detail_from_row(
@router.get("/{repo_id}/commits", response_model=Paginated[CommitResponse])
async def get_commits(
repo_id: str,
- sort: str = Query("risk", pattern="^(risk|date)$"),
+ sort: str = Query("date", pattern="^(risk|date)$"),
authorship: str = Query("all", pattern="^(all|agent|human)$"),
+ kind: str = Query("all", pattern="^(all|high|fixes)$"),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
session: AsyncSession = Depends(get_db_session),
) -> Paginated[CommitResponse]:
"""Per-commit change-risk feed — the review-priority queue.
- ``sort=risk`` (default) orders by supporting diff-shape score descending (the
- review-priority order); ``sort=date`` orders by recency. ``authorship``
- narrows the feed to agent-attributed or human commits. Each commit also
- carries a **repo-relative** ``risk_percentile`` + ``review_priority`` so the
- ranking is portable across repos (the absolute calibration band is not).
+ ``sort=date`` (default) orders by recency; ``sort=risk`` orders by the
+ supporting diff-shape score descending. ``authorship`` narrows to
+ agent-attributed or human commits, and ``kind`` to the ``high``
+ review-priority band or to ``fixes``. Each commit carries a
+ **repo-relative** ``risk_percentile`` + ``review_priority`` so the ranking
+ is portable across repos (the absolute calibration band is not).
"""
- total = await crud.count_git_commits(session, repo_id, authorship=authorship)
+ normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
+ # The high band is a tercile of the repo's own scores, so the boundary has
+ # to be resolved before the page is cut rather than derived per row.
+ high_cut = normalizer.high_cut
+ total = await crud.count_git_commits(
+ session, repo_id, authorship=authorship, kind=kind, high_cut=high_cut
+ )
rows = await crud.get_git_commits(
- session, repo_id, limit=limit, offset=offset, sort=sort, authorship=authorship
+ session,
+ repo_id,
+ limit=limit,
+ offset=offset,
+ sort=sort,
+ authorship=authorship,
+ kind=kind,
+ high_cut=high_cut,
)
- normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
author_counts = await _author_commit_counts(session, repo_id)
items = [_commit_from_row(r, normalizer, author_counts) for r in rows]
next_offset = offset + limit if offset + limit < total else None
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
index 4a076c333..2979dccef 100644
--- a/packages/ui/src/commits/commit-table.tsx
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -14,6 +14,7 @@ import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
export type CommitSort = "risk" | "date";
export type CommitAuthorship = "all" | "human" | "agent";
+export type CommitKind = "all" | "high" | "fixes";
export interface CommitTableProps {
commits: Commit[];
@@ -24,6 +25,13 @@ export interface CommitTableProps {
* no handler is provided. */
authorship?: CommitAuthorship;
onAuthorshipChange?: (authorship: CommitAuthorship) => void;
+ /** Server-driven review-priority / fixes filter. */
+ kind?: CommitKind;
+ onKindChange?: (kind: CommitKind) => void;
+ /** Repo-wide counts for the filter chips. Page-scoped counts read as
+ * "All (50), High priority (50)" on a risk-sorted feed, where every loaded
+ * row is already in the top tercile. */
+ counts?: { all: number; high: number; fixes: number } | undefined;
onSelect?: (commit: Commit) => void;
total?: number;
hasMore?: boolean;
@@ -31,8 +39,6 @@ export interface CommitTableProps {
onLoadMore?: () => void;
}
-type Filter = "all" | "high" | "fixes";
-
type CommitRow = Commit & { _idx: number };
const COLUMNS: ResponsiveColumn<CommitRow>[] = [
@@ -128,21 +134,6 @@ const COLUMNS: ResponsiveColumn<CommitRow>[] = [
</span>
),
},
- {
- key: "top_driver",
- header: "Top driver",
- headerClassName: "max-xl:hidden",
- cellClassName: "max-xl:hidden max-w-[220px]",
- hideInCard: true,
- render: (c) => (
- <span
- className="block truncate text-xs text-[var(--color-text-tertiary)]"
- title={c.top_driver ?? undefined}
- >
- {c.top_driver ?? "—"}
- </span>
- ),
- },
];
/**
@@ -157,6 +148,9 @@ export function CommitTable({
onSortChange,
authorship = "all",
onAuthorshipChange,
+ kind = "all",
+ onKindChange,
+ counts,
onSelect,
total,
hasMore,
@@ -164,23 +158,19 @@ export function CommitTable({
onLoadMore,
}: CommitTableProps) {
const [search, setSearch] = useState("");
- const [filter, setFilter] = useState<Filter>("all");
+ // Search stays client-side over the loaded page; the band and fix filters
+ // are server-driven, so they narrow the repository rather than the page.
const filtered = useMemo(() => {
- let items = commits;
- if (search) {
- const q = search.toLowerCase();
- items = items.filter(
- (c) =>
- c.subject.toLowerCase().includes(q) ||
- c.author_name.toLowerCase().includes(q) ||
- c.sha.toLowerCase().includes(q),
- );
- }
- if (filter === "high") items = items.filter((c) => c.review_priority === "high");
- else if (filter === "fixes") items = items.filter((c) => c.is_fix);
- return items;
- }, [commits, search, filter]);
+ if (!search) return commits;
+ const q = search.toLowerCase();
+ return commits.filter(
+ (c) =>
+ c.subject.toLowerCase().includes(q) ||
+ c.author_name.toLowerCase().includes(q) ||
+ c.sha.toLowerCase().includes(q),
+ );
+ }, [commits, search]);
if (commits.length === 0 && authorship === "all") {
return (
@@ -191,14 +181,10 @@ export function CommitTable({
);
}
- const filters: { key: Filter; label: string; count: number }[] = [
- { key: "all", label: "All", count: commits.length },
- {
- key: "high",
- label: "High priority",
- count: commits.filter((c) => c.review_priority === "high").length,
- },
- { key: "fixes", label: "Fixes", count: commits.filter((c) => c.is_fix).length },
+ const filters: { key: CommitKind; label: string; count: number | undefined }[] = [
+ { key: "all", label: "All", count: counts?.all },
+ { key: "high", label: "High priority", count: counts?.high },
+ { key: "fixes", label: "Fixes", count: counts?.fixes },
];
const sorts: { key: CommitSort; label: string }[] = [
@@ -222,16 +208,21 @@ export function CommitTable({
{filters.map((f) => (
<button
key={f.key}
- onClick={() => setFilter(f.key)}
+ onClick={() => onKindChange?.(f.key)}
+ aria-pressed={kind === f.key}
className={cn(
"px-2.5 py-1.5 font-medium transition-colors",
- filter === f.key
+ kind === f.key
? "bg-[var(--color-accent-primary)] text-[var(--color-text-inverse)]"
: "bg-transparent text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]",
)}
>
{f.label}
- <span className="ml-1 text-[10px] opacity-70">({f.count})</span>
+ {f.count != null && (
+ <span className="ml-1 text-[10px] opacity-70">
+ ({f.count.toLocaleString()})
+ </span>
+ )}
</button>
))}
</div>
diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsx
index 62179baec..2606620fe 100644
--- a/packages/web/src/app/repos/[id]/commits/page.tsx
+++ b/packages/web/src/app/repos/[id]/commits/page.tsx
@@ -61,7 +61,7 @@ export default async function CommitsPage({
safeFetch(() => getCommitEvolution(id)),
safeFetch(() => getAgentTrend(id)),
safeFetch(() =>
- getCommitsPage(id, { sort: "risk", authorship: "all", limit: PAGE_SIZE }),
+ getCommitsPage(id, { sort: "date", authorship: "all", limit: PAGE_SIZE }),
),
safeFetch(() => getCommitsPage(id, { sort: "date", limit: SCATTER_SAMPLE })),
]);
@@ -103,11 +103,24 @@ export default async function CommitsPage({
{trend && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
<OverviewSection
- title="Review-priority queue"
- description="Ranked by change-risk, highest first. Priority is a tercile of this repo's own distribution, so a quiet repo still fills its top band."
+ title="Review queue"
+ description="Newest first by default. Priority is a tercile of this repo's own distribution, so sorting by it shows only the top third — the filters narrow the whole repository, not the page."
action={<CredibilityInfoButton />}
>
- <CommitQueue repoId={id} initial={firstPage} total={total} />
+ <CommitQueue
+ repoId={id}
+ initial={firstPage}
+ total={total}
+ counts={
+ stats
+ ? {
+ all: stats.total_commits,
+ high: stats.high_priority_count,
+ fixes: stats.fix_commit_count,
+ }
+ : undefined
+ }
+ />
</OverviewSection>
<OverviewSection
diff --git a/packages/web/src/components/commits/commit-queue.tsx b/packages/web/src/components/commits/commit-queue.tsx
index 94a0e799e..b53c11fe0 100644
--- a/packages/web/src/components/commits/commit-queue.tsx
+++ b/packages/web/src/components/commits/commit-queue.tsx
@@ -1,59 +1,85 @@
"use client";
-import { useState } from "react";
-import useSWR from "swr";
+import { useMemo, useState } from "react";
+import useSWRInfinite from "swr/infinite";
import { useQueryState } from "nuqs";
import {
CommitTable,
type CommitAuthorship,
+ type CommitKind,
type CommitSort,
} from "@repowise-dev/ui/commits/commit-table";
import { getCommitsPage } from "@/lib/api/git";
import type { CommitResponse, Paginated } from "@/lib/api/types";
const PAGE_SIZE = 50;
-const MAX_ROWS = 200;
/**
* The review queue: the one part of this page that genuinely needs client
- * state. Sort, authorship filter and paging all refetch, and selecting a row
- * writes `?commit=` so the detail sheet can be a separate island that shares
- * state through the URL rather than through a common parent — which is what
- * kept the whole page a client component before.
+ * state. Sort, the filters and paging all refetch, and selecting a row writes
+ * `?commit=` so the detail sheet can be a separate island that shares state
+ * through the URL rather than through a common parent.
*
- * The first page is server-rendered and handed in as `initial`, so the table
- * is in the initial HTML and SWR only takes over once the reader changes
- * something.
+ * Pages accumulate through `offset` rather than by growing `limit`, so the
+ * whole history is reachable: the endpoint caps a single page at 200, which
+ * used to be the ceiling on everything the queue could ever show.
*/
export function CommitQueue({
repoId,
initial,
total,
+ counts,
}: {
repoId: string;
initial: Paginated<CommitResponse>;
total: number;
+ /** Repo-wide chip counts, from the stats endpoint the page already fetches. */
+ counts?: { all: number; high: number; fixes: number } | undefined;
}) {
- const [sort, setSort] = useState<CommitSort>("risk");
+ const [sort, setSort] = useState<CommitSort>("date");
const [authorship, setAuthorship] = useState<CommitAuthorship>("all");
- const [limit, setLimit] = useState(PAGE_SIZE);
+ const [kind, setKind] = useState<CommitKind>("all");
const [, setSelectedSha] = useQueryState("commit");
- const pristine = sort === "risk" && authorship === "all" && limit === PAGE_SIZE;
+ const pristine = sort === "date" && authorship === "all" && kind === "all";
- const { data, isLoading, isValidating } = useSWR<Paginated<CommitResponse>>(
- `commits:${repoId}:${sort}:${authorship}:${limit}`,
- () => getCommitsPage(repoId, { sort, authorship, limit }),
+ const { data, size, setSize, isLoading, isValidating } = useSWRInfinite<
+ Paginated<CommitResponse>
+ >(
+ (pageIndex, previous) => {
+ if (previous && !previous.has_more) return null;
+ return `commits:${repoId}:${sort}:${authorship}:${kind}:${pageIndex}`;
+ },
+ (key) => {
+ const pageIndex = parseInt(key.split(":").pop() as string, 10);
+ return getCommitsPage(repoId, {
+ sort,
+ authorship,
+ kind,
+ limit: PAGE_SIZE,
+ offset: pageIndex * PAGE_SIZE,
+ });
+ },
{
revalidateOnFocus: false,
+ revalidateFirstPage: false,
keepPreviousData: true,
- // Nothing to fetch until the reader moves off the server-rendered view.
- fallbackData: pristine ? initial : undefined,
+ // The first page is server-rendered, so an untouched queue fetches nothing.
+ fallbackData: pristine ? [initial] : undefined,
revalidateOnMount: !pristine,
},
);
- const list = data?.items ?? initial.items;
+ const list = useMemo(
+ () => (data ? data.flatMap((p) => p.items) : initial.items),
+ [data, initial.items],
+ );
+ const loadedTotal = data && data.length > 0 ? data[0].total : total;
+ const hasMore = data ? !!data[data.length - 1]?.has_more : initial.has_more;
+
+ // Every filter change resets to one page; SWRInfinite keeps `size` across
+ // key changes otherwise, which would refetch every page of the new filter.
+ const reset = () => void setSize(1);
return (
<CommitTable
@@ -61,18 +87,24 @@ export function CommitQueue({
sort={sort}
onSortChange={(s) => {
setSort(s);
- setLimit(PAGE_SIZE);
+ reset();
}}
authorship={authorship}
onAuthorshipChange={(a) => {
setAuthorship(a);
- setLimit(PAGE_SIZE);
+ reset();
+ }}
+ kind={kind}
+ onKindChange={(k) => {
+ setKind(k);
+ reset();
}}
+ counts={counts}
onSelect={(c) => void setSelectedSha(c.sha)}
- total={total}
- hasMore={data?.has_more ?? initial.has_more}
+ total={loadedTotal}
+ hasMore={hasMore}
loadingMore={isValidating && !isLoading}
- onLoadMore={() => setLimit((n) => Math.min(n + PAGE_SIZE, MAX_ROWS))}
+ onLoadMore={() => void setSize((n) => n + 1)}
/>
);
}
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index 0769e95dc..a508f7fc4 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -261,6 +261,84 @@ async def test_get_commits_sorted_by_risk(client: AsyncClient, app) -> None:
assert items[-1]["review_priority"] == "low"
+async def test_the_high_band_filters_the_repository_not_the_page(
+ client: AsyncClient, app
+) -> None:
+ """A risk-sorted page is entirely top-tercile, so a page-scoped filter is a no-op."""
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits", params={"kind": "high"})
+ assert resp.status_code == 200
+ payload = resp.json()
+
+ assert payload["total"] == 1
+ assert [c["short_sha"] for c in payload["items"]] == ["bbbbbbbb"]
+ assert all(c["review_priority"] == "high" for c in payload["items"])
+
+
+async def test_the_fixes_filter_counts_the_whole_repository(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_git_commits_bulk(
+ session,
+ repo["id"],
+ [
+ {
+ "sha": "ffffffff44",
+ "author_name": "Ann",
+ "author_email": "[email protected]",
+ "committed_at": datetime.fromtimestamp(4000, tz=UTC),
+ "subject": "fix: a real one",
+ "lines_added": 3,
+ "lines_deleted": 1,
+ "files_changed": 1,
+ "dirs_changed": 1,
+ "subsystems_changed": 1,
+ "entropy": 0.1,
+ "is_fix": True,
+ "author_experience": 3,
+ "change_risk_score": 1.0,
+ "change_risk_level": "low",
+ }
+ ],
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits", params={"kind": "fixes"})
+ assert resp.status_code == 200
+ payload = resp.json()
+
+ assert payload["total"] == 1
+ assert [c["short_sha"] for c in payload["items"]] == ["ffffffff"]
+
+
+async def test_an_unknown_kind_is_rejected_rather_than_ignored(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits", params={"kind": "spicy"})
+
+ assert resp.status_code == 422
+
+
+async def test_the_feed_defaults_to_recency(client: AsyncClient, app) -> None:
+ """Risk order shows only the top tercile, so it is no longer the default."""
+ repo = await create_test_repo(client)
+ await _insert_git_commits(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/commits")
+
+ assert [c["short_sha"] for c in resp.json()["items"]] == [
+ "aaaaaaaa",
+ "cccccccc",
+ "bbbbbbbb",
+ ]
+
+
@pytest.mark.asyncio
async def test_get_commits_sorted_by_date(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)