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(overview): a short Overview that opens on what to do (#4163)

Raghav Chamadiya7c3fbfea9440
diff --git a/packages/api-client/src/security.test.ts b/packages/api-client/src/security.test.ts
new file mode 100644
index 000000000..21878ab48
--- /dev/null
+++ b/packages/api-client/src/security.test.ts
@@ -0,0 +1,12 @@
+import { describe, expectTypeOf, it } from "vitest";
+import type * as Wire from "@repowise-dev/types/security";
+
+import type { SecurityFinding, SecuritySummary } from "./security";
+
+describe("security client types", () => {
+ it("are the types package's wire shapes, new fields included", () => {
+ expectTypeOf<SecurityFinding>().toEqualTypeOf<Wire.SecurityFinding>();
+ expectTypeOf<SecuritySummary>().toEqualTypeOf<Wire.SecuritySummary>();
+ expectTypeOf<SecuritySummary["class_counts"]>().not.toBeNever();
+ });
+});
diff --git a/packages/api-client/src/security.ts b/packages/api-client/src/security.ts
index 2b0b7568a..af12b9858 100644
--- a/packages/api-client/src/security.ts
+++ b/packages/api-client/src/security.ts
@@ -1,22 +1,9 @@
+import type { SecurityFinding, SecuritySummary } from "@repowise-dev/types/security";
import { apiGet } from "./client";
-export interface SecurityFinding {
- id: number;
- file_path: string;
- kind: string;
- severity: "high" | "med" | "low" | string;
- snippet: string | null;
- detected_at: string;
- /** Verified against the live tree; `null` when the snippet has moved away. */
- line_number: number | null;
- line_verified: boolean;
- commit_at: string | null;
-}
-
-export interface SecuritySummary {
- /** ISO 8601 UTC; `null`/absent = never ran or unknown (not an all-clear). */
- scanned_at?: string | null;
-}
+// One definition of the wire shapes: the types package's, so a field the
+// server adds (path class, class counts) reaches every typed consumer.
+export type { SecurityFinding, SecurityPathClass, SecuritySummary } from "@repowise-dev/types/security";
export async function getSecuritySummary(repoId: string): Promise<SecuritySummary> {
return apiGet<SecuritySummary>(`/api/repos/${repoId}/security/summary`);
diff --git a/packages/server/src/repowise/server/routers/overview.py b/packages/server/src/repowise/server/routers/overview.py
index f162718a7..88332b976 100644
--- a/packages/server/src/repowise/server/routers/overview.py
+++ b/packages/server/src/repowise/server/routers/overview.py
@@ -21,6 +21,7 @@ from repowise.core.persistence.models import GitMetadata
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.routers.git import _hotspot_from_row
from repowise.server.services import overview_payload as sections
+from repowise.server.services.overview_counts import explore_counts
router = APIRouter(
prefix="/api/repos",
@@ -129,6 +130,8 @@ async def overview_summary(
"top_hotspots": await _top_hotspots(session, repo_id),
"recent_decisions": await sections.recent_decisions(session, repo_id),
"savings": await sections.savings_block(repo.local_path),
+ # The figures the explore cards and inventory share with their pages.
+ "explore": await explore_counts(session, repo_id),
"sync": await sections.sync_block(
session, repo_id, repo, page_count=stats["doc_page_count"]
),
diff --git a/packages/server/src/repowise/server/routers/security.py b/packages/server/src/repowise/server/routers/security.py
index 46395e842..df9025f75 100644
--- a/packages/server/src/repowise/server/routers/security.py
+++ b/packages/server/src/repowise/server/routers/security.py
@@ -13,6 +13,7 @@ from repowise.core.persistence.models import Repository, SecurityFinding
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.schemas import SecurityFindingResponse, SecuritySummaryResponse
from repowise.server.services.analysis_ran_at import security_scanned_at
+from repowise.server.services.security_classes import path_classes, security_class_counts
from repowise.server.services.security_lines import check_finding_line
router = APIRouter(
@@ -61,6 +62,7 @@ async def list_security_findings(
# on a cold cache. If that ever bites, verify at scan time and persist the
# outcome instead of re-deriving it per request.
file_cache: dict[str, list[str] | None] = {}
+ classes = await path_classes(session, repo_id, (row.file_path for row in rows))
responses = []
for row in rows:
@@ -83,6 +85,7 @@ async def list_security_findings(
commit_sha=row.commit_sha or None,
commit_at=row.commit_at,
found_in_history=bool(row.commit_sha),
+ path_class=classes[row.file_path],
)
)
return responses
@@ -93,8 +96,12 @@ async def security_summary(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
) -> SecuritySummaryResponse:
- """When the pattern scan last ran; ``scanned_at`` is null when unknown."""
- return SecuritySummaryResponse(scanned_at=await security_scanned_at(session, repo_id))
+ """When the pattern scan last ran (null when unknown), and every stored
+ finding counted by shipped source, tests and docs."""
+ return SecuritySummaryResponse(
+ scanned_at=await security_scanned_at(session, repo_id),
+ **await security_class_counts(session, repo_id),
+ )
async def _repo_root(session: AsyncSession, repo_id: str) -> Path | None:
diff --git a/packages/server/src/repowise/server/routers/stats.py b/packages/server/src/repowise/server/routers/stats.py
index b363b4fd3..649dac06b 100644
--- a/packages/server/src/repowise/server/routers/stats.py
+++ b/packages/server/src/repowise/server/routers/stats.py
@@ -2,8 +2,9 @@
A read-only aggregate for the repo Stats page. The derivations live in
:mod:`repowise.core.stats_highlights` so the hosted backend can build the same
-payload from its artifacts; this module only reads rows. Every read is a narrow
-column select or a capped ordered query, and nothing recomputes analysis.
+payload from its artifacts; this module reads rows plus one threaded size walk
+of ``.repowise/``. Every read is a narrow column select or a capped ordered
+query, and nothing recomputes analysis.
"""
from __future__ import annotations
@@ -27,6 +28,7 @@ from repowise.core.persistence.models import (
WikiSymbol,
)
from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.services.index_storage import index_storage_bytes
router = APIRouter(
prefix="/api/repos",
@@ -241,6 +243,8 @@ async def stats_highlights(
"chronotypes": activity["chronotypes"],
"arrivals": activity["arrivals"],
}
+ # Absent, not zero, where no local index exists to measure.
+ index_size = await index_storage_bytes(repo.local_path)
return {
"repo": {"id": repo.id, "name": repo.name},
"scale": sh.build_scale(file_nodes, metrics),
@@ -249,4 +253,5 @@ async def stats_highlights(
"rhythm": rhythm,
"people": people,
"records": records,
+ **({"index_storage_bytes": index_size} if index_size is not None else {}),
}
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index 50358db28..e7f135a6f 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -4,8 +4,9 @@ from __future__ import annotations
import json
from datetime import datetime
+from typing import Literal
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from repowise.core.analysis.dead_code.deletion_gate import effective_safe_to_delete
from repowise.core.analysis.dead_code.risk_factors import (
@@ -132,11 +133,20 @@ class SecurityFindingResponse(BaseModel):
commit_sha: str | None
commit_at: datetime | None
found_in_history: bool
+ # Shipped source, tests, or docs (``services/security_classes.py``).
+ path_class: Literal["source", "test", "docs"] = "source"
class SecuritySummaryResponse(BaseModel):
# When the pattern scan last ran; None = never ran or unknown (not all-clear).
scanned_at: datetime | None = None
+ # Every stored finding, and how many sit in shipped source, tests and docs
+ # (``services/security_classes.py``). The page lede reads these rather
+ # than counting a capped list.
+ total: int = 0
+ class_counts: dict[Literal["source", "test", "docs"], int] = Field(default_factory=dict)
+ # High-severity findings in shipped source.
+ source_high: int = 0
class RepoStatsResponse(BaseModel):
diff --git a/packages/server/src/repowise/server/services/index_storage.py b/packages/server/src/repowise/server/services/index_storage.py
new file mode 100644
index 000000000..be89d54d7
--- /dev/null
+++ b/packages/server/src/repowise/server/services/index_storage.py
@@ -0,0 +1,38 @@
+"""On-disk size of a repo's ``.repowise/`` directory, for the Stats page."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+from pathlib import Path
+
+
+def walk_index_storage_bytes(repowise_dir: Path) -> int:
+ """Total on-disk size of a repo's ``.repowise/`` directory."""
+ if not repowise_dir.is_dir():
+ return 0
+ total = 0
+ for path in repowise_dir.rglob("*"):
+ if path.is_file():
+ with contextlib.suppress(OSError):
+ total += path.stat().st_size
+ return total
+
+
+async def index_storage_bytes(local_path: str | None) -> int | None:
+ """``walk_index_storage_bytes`` for a repo checkout, off the event loop;
+ ``None`` when there is no local index to measure.
+
+ The walk is a full recursive stat of a directory that holds the vectors,
+ the wiki and the symbol store, routinely hundreds of megabytes and tens of
+ thousands of files, so it runs in a thread rather than blocking the loop.
+
+ Ceiling: the walk still happens once per Stats page load. The real fix is
+ to stamp the size when the index is written and read the number back.
+ """
+ if not local_path:
+ return None
+ repowise_dir = Path(local_path) / ".repowise"
+ if not repowise_dir.is_dir():
+ return None
+ return await asyncio.to_thread(walk_index_storage_bytes, repowise_dir)
diff --git a/packages/server/src/repowise/server/services/overview_counts.py b/packages/server/src/repowise/server/services/overview_counts.py
new file mode 100644
index 000000000..5a4b9b773
--- /dev/null
+++ b/packages/server/src/repowise/server/services/overview_counts.py
@@ -0,0 +1,113 @@
+"""The figures Overview's explore cards and inventory share with their pages.
+
+Each count is read through the function the destination page leads with, so
+the Overview figure and the page figure cannot disagree:
+
+- decisions: ``count_decisions_by_lane``, the Decisions page lede;
+- refactoring: the stored rollup the Refactoring page lede reads;
+- ownership: files with bus factor exactly 1, the Contributors page's
+ "Sole-owned files";
+- security: :func:`security_class_counts`, the split the Security page lede
+ reads, "in shipped source" versus tests and docs;
+- coverage: the newest ingested report, the Tests page lede.
+
+The reads are grouped counts, a primary-key read and the decision lanes'
+three-column scan the Decisions page already pays. Each runs in a savepoint,
+so a store that fails costs its own block rather than the page.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from sqlalchemy import func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.health.refactoring.serving import summary_payload
+from repowise.core.persistence import crud
+from repowise.core.persistence.crud.analysis.coverage import load_newest_ingest
+from repowise.core.persistence.crud.analysis.refactoring_opportunities import (
+ get_refactoring_summary,
+)
+from repowise.core.persistence.models import GitMetadata
+from repowise.server.services.security_classes import security_class_counts
+
+
+async def _decisions(session: AsyncSession, repo_id: str) -> dict[str, int]:
+ lanes = await crud.count_decisions_by_lane(session, repo_id)
+ return {
+ "total": int(lanes.get("total", 0)),
+ "accepted": int(
+ lanes.get("active", 0) + lanes.get("needs_review", 0) + lanes.get("uncheckable", 0)
+ ),
+ "candidates": int(lanes.get("candidates", 0)),
+ "needs_review": int(lanes.get("needs_review", 0)),
+ }
+
+
+async def _refactoring(session: AsyncSession, repo_id: str) -> dict[str, int] | None:
+ # The rollup the Refactoring lede reads, without the gate breakdown the
+ # page adds beside it.
+ summary = summary_payload(await get_refactoring_summary(session, repo_id))
+ if summary.get("status") != "available":
+ return None
+ return {
+ "opportunities_total": int(summary.get("opportunities_total") or 0),
+ "files_total": int(summary.get("files_total") or 0),
+ }
+
+
+async def _ownership(session: AsyncSession, repo_id: str) -> dict[str, int]:
+ # Exactly 1, credited to a primary owner (named or by email), as the
+ # owners rollup counts it: a bus factor of 0 means no indexed history.
+ sole = await session.scalar(
+ select(func.count()).where(
+ crud.code_file_rows(repo_id),
+ GitMetadata.bus_factor == 1,
+ or_(GitMetadata.primary_owner_name != "", GitMetadata.primary_owner_email != ""),
+ )
+ )
+ return {"sole_owned_files": int(sole or 0)}
+
+
+async def _security(session: AsyncSession, repo_id: str) -> dict[str, int]:
+ counts = await security_class_counts(session, repo_id)
+ classes = counts["class_counts"]
+ return {
+ "total": counts["total"],
+ "source": classes["source"],
+ "source_high": counts["source_high"],
+ "elsewhere": classes["test"] + classes["docs"],
+ }
+
+
+async def _coverage(session: AsyncSession, repo_id: str) -> dict[str, Any] | None:
+ ingest = await load_newest_ingest(session, repo_id)
+ if ingest is None or ingest.line_coverage_pct is None:
+ return None
+ return {
+ "line_coverage_pct": float(ingest.line_coverage_pct),
+ "ingested_at": ingest.ingested_at.isoformat() if ingest.ingested_at else None,
+ }
+
+
+_BLOCKS: tuple[tuple[str, Callable[[AsyncSession, str], Awaitable[Any]]], ...] = (
+ ("decisions", _decisions),
+ ("refactoring", _refactoring),
+ ("ownership", _ownership),
+ ("security", _security),
+ ("coverage", _coverage),
+)
+
+
+async def explore_counts(session: AsyncSession, repo_id: str) -> dict[str, Any]:
+ """One block per page; ``None`` where the store is absent or failed."""
+ out: dict[str, Any] = {}
+ for key, read in _BLOCKS:
+ try:
+ async with session.begin_nested():
+ out[key] = await read(session, repo_id)
+ except Exception:
+ out[key] = None
+ return out
diff --git a/packages/server/src/repowise/server/services/overview_payload.py b/packages/server/src/repowise/server/services/overview_payload.py
index 699d7545a..c3debace6 100644
--- a/packages/server/src/repowise/server/services/overview_payload.py
+++ b/packages/server/src/repowise/server/services/overview_payload.py
@@ -7,10 +7,8 @@ payload field for field, so a builder's keys and their order are its contract.
from __future__ import annotations
-import asyncio
import contextlib
import json
-from pathlib import Path
from typing import Any
from sqlalchemy import func, select
@@ -405,33 +403,6 @@ async def savings_block(repo_local_path: str | None) -> dict:
}
-def walk_index_storage_bytes(repowise_dir: Path) -> int:
- """Total on-disk size of a repo's ``.repowise/`` directory."""
- if not repowise_dir.is_dir():
- return 0
- total = 0
- for path in repowise_dir.rglob("*"):
- if path.is_file():
- with contextlib.suppress(OSError):
- total += path.stat().st_size
- return total
-
-
-async def index_storage_bytes(repowise_dir: Path) -> int:
- """``walk_index_storage_bytes`` off the event loop.
-
- The walk is a full recursive stat of a directory that holds the vectors,
- the wiki and the symbol store, routinely hundreds of megabytes and tens of
- thousands of files. Run inline in an ``async def`` it blocks the worker's
- event loop for its whole duration, stalling every other request in flight.
-
- Ceiling: a thread is the cheap fix, and the walk still happens once per
- page load. The real fix is to stamp the size when the index is written and
- read the number back; do that if this ever shows up in a profile again.
- """
- return await asyncio.to_thread(walk_index_storage_bytes, repowise_dir)
-
-
def sync_times(job_rows: list[Any], repo_updated_at: Any) -> dict:
"""Last sync, last full re-index, its model and any active job id.
@@ -479,7 +450,7 @@ def sync_times(job_rows: list[Any], repo_updated_at: Any) -> dict:
async def sync_block(session: AsyncSession, repo_id: str, repo: Any, page_count: int) -> dict:
- """Sync status from the last 30 jobs, plus page count and index size."""
+ """Sync status from the last 30 jobs, plus the page count."""
job_rows = (
(
await session.execute(
@@ -492,9 +463,4 @@ async def sync_block(session: AsyncSession, repo_id: str, repo: Any, page_count:
.scalars()
.all()
)
- repowise_dir = Path(repo.local_path) / ".repowise" if repo.local_path else Path(".repowise")
- return {
- **sync_times(job_rows, repo.updated_at),
- "page_count": page_count,
- "index_storage_bytes": await index_storage_bytes(repowise_dir),
- }
+ return {**sync_times(job_rows, repo.updated_at), "page_count": page_count}
diff --git a/packages/server/src/repowise/server/services/security_classes.py b/packages/server/src/repowise/server/services/security_classes.py
new file mode 100644
index 000000000..10658614d
--- /dev/null
+++ b/packages/server/src/repowise/server/services/security_classes.py
@@ -0,0 +1,79 @@
+"""Which population a security finding's file belongs to: shipped source,
+tests, or docs.
+
+Read from the file's stored ``code_origin`` (the same classification every
+health surface narrows on), falling back to the path-only origin for a file
+with no health row, such as a history finding on a deleted file. Prose files
+carry no origin of their own, so the engine's doc-path rule names them. Test
+wins over docs: ``tests/fixtures/leak.md`` is test material. Config counts as
+source on purpose: a secret in one ships.
+
+The Security page lede and Overview both read these counts, so they agree.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import Literal
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.finding_registry import stored_origin
+from repowise.core.code_origin import path_origin
+from repowise.core.ingestion.git_indexer.fix_shape import is_doc_path
+from repowise.core.persistence.models import HealthFileMetric, SecurityFinding
+
+PathClass = Literal["source", "test", "docs"]
+
+#: Paths per ``IN`` read, well under every backend's bound-parameter limit.
+_CHUNK = 500
+
+
+def path_class(path: str, origin: str) -> PathClass:
+ """The population of *path*, given its code origin."""
+ if origin == "test":
+ return "test"
+ if origin == "docs_example" or is_doc_path(path):
+ return "docs"
+ return "source"
+
+
+async def path_classes(
+ session: AsyncSession, repo_id: str, paths: Iterable[str]
+) -> dict[str, PathClass]:
+ """``{path: class}`` for *paths*, from their stored origins."""
+ wanted = sorted(set(paths))
+ origins: dict[str, str] = {}
+ for i in range(0, len(wanted), _CHUNK):
+ rows = await session.execute(
+ select(
+ HealthFileMetric.file_path, HealthFileMetric.code_origin, HealthFileMetric.is_test
+ ).where(
+ HealthFileMetric.repository_id == repo_id,
+ HealthFileMetric.file_path.in_(wanted[i : i + _CHUNK]),
+ )
+ )
+ for path, origin, is_test in rows.all():
+ origins[path] = stored_origin(origin, is_test)
+ return {p: path_class(p, origins.get(p) or path_origin(p)) for p in wanted}
+
+
+async def security_class_counts(session: AsyncSession, repo_id: str) -> dict[str, object]:
+ """Every stored finding counted by class, plus the high ones in source."""
+ groups = (
+ await session.execute(
+ select(SecurityFinding.file_path, SecurityFinding.severity, func.count())
+ .where(SecurityFinding.repository_id == repo_id)
+ .group_by(SecurityFinding.file_path, SecurityFinding.severity)
+ )
+ ).all()
+ classes = await path_classes(session, repo_id, (path for path, _, _ in groups))
+ counts: dict[str, int] = {"source": 0, "test": 0, "docs": 0}
+ source_high = 0
+ for path, severity, n in groups:
+ cls = classes[path]
+ counts[cls] += n
+ if cls == "source" and severity == "high":
+ source_high += n
+ return {"total": sum(counts.values()), "class_counts": counts, "source_high": source_high}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index fb137217e..30f115634 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4057,10 +4057,14 @@ export interface SecurityFindingResponse {
commit_sha: string | null;
commit_at: string | null;
found_in_history: boolean;
+ path_class?: "source" | "test" | "docs";
}
export interface SecuritySummaryResponse {
scanned_at?: string | null;
+ total?: number;
+ class_counts?: Record<string, number>;
+ source_high?: number;
}
export interface SelectionProvenance {
diff --git a/packages/types/src/overview.ts b/packages/types/src/overview.ts
index 72579b0b4..cb633be73 100644
--- a/packages/types/src/overview.ts
+++ b/packages/types/src/overview.ts
@@ -253,10 +253,28 @@ export interface OverviewSyncStatus {
last_sync_model: string | null;
active_job_id: string | null;
page_count: number;
- /** Total on-disk size of the repo's `.repowise/` directory (bytes). */
+ /** @deprecated Not sent by the OSS server; read `StatsHighlights.index_storage_bytes`. */
index_storage_bytes?: number;
}
+/**
+ * Figures Overview shares with the pages it links to, each read through the
+ * function that page leads with. A block is `null` when its store is absent.
+ */
+export interface OverviewExploreCounts {
+ /** The Decisions page lanes: accepted of total recorded, candidates
+ * awaiting review, and accepted ones drifting from the code. */
+ decisions: { total: number; accepted: number; candidates: number; needs_review: number } | null;
+ /** The Refactoring page lede: open opportunities, one per file. */
+ refactoring: { opportunities_total: number; files_total: number } | null;
+ /** The Contributors page: files with one author and no second reader. */
+ ownership: { sole_owned_files: number } | null;
+ /** The Security page lede: matches in shipped source versus tests and docs. */
+ security: { total: number; source: number; source_high: number; elsewhere: number } | null;
+ /** The Tests page lede; `null` until a coverage report is ingested. */
+ coverage: { line_coverage_pct: number; ingested_at: string | null } | null;
+}
+
export interface OverviewSummaryResponse {
repo: OverviewRepoMeta;
stats: OverviewStats;
@@ -274,4 +292,6 @@ export interface OverviewSummaryResponse {
recent_decisions: OverviewDecisionSlim[];
savings: OverviewSavings;
sync: OverviewSyncStatus;
+ /** Optional: a server predating it omits the block. */
+ explore?: OverviewExploreCounts;
}
diff --git a/packages/types/src/security.ts b/packages/types/src/security.ts
index 683e466b7..643849d7a 100644
--- a/packages/types/src/security.ts
+++ b/packages/types/src/security.ts
@@ -8,6 +8,9 @@
export type SecuritySeverity = "high" | "med" | "low" | (string & {});
+/** Shipped source, tests, or docs, as the server classifies the file. */
+export type SecurityPathClass = "source" | "test" | "docs";
+
export interface SecurityFinding {
id: number;
file_path: string;
@@ -29,6 +32,8 @@ export interface SecurityFinding {
line_verified: boolean;
/** When the introducing commit landed; only set for history findings. */
commit_at: string | null;
+ /** Shipped source, tests, or docs. Absent on older servers. */
+ path_class?: SecurityPathClass;
}
/** Run metadata for the pattern scan, served beside the findings list. */
@@ -38,6 +43,12 @@ export interface SecuritySummary {
* means never ran or unknown, which is not an all-clear.
*/
scanned_at?: string | null;
+ /** Every stored finding. Absent on older servers, with the two below. */
+ total?: number;
+ /** Findings by where they sit: shipped source, tests, docs. */
+ class_counts?: Partial<Record<SecurityPathClass, number>>;
+ /** High-severity findings in shipped source. */
+ source_high?: number;
}
export interface SecurityFindingList {
diff --git a/packages/types/src/stats.ts b/packages/types/src/stats.ts
index e80bae3da..eee7e6863 100644
--- a/packages/types/src/stats.ts
+++ b/packages/types/src/stats.ts
@@ -244,4 +244,7 @@ export interface StatsHighlights {
rhythm: StatsRhythm;
people: StatsPeople;
records: StatsRecords;
+ /** On-disk size of the local `.repowise/` index. Absent where the index is
+ * not stored on this machine. */
+ index_storage_bytes?: number;
}
diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsx
index abf5cb973..ba0050f44 100644
--- a/packages/ui/__tests__/overview/next-actions.test.tsx
+++ b/packages/ui/__tests__/overview/next-actions.test.tsx
@@ -175,7 +175,7 @@ describe("NextActions", () => {
expect(details).not.toBeNull();
expect(details).not.toHaveAttribute("open");
// The count is the default time frame's, the same one its chip shows.
- expect(within(details!.querySelector("summary")!).getByText("1 suggested")).toBeInTheDocument();
+ expect(within(details!.querySelector("summary")!).getByRole("heading", { name: "Do next · 1" })).toBeInTheDocument();
details!.open = true;
fireEvent.click(within(details!).getByRole("radio", { name: /This quarter/ }));
@@ -183,13 +183,30 @@ describe("NextActions", () => {
"aria-checked",
"true",
);
- expect(screen.getByText("2 suggested")).toBeInTheDocument();
+ expect(screen.getByRole("heading", { name: "Do next · 2" })).toBeInTheDocument();
// React only writes `open` when the prop changes, so a rerender keeps a
// section the user opened open.
expect(details!.open).toBe(true);
});
});
+describe("the row prompt", () => {
+ it("opens the agent prompt from the row without opening the drawer", async () => {
+ const loadPrompt = vi.fn().mockResolvedValue("Prompt from core");
+ render(<NextActions data={response([], [action()])} hrefFor={() => null} loadPrompt={loadPrompt} />);
+ fireEvent.click(screen.getByRole("button", { name: /Copy prompt for your agent: Raise test coverage/ }));
+ const dialog = await screen.findByRole("dialog");
+ expect(await within(dialog).findByText("Prompt from core")).toBeInTheDocument();
+ expect(within(dialog).queryByText("Why it is on the list")).toBeNull();
+ expect(loadPrompt).toHaveBeenCalledWith(action(), expect.any(String));
+ });
+
+ it("is absent when the host has no prompt", () => {
+ render(<NextActions data={response([], [action()])} hrefFor={() => null} />);
+ expect(screen.queryByRole("button", { name: /Copy prompt for your agent/ })).toBeNull();
+ });
+});
+
describe("the action drawer", () => {
it("opens on a row click with the evidence link, the facts and the prompt", async () => {
const loadPrompt = vi.fn().mockResolvedValue("Prompt from core");
diff --git a/packages/ui/__tests__/overview/overview-body.test.tsx b/packages/ui/__tests__/overview/overview-body.test.tsx
new file mode 100644
index 000000000..de4dcf0f1
--- /dev/null
+++ b/packages/ui/__tests__/overview/overview-body.test.tsx
@@ -0,0 +1,288 @@
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+
+import { AttentionAreas } from "../../src/overview/attention-areas.js";
+import { HealthLede } from "../../src/overview/health-lede.js";
+import { OverviewBody } from "../../src/overview/overview-body.js";
+import { buildReads, inventoryRows } from "../../src/overview/overview-model.js";
+
+function summary(): OverviewSummaryResponse {
+ return {
+ repo: {
+ id: "r1",
+ name: "acme",
+ local_path: "/src/acme",
+ default_branch: "main",
+ head_commit: "abc1234",
+ updated_at: null,
+ },
+ stats: {
+ file_count: 6328,
+ symbol_count: 40000,
+ entry_point_count: 12,
+ doc_page_count: 300,
+ doc_prose_page_count: 200,
+ doc_coverage_pct: 80,
+ freshness_score: 90,
+ dead_export_count: 42,
+ hotspot_count: 1059,
+ silo_count: 3,
+ module_count: 20,
+ total_nloc: 500000,
+ deltas: { average_health: null, hotspot_health: null, file_count: null },
+ },
+ health: {
+ average_health: 8.04,
+ hotspot_health: 6.66,
+ maintainability_average: 8.6,
+ performance_average: 9.7,
+ worst_performer_path: null,
+ worst_performer_score: null,
+ open_findings: 10,
+ severity_breakdown: {},
+ last_indexed_at: null,
+ snapshot_count: 1,
+ history: [],
+ },
+ languages: [{ language: "python", file_count: 6000 }],
+ attention: [],
+ onboarding_targets: [],
+ top_hotspots: [],
+ recent_decisions: [
+ { id: "d1", title: "Use SQLite", status: "active", source: "adr", created_at: null },
+ ],
+ savings: { available: true, saved_input_tokens: 5_000_000, inferred_saved_input_tokens: 10 },
+ sync: {
+ last_sync_at: null,
+ last_resync_at: null,
+ last_sync_model: null,
+ active_job_id: null,
+ page_count: 300,
+ index_storage_bytes: 1_000_000,
+ },
+ } as unknown as OverviewSummaryResponse;
+}
+
+describe("HealthLede", () => {
+ it("leads with the score and one hotspot reading, without the other pillars", () => {
+ render(
+ <HealthLede
+ score={8.04}
+ maintainability={8.6}
+ performance={9.7}
+ hotspotHealth={6.66}
+ hotspotCount={1059}
+ fileCount={6328}
+ href="/h"
+ />,
+ );
+ expect(screen.getByText("8.0")).toBeInTheDocument();
+ expect(screen.getByText("6.6")).toBeInTheDocument();
+ expect(document.body.textContent).toMatch(/Hotspots average 6\.6, the place fixes pay off most\./);
+ expect(document.body.textContent).not.toMatch(/maintainability|performance|8\.6|9\.7/i);
+ expect(screen.getByRole("button", { name: "What Code health means" })).toBeInTheDocument();
+ });
+
+ it("names hotspots that hold up as a good state", () => {
+ render(<HealthLede score={7} hotspotHealth={7.5} hotspotCount={3} fileCount={10} href="/h" />);
+ expect(document.body.textContent).toMatch(/as healthy as the rest of the code/);
+ });
+
+ it("takes its words as props", () => {
+ render(
+ <HealthLede
+ score={7}
+ hotspotHealth={5}
+ hotspotCount={3}
+ fileCount={10}
+ href="/h"
+ copy={{ reportLink: "Rapport", hotspotReading: (f) => <>Points chauds {f}</> }}
+ />,
+ );
+ expect(screen.getByText("Rapport")).toBeInTheDocument();
+ expect(document.body.textContent).toMatch(/Points chauds 5\.0/);
+ });
+});
+
+describe("buildReads", () => {
+ it("keeps documentation and drops savings, dead code and index size", () => {
+ const keys = buildReads(summary(), { base: "/r", costs: "/r/costs", settings: "/r/s" }).map(
+ (r) => r.key,
+ );
+ expect(keys).toEqual(["docs"]);
+ });
+});
+
+describe("OverviewBody", () => {
+ it("is short: no ribbon, recent activity or composition, and renders the wins slot", () => {
+ render(
+ <OverviewBody
+ summary={summary()}
+ routes={{ base: "/r" }}
+ commits={[]}
+ totalNloc={500000}
+ slots={{ wins: <p>Recent wins here</p> }}
+ />,
+ );
+ expect(screen.getByText("Recent wins here")).toBeInTheDocument();
+ for (const gone of ["Recent activity", "Composition", "Lines of code", "Estimated agent savings", "Dead code"]) {
+ expect(screen.queryByText(gone)).toBeNull();
+ }
+ expect(screen.getByRole("link", { name: /Decisions/ })).toHaveAttribute("href", "/r/decisions");
+ });
+
+ it("orders ask, explore cards, Do next, wins, publish, then the folded inventory", () => {
+ const { container } = render(
+ <OverviewBody
+ summary={{
+ ...summary(),
+ attention_summary: { total: 1, areas: [] },
+ attention: [{ type: "hotspot", title: "x", target: "a.py", severity: "high", score: 1 }],
+ } as unknown as OverviewSummaryResponse}
+ routes={{ base: "/r" }}
+ slots={{
+ ask: <p>ASK</p>,
+ actions: <p>DO NEXT</p>,
+ wins: <p>WINS</p>,
+ beforeExplore: <p>PUBLISH</p>,
+ }}
+ />,
+ );
+ const text = container.textContent ?? "";
+ const order = ["ASK", "Explore this codebase", "DO NEXT", "WINS", "PUBLISH", "Everything we found"].map(
+ (s) => text.indexOf(s),
+ );
+ expect(order.every((i) => i >= 0)).toBe(true);
+ expect([...order].sort((a, b) => a - b)).toEqual(order);
+ });
+
+ it("gives each main door a live figure read through its page's basis", () => {
+ const withCounts = {
+ ...summary(),
+ explore: {
+ decisions: { total: 12, accepted: 7, candidates: 4, needs_review: 1 },
+ refactoring: { opportunities_total: 9, files_total: 9 },
+ ownership: { sole_owned_files: 41 },
+ security: { total: 10, source: 1, source_high: 1, elsewhere: 9 },
+ coverage: { line_coverage_pct: 81.25, ingested_at: null },
+ },
+ } as unknown as OverviewSummaryResponse;
+ render(<OverviewBody summary={withCounts} routes={{ base: "/r" }} />);
+ const map = screen.getByRole("link", { name: /Code health map/ });
+ expect(map).toHaveAttribute("href", "/r/code-health");
+ expect(map).toHaveTextContent("1,059");
+ expect(screen.getByRole("link", { name: /^Ownership/ })).toHaveTextContent("41sole-owned files");
+ expect(screen.getByRole("link", { name: /^Decisions/ })).toHaveTextContent(
+ "12recorded, of which 7 accepted and 4 awaiting review",
+ );
+ expect(screen.getByRole("link", { name: /^Refactoring/ })).toHaveTextContent("9open opportunities");
+ expect(screen.getByRole("link", { name: /^Tests/ })).toHaveTextContent("81.3%line coverage");
+ // Docs and Commits are further doors now, once each.
+ expect(screen.getAllByRole("link", { name: /^Docs/ })).toHaveLength(1);
+ expect(screen.getByRole("link", { name: "Commits" })).toHaveAttribute("href", "/r/commits");
+ expect(screen.getAllByRole("link", { name: /^Decisions/ })).toHaveLength(1);
+ });
+
+ it("offers no command where the server cannot say whether a report exists", () => {
+ render(<OverviewBody summary={summary()} routes={{ base: "/r" }} />);
+ expect(screen.getByRole("link", { name: /^Tests/ })).toHaveTextContent("Coverage and the tests");
+ expect(screen.queryByText("repowise coverage add")).toBeNull();
+ });
+
+ it("turns the Tests card into the ingest command when no report exists", () => {
+ const noReport = {
+ ...summary(),
+ explore: { decisions: null, refactoring: null, ownership: null, security: null, coverage: null },
+ } as unknown as OverviewSummaryResponse;
+ render(<OverviewBody summary={noReport} routes={{ base: "/r" }} />);
+ expect(screen.getByRole("link", { name: /^Tests/ })).toHaveTextContent("No coverage report yet");
+ expect(screen.getByText("repowise coverage add")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Copy the command" })).toBeInTheDocument();
+ });
+});
+
+describe("inventoryRows", () => {
+ it("counts each area on the same basis as its card and page", () => {
+ const rows = inventoryRows({
+ ...summary(),
+ health: { ...summary().health, finding_counts: { inventory: 321 } },
+ attention_summary: {
+ total: 99,
+ by_source: {},
+ areas: ["health", "security", "refactoring", "decisions", "ownership", "doc_drift"].map((key) => ({
+ key,
+ total: 5,
+ severity: "low",
+ detail: "server detail",
+ lead: null,
+ })),
+ },
+ explore: {
+ decisions: { total: 12, accepted: 7, candidates: 4, needs_review: 1 },
+ refactoring: { opportunities_total: 9, files_total: 9 },
+ ownership: { sole_owned_files: 41 },
+ security: { total: 10, source: 1, source_high: 1, elsewhere: 9 },
+ coverage: null,
+ },
+ } as unknown as OverviewSummaryResponse);
+ expect(rows.map((r) => [r.key, r.total, r.unit ?? null, r.detail])).toEqual([
+ ["health", 321, "open findings", "server detail"],
+ ["security", 1, "in shipped source", "9 more in tests and docs"],
+ ["refactoring", 9, "open opportunities", "server detail"],
+ ["decisions", 5, "to review", "4 awaiting review, 1 drifting from the code"],
+ ["ownership", 41, "sole-owned files", "One author, no second reader"],
+ ["doc_drift", 5, null, "server detail"],
+ ]);
+ });
+});
+
+describe("AttentionAreas", () => {
+ it("shows the worst item's severity once, as a dot and a word, with no hidden copy", () => {
+ render(
+ <AttentionAreas
+ prefix="/r"
+ areas={[
+ {
+ key: "refactoring",
+ total: 9,
+ unit: "open opportunities",
+ severity: "low",
+ detail: "",
+ lead: { title: "Split parse()", description: "+1.2 health", type: "refactoring", severity: "low" },
+ },
+ ]}
+ />,
+ );
+ const row = screen.getByRole("link", { name: /Refactoring/ });
+ expect(row).toHaveTextContent("9 open opportunities");
+ expect(row.textContent!.match(/Low/g)).toHaveLength(1);
+ expect(row.textContent).not.toMatch(/worst item is/);
+ });
+});
+
+describe("AttentionAreas paths", () => {
+ it("names a lead that is a path by its file first", () => {
+ render(
+ <AttentionAreas
+ prefix="/r"
+ areas={[
+ {
+ key: "health",
+ total: 3,
+ severity: "high",
+ detail: "",
+ lead: {
+ title: "packages/core/src/deep/engine.py",
+ target_id: "packages/core/src/deep/engine.py",
+ description: "3 findings",
+ type: "health_finding",
+ severity: "high",
+ },
+ },
+ ]}
+ />,
+ );
+ expect(screen.getByText("engine.py")).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/security/security.test.tsx b/packages/ui/__tests__/security/security.test.tsx
index fdf3f3419..695c16c33 100644
--- a/packages/ui/__tests__/security/security.test.tsx
+++ b/packages/ui/__tests__/security/security.test.tsx
@@ -8,14 +8,17 @@ import { FindingsByDirectory as FromBarrel } from "@repowise-dev/ui/security";
import {
SecurityPosture,
countSecurityFindings,
- securityPathClass,
+ postureCountsFromSummary,
} from "../../src/security/posture.js";
let nextId = 1;
function finding(file_path: string, severity: string, kind = "eval_call"): SecurityFinding {
+ const top = file_path.split("/")[0];
return {
id: nextId++,
file_path,
+ // The server's class; these fixtures sit where the name says.
+ path_class: top === "tests" ? "test" : top === "docs" ? "docs" : "source",
kind,
severity,
snippet: "eval(x)",
@@ -33,14 +36,21 @@ const FINDINGS = [
finding("src/app/util.py", "med"),
];
-describe("securityPathClass", () => {
- it("separates shipped source from tests and docs", () => {
- expect(securityPathClass("src/app/server.py")).toBe("source");
- expect(securityPathClass("packages/ui/__tests__/a.test.tsx")).toBe("test");
- expect(securityPathClass("pkg/foo_test.go")).toBe("test");
- expect(securityPathClass("test_login.py")).toBe("test");
- expect(securityPathClass("docs/guide/index.html")).toBe("docs");
- expect(securityPathClass("CHANGELOG.md")).toBe("docs");
+describe("postureCountsFromSummary", () => {
+ it("reads the server's split over every finding", () => {
+ expect(
+ postureCountsFromSummary({
+ scanned_at: null,
+ total: 10,
+ class_counts: { source: 1, test: 6, docs: 3 },
+ source_high: 1,
+ }),
+ ).toEqual({ total: 10, source: 1, elsewhere: 9, sourceHigh: 1 });
+ });
+
+ it("is null for a server that sends no split", () => {
+ expect(postureCountsFromSummary({ scanned_at: null })).toBeNull();
+ expect(postureCountsFromSummary(null)).toBeNull();
});
});
@@ -51,9 +61,6 @@ describe("countSecurityFindings", () => {
source: 2,
elsewhere: 2,
sourceHigh: 1,
- high: 1,
- med: 2,
- low: 1,
});
});
});
@@ -69,6 +76,19 @@ describe("SecurityPosture", () => {
expect(screen.getByText("Scanned 3 days ago.")).toBeInTheDocument();
});
+ it("prefers the server's counts, which are never capped", () => {
+ render(
+ <SecurityPosture
+ counts={{ total: 10, source: 1, elsewhere: 9, sourceHigh: 1 }}
+ findings={FINDINGS}
+ scannedAgo="now"
+ capped
+ />,
+ );
+ expect(screen.getByText("of 10 findings")).toBeInTheDocument();
+ expect(screen.getByText(/1 place in shipped source, 1 of them high\. 9 more are in tests and docs/)).toBeInTheDocument();
+ });
+
it("never implies freshness it does not have", () => {
render(<SecurityPosture findings={FINDINGS} scannedAgo={null} capped />);
expect(screen.getByText("Scan time not recorded.")).toBeInTheDocument();
diff --git a/packages/ui/__tests__/stats/stats-report.test.tsx b/packages/ui/__tests__/stats/stats-report.test.tsx
index 738627d59..422d20d32 100644
--- a/packages/ui/__tests__/stats/stats-report.test.tsx
+++ b/packages/ui/__tests__/stats/stats-report.test.tsx
@@ -73,6 +73,11 @@ describe("StatsReport", () => {
expect(screen.getByText("70 lines of tests")).toBeInTheDocument();
});
+ it("states the index size when the server measured it", () => {
+ render(<StatsReport data={{ ...makeData(), index_storage_bytes: 5 * 1024 * 1024 }} />);
+ expect(document.body.textContent).toMatch(/Repowise index .* takes 5(\.0)? MB on disk/);
+ });
+
it("counts merge commits apart from the commit total", () => {
const data = makeData();
render(<StatsReport data={{ ...data, origin: { ...data.origin, total_merge_commits: 312 } }} />);
diff --git a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx
index 23bb946f3..c49573df7 100644
--- a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx
+++ b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx
@@ -113,4 +113,21 @@ describe("WorkspaceNextActions", () => {
expect(await within(dialog).findByText("Prompt from core")).toBeInTheDocument();
expect(loadPrompt).toHaveBeenCalledWith("f1", expect.objectContaining({ id: "y" }), expect.any(String));
});
+
+ it("gives each repository's rows the agent prompt, loaded from that repository", async () => {
+ const loadPrompt = vi.fn().mockResolvedValue("Row prompt");
+ render(
+ <WorkspaceNextActions
+ data={data}
+ hrefFor={() => null}
+ repoHref={(id) => `/repos/${id}/overview`}
+ contractsHref="/workspace/contracts"
+ loadPrompt={loadPrompt}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /Copy prompt for your agent: Clean up/ }));
+ const dialog = await screen.findByRole("dialog");
+ expect(await within(dialog).findByText("Row prompt")).toBeInTheDocument();
+ expect(loadPrompt).toHaveBeenCalledWith("f1", expect.objectContaining({ id: "y" }), expect.any(String));
+ });
});
diff --git a/packages/ui/src/overview/attention-areas.tsx b/packages/ui/src/overview/attention-areas.tsx
index 5fdfda385..b1daa7ac5 100644
--- a/packages/ui/src/overview/attention-areas.tsx
+++ b/packages/ui/src/overview/attention-areas.tsx
@@ -1,23 +1,11 @@
import * as React from "react";
import type { OverviewAttentionAreaRow } from "@repowise-dev/types/overview";
-import {
- attentionSourceHref,
- attentionSourceLabel,
- type AttentionSeverity,
-} from "../dashboard/attention-href";
+import { attentionSourceHref, attentionSourceLabel } from "../dashboard/attention-href";
import { biomarkerLabel } from "../health/biomarker-glossary";
+import { SeverityMark } from "../health/severity-mark";
+import { FilePath } from "../shared/file-path";
import { formatNumber } from "../lib/format";
-const SEVERITY_COLOR: Record<AttentionSeverity, string> = {
- // Critical and high share the one red. The palette has a single "this is
- // bad" hue and a second would spend the distinction on nothing: the band is
- // already named in the screen-reader text and carried by the row order.
- critical: "var(--color-error)",
- high: "var(--color-error)",
- medium: "var(--color-warning)",
- low: "var(--color-text-tertiary)",
-};
-
/** What to call the lead item's kind. Health findings name their biomarker. */
function leadKind(lead: NonNullable<OverviewAttentionAreaRow["lead"]>): string {
if (lead.type === "health_finding" && lead.subtype) return biomarkerLabel(lead.subtype);
@@ -43,14 +31,16 @@ function leadKind(lead: NonNullable<OverviewAttentionAreaRow["lead"]>): string {
*
* Fixed order, never re-sorted by severity. These are stable subjects, and a
* list whose rows move between visits cannot be scanned by position — you have
- * to re-read it every time. Severity is carried by the dot and by the lead.
+ * to re-read it every time. The worst item's severity sits beside the lead as
+ * a dot and a word, read once by sight and once by a screen reader.
*/
export function AttentionAreas({
areas,
prefix,
LinkComponent,
}: {
- areas: OverviewAttentionAreaRow[];
+ /** `unit` names what the count is in, e.g. "open findings". */
+ areas: InventoryArea[];
prefix: string;
LinkComponent?: React.ElementType | undefined;
}) {
@@ -64,54 +54,25 @@ export function AttentionAreas({
return (
<ul className="m-0 list-none divide-y divide-[var(--color-border-default)] border-t border-[var(--color-border-default)] p-0">
{areas.map((area) => {
- const kind = area.lead ? leadKind(area.lead) : "";
return (
<li key={area.key}>
<A
href={attentionSourceHref(area.key, prefix)}
className="group flex flex-col gap-1 py-3 text-xs no-underline sm:flex-row sm:items-baseline sm:gap-4"
>
- <span className="flex shrink-0 items-center gap-2 sm:w-40">
- <span
- aria-hidden
- className="h-1.5 w-1.5 shrink-0 rounded-full"
- style={{ background: SEVERITY_COLOR[area.severity] }}
- />
- {/* The dot is nothing at all to a screen reader, and to anyone
- who cannot separate the hues. The text equivalent goes here
- rather than into a `title`, which assistive tech reads
- inconsistently. */}
- <span className="sr-only">worst item is {area.severity} severity. </span>
- <span className="font-medium text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)]">
- {attentionSourceLabel(area.key)}
- </span>
+ <span className="shrink-0 font-medium text-[var(--color-text-primary)] group-hover:text-[var(--color-accent-primary)] sm:w-32">
+ {attentionSourceLabel(area.key)}
</span>
- <span className="shrink-0 font-mono tabular-nums text-[var(--color-text-secondary)] sm:w-24">
- {formatNumber(area.total)}
+ <span className="shrink-0 text-[var(--color-text-tertiary)] sm:w-48">
+ <span className="font-mono tabular-nums text-[var(--color-text-secondary)]">
+ {formatNumber(area.total)}
+ </span>
+ {area.unit && ` ${area.unit}`}
</span>
<span className="min-w-0 flex-1 text-[var(--color-text-tertiary)]">
- {area.lead ? (
- <>
- {kind && <span className="text-[var(--color-text-secondary)]">{kind} · </span>}
- <span className="text-[var(--color-text-secondary)]">{area.lead.title}</span>
- <span className="mt-0.5 block truncate text-[11px] [text-wrap:pretty]">
- {/* The composition wins the second line where there is
- one: knowing that most of a security count is git
- history rather than the working tree changes what the
- number means, and changes it more than one more
- example would. */}
- {area.detail || area.lead.description}
- </span>
- </>
- ) : (
- area.detail && (
- <span className="block truncate text-[11px] [text-wrap:pretty]">
- {area.detail}
- </span>
- )
- )}
+ <AreaLead area={area} />
</span>
<span
@@ -127,3 +88,38 @@ export function AttentionAreas({
</ul>
);
}
+
+type InventoryArea = OverviewAttentionAreaRow & { unit?: string };
+
+/** The worst item in an area, its severity, and what the count is made of. */
+function AreaLead({ area }: { area: InventoryArea }) {
+ const lead = area.lead;
+ if (!lead) {
+ return area.detail ? (
+ <span className="block truncate text-[11px] [text-wrap:pretty]">{area.detail}</span>
+ ) : null;
+ }
+ const kind = leadKind(lead);
+ const isPath = !!lead.target_id && lead.title === lead.target_id;
+ return (
+ <>
+ <SeverityMark severity={area.severity} className="mr-2" />
+ {kind && <span className="text-[var(--color-text-secondary)]">{kind} · </span>}
+ {isPath ? (
+ <FilePath
+ path={lead.title}
+ fold
+ className="min-w-0 align-baseline text-[var(--color-text-secondary)]"
+ />
+ ) : (
+ <span className="text-[var(--color-text-secondary)]">{lead.title}</span>
+ )}
+ {/* The composition wins the second line where there is one: knowing that
+ most security matches sit in tests and docs changes what the number
+ means more than one more example would. */}
+ <span className="mt-0.5 block truncate text-[11px] [text-wrap:pretty]">
+ {area.detail || lead.description}
+ </span>
+ </>
+ );
+}
diff --git a/packages/ui/src/overview/attention-section.tsx b/packages/ui/src/overview/attention-section.tsx
new file mode 100644
index 000000000..dddf29968
--- /dev/null
+++ b/packages/ui/src/overview/attention-section.tsx
@@ -0,0 +1,80 @@
+import * as React from "react";
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import { getDefaultHref } from "../dashboard/attention-href";
+import { formatNumber } from "../lib/format";
+import { AttentionAreas } from "./attention-areas";
+import { AttentionRows } from "./attention-rows";
+import { inventoryRows } from "./overview-model";
+import { OverviewSection } from "./section";
+
+/** Ranked rows shown when the server predates the area rollup. */
+const ATTENTION_ROWS = 6;
+
+export interface AttentionSectionProps {
+ summary: OverviewSummaryResponse;
+ /** Link prefix for this host. */
+ base: string;
+ /** Fold it as the inventory behind "Do next" instead of leading with it. */
+ inventory?: boolean;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+/** Areas count different things, so the header counts areas, not their sum. */
+function scopeLabel(summary: OverviewSummaryResponse, areaCount: number): string {
+ if (areaCount > 0) return `${formatNumber(areaCount)} ${areaCount === 1 ? "area" : "areas"}`;
+ return `${formatNumber(summary.attention_summary?.total ?? summary.attention.length)} open`;
+}
+
+/**
+ * Every detector's open findings by area of work. Leads the page on a host
+ * without "Do next"; folds into an inventory below it otherwise. Renders
+ * nothing when nothing is open.
+ */
+export function AttentionSection({
+ summary,
+ base,
+ inventory = false,
+ LinkComponent,
+}: AttentionSectionProps) {
+ // Counts read from the same basis as the explore cards and the pages they
+ // link to. The areas count different things (findings, files,
+ // opportunities), so the header counts areas rather than summing them.
+ const areas = inventoryRows(summary);
+ const hasAttention = areas.length > 0 || summary.attention.length > 0;
+ const scope = scopeLabel(summary, areas.length);
+
+ if (!hasAttention) return null;
+ return (
+ <OverviewSection
+ title={inventory ? "Everything we found" : "Needs attention"}
+ description={
+ inventory
+ ? "Every detector's open count by area. The actions above are the part worth doing."
+ : "Each area of work, led by the worst thing in it."
+ }
+ collapsible={inventory}
+ defaultOpen={!inventory}
+ hint={inventory ? scope : undefined}
+ // No section link: these span seven pages, so there is no single
+ // destination that holds "all of them", and a count linking to one
+ // of them would be a lie about where the rest live.
+ action={
+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ {scope}
+ </span>
+ }
+ >
+ {areas.length > 0 ? (
+ <AttentionAreas areas={areas} prefix={base} LinkComponent={LinkComponent} />
+ ) : (
+ // A server predating the area rollup still sends ranked items, and
+ // rendering those is strictly better than rendering nothing.
+ <AttentionRows
+ items={summary.attention.slice(0, ATTENTION_ROWS)}
+ hrefFor={(item) => getDefaultHref(item, base)}
+ LinkComponent={LinkComponent}
+ />
+ )}
+ </OverviewSection>
+ );
+}
diff --git a/packages/ui/src/overview/explore-cards.tsx b/packages/ui/src/overview/explore-cards.tsx
new file mode 100644
index 000000000..b6b3c4fc5
--- /dev/null
+++ b/packages/ui/src/overview/explore-cards.tsx
@@ -0,0 +1,98 @@
+import * as React from "react";
+import { CopyLine } from "../settings/settings-primitives";
+import type { ExploreEntry } from "./explore-list";
+
+export interface ExploreCard {
+ key: string;
+ label: string;
+ /** One live figure. Omitted when the payload has none for this door. */
+ value?: string;
+ /** What the figure counts, or what the page holds when there is no figure. */
+ caption: string;
+ /** A command that fills the page, shown with a copy button. */
+ command?: string;
+ href: string;
+}
+
+export interface ExploreCardsProps {
+ cards: ExploreCard[];
+ /** Further doors, shown as one quiet line of links under the cards. */
+ more?: ExploreEntry[];
+ /** Label before the further doors. */
+ moreLabel?: string;
+ /** What a card's command is, for its copy button's accessible name. */
+ commandLabel?: string;
+ LinkComponent?: React.ElementType | undefined;
+}
+
+/**
+ * The main pages as a grid of doors, each carrying one figure from the data
+ * the page already loaded. Hairline outlines on the page ground, no fill: the
+ * card's link fills it, and hover strengthens the hairline rather than lifting
+ * it. A card with a command keeps the copy button outside the link.
+ */
+export function ExploreCards({
+ cards,
+ more = [],
+ moreLabel = "Also",
+ commandLabel = "the command",
+ LinkComponent,
+}: ExploreCardsProps) {
+ const A = LinkComponent ?? "a";
+ if (cards.length === 0 && more.length === 0) return null;
+ return (
+ <div className="flex flex-col gap-3">
+ <ul className="m-0 grid list-none grid-cols-1 gap-3 p-0 sm:grid-cols-2 lg:grid-cols-3">
+ {cards.map((c) => (
+ <li
+ key={c.key}
+ className="group flex min-w-0 flex-col rounded-lg border border-[var(--color-border-default)] bg-transparent transition-colors hover:border-[var(--color-border-hover)] focus-within:border-[var(--color-border-hover)]"
+ >
+ <A
+ href={c.href}
+ className="flex flex-1 flex-col gap-1.5 rounded-lg px-5 py-4 no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <span className="flex items-center justify-between gap-2 text-xs font-medium text-[var(--color-text-secondary)]">
+ {c.label}
+ <span
+ aria-hidden
+ className="text-[var(--color-text-tertiary)] transition-transform group-hover:translate-x-0.5 group-has-[a:focus-visible]:translate-x-0.5"
+ >
+ →
+ </span>
+ </span>
+ {c.value && (
+ <span className="font-mono text-[22px] font-semibold leading-tight tabular-nums text-[var(--color-text-primary)]">
+ {c.value}
+ </span>
+ )}
+ <span className="text-xs text-[var(--color-text-tertiary)] [text-wrap:pretty]">
+ {c.caption}
+ </span>
+ </A>
+ {c.command && (
+ <div className="px-5 pb-4">
+ <CopyLine value={c.command} copyLabel={commandLabel} />
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ {more.length > 0 && (
+ <p className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
+ <span>{moreLabel}</span>
+ {more.map((e) => (
+ <A
+ key={e.key}
+ href={e.href}
+ title={e.description}
+ className="font-medium text-[var(--color-accent-primary)] hover:underline"
+ >
+ {e.label}
+ </A>
+ ))}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/overview/health-lede.tsx b/packages/ui/src/overview/health-lede.tsx
index 6a454364a..a08d131b7 100644
--- a/packages/ui/src/overview/health-lede.tsx
+++ b/packages/ui/src/overview/health-lede.tsx
@@ -3,125 +3,113 @@ import { healthBand } from "../health/tokens";
import { formatScore } from "@repowise-dev/types/health";
import { LedeLink, PageLede } from "../shared/page-lede";
+export interface HealthLedeCopy {
+ label: string;
+ unit: string;
+ reportLink: string;
+ /** Shown before the first health run. */
+ empty: string;
+ /** Methodology behind the info tip beside the label. `counts` is null when
+ * the index has no hotspots. */
+ hint: (counts: { hotspots: string; files: string } | null) => string;
+ /** The one reading under the figure. `figure` is the coloured hotspot score;
+ * `holdsUp` is true when hotspots score at or above the whole codebase. */
+ hotspotReading: (figure: React.ReactNode, holdsUp: boolean) => React.ReactNode;
+}
+
+export const HEALTH_LEDE_COPY: HealthLedeCopy = {
+ label: "Code health",
+ unit: "out of 10",
+ reportLink: "Full health report",
+ empty:
+ "Health scores land with the first index: complexity, duplication, coverage, churn and ownership across every file.",
+ hint: (counts) =>
+ `Average code health of every scored file, from 1 to 10.${
+ counts
+ ? ` Hotspots are the ${counts.hotspots} of ${counts.files} files that git history changes and fixes most.`
+ : ""
+ }`,
+ hotspotReading: (figure, holdsUp) =>
+ holdsUp ? (
+ <>Hotspots average {figure}, as healthy as the rest of the code.</>
+ ) : (
+ <>Hotspots average {figure}, the place fixes pay off most.</>
+ ),
+};
+
export interface HealthLedeProps {
/** Code-health headline, 1–10. Higher is better. Null before the first run. */
score: number | null;
+ /** @deprecated Not shown on Overview; Code Health owns it. */
maintainability?: number | null | undefined;
- /** Static performance score, 1–10. Higher is better, like the other two. */
+ /** @deprecated Not shown on Overview; Code Health owns it. */
performance?: number | null | undefined;
- /** Health of the highest-churn files. The interesting number, usually. */
+ /** Health of the highest-churn files. */
hotspotHealth?: number | null | undefined;
hotspotCount?: number | undefined;
fileCount?: number | undefined;
/** "Full health report →" target. */
href: string;
LinkComponent?: React.ElementType | undefined;
+ copy?: Partial<HealthLedeCopy> | undefined;
}
/**
- * Code health as a headline number and a plain sentence, not a card of tiles.
- *
- * The figure alone is not readable: "329 risks · 9.9/10" looks like a
- * contradiction until something says the score is a bounded summary of the
- * findings rather than a count of them. So the prose is load-bearing, not
- * decoration — it is the part that makes the number mean anything, and it is
- * why the public repo landing page reads calm while showing the same data.
- *
- * Health keeps the largest number on the page because it is the product's
- * moat. It does not get the whole top of the page: the column beside it
- * carries the other reasons people open Overview.
+ * Code health as one figure, its band, and one reading that points at where
+ * work pays off. How the score is built sits behind the info tip.
*/
export function HealthLede({
score,
- maintainability,
- performance,
hotspotHealth,
hotspotCount = 0,
fileCount = 0,
href,
LinkComponent,
+ copy,
}: HealthLedeProps) {
+ const c = { ...HEALTH_LEDE_COPY, ...copy };
if (score == null) {
return (
<div className="flex flex-col gap-2">
<p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Code health
- </p>
- <p className="max-w-[54ch] text-sm text-[var(--color-text-secondary)]">
- Health scores land with the first index: complexity, duplication, coverage,
- churn and ownership across every file.
+ {c.label}
</p>
+ <p className="max-w-[54ch] text-sm text-[var(--color-text-secondary)]">{c.empty}</p>
</div>
);
}
const band = healthBand(score);
- const hot = hotspotHealth != null ? healthBand(hotspotHealth) : null;
-
- // Assembled rather than interpolated inline: a repo can have measured one
- // pillar and not the other, and the naive version produced "Maintainability
- // scores 8.6. The three are scored separately" (there were two) or a sentence
- // starting lowercase when only performance was present.
- // "static performance risk 9.7" read as an alarm and meant the opposite: the
- // figure is a score on the same 1-10 ladder as the other two, where 9.7 is
- // close to clean. The noun has to agree with the direction of the number, so
- // it is named like its siblings and the word "risk" is left to the findings
- // count on the health page, where more genuinely is worse.
- const pillars: string[] = [];
- if (maintainability != null) pillars.push(`maintainability ${formatScore(maintainability)}`);
- if (performance != null) pillars.push(`static performance ${formatScore(performance)}`);
- const pillarSentence =
- pillars.length === 0
- ? null
- : `It also scores ${pillars.join(" and ")} out of 10. ${
- pillars.length === 1
- ? "The two are scored separately and never blended into one number."
- : "The three are scored separately and never blended into one number."
- }`;
+ const hot = hotspotCount > 0 && hotspotHealth != null ? hotspotHealth : null;
return (
<PageLede
- label="Code health"
+ label={c.label}
+ labelHint={c.hint(
+ hot != null && fileCount > 0
+ ? { hotspots: hotspotCount.toLocaleString(), files: fileCount.toLocaleString() }
+ : null,
+ )}
value={formatScore(score)}
valueColor={band.color}
- unit="out of 10"
+ unit={c.unit}
band={band}
action={
<LedeLink href={href} LinkComponent={LinkComponent}>
- Full health report
+ {c.reportLink}
</LedeLink>
}
>
- <p>
- This codebase scores{" "}
- <strong className="font-semibold text-[var(--color-text-primary)]">
- {formatScore(score)} out of 10
- </strong>{" "}
- for code health, which we rate {band.label.toLowerCase()}.
- {pillarSentence && ` ${pillarSentence}`}
- {/* This used to open "The files you change most are the weak spot",
- which reads as an indictment of something every codebase does. Hot
- files scoring below the average is the premise the whole product
- rests on, not a failure: it is why ranking by git history finds
- defects that reading the code alone does not. Same two figures,
- stated as the finding they are, and pointed at the files rather
- than at the reader. */}
- {hotspotCount > 0 && hot && (
- <>
- {" "}
- Risk is concentrated, as it usually is:{" "}
- <strong className="font-semibold text-[var(--color-text-primary)]">
- {hotspotCount.toLocaleString()}
- {fileCount > 0 ? ` of ${fileCount.toLocaleString()}` : ""} files
- </strong>{" "}
- are git hotspots, and they average{" "}
- <strong className="font-semibold" style={{ color: hot.color }}>
- {formatScore(hotspotHealth!)}
- </strong>
- {" "}— which is where the fixes pay off most.
- </>
- )}
- </p>
+ {hot != null && (
+ <p>
+ {c.hotspotReading(
+ <strong className="font-semibold tabular-nums" style={{ color: healthBand(hot).color }}>
+ {formatScore(hot)}
+ </strong>,
+ hot >= score,
+ )}
+ </p>
+ )}
</PageLede>
);
}
diff --git a/packages/ui/src/overview/index.ts b/packages/ui/src/overview/index.ts
index dd8fcdeb6..fe7e7713b 100644
--- a/packages/ui/src/overview/index.ts
+++ b/packages/ui/src/overview/index.ts
@@ -44,15 +44,19 @@ export { actionHref } from "./action-href";
export { NextActions, renderActionTitle } from "./next-actions";
export type { NextActionsProps } from "./next-actions";
export { ExploreList } from "./explore-list";
+export { ExploreCards } from "./explore-cards";
+export type { ExploreCard, ExploreCardsProps } from "./explore-cards";
export type { ExploreEntry } from "./explore-list";
export { LanguageBar } from "./language-bar";
export { OverviewBody } from "./overview-body";
-export type { OverviewBodyProps, OverviewBodySlots } from "./overview-body";
+export { OVERVIEW_BODY_COPY } from "./overview-body";
+export type { OverviewBodyCopy, OverviewBodyProps, OverviewBodySlots } from "./overview-body";
export {
buildChangeStats,
buildExplore,
+ buildExploreCards,
buildLanguageDistribution,
buildReads,
buildRibbon,
diff --git a/packages/ui/src/overview/next-actions.tsx b/packages/ui/src/overview/next-actions.tsx
index 6c85b2ce4..ad8e13c10 100644
--- a/packages/ui/src/overview/next-actions.tsx
+++ b/packages/ui/src/overview/next-actions.tsx
@@ -1,6 +1,6 @@
"use client";
-import { Fragment, useMemo, useState, type ElementType, type ReactNode } from "react";
+import { Fragment, useCallback, useMemo, useState, type ElementType, type ReactNode } from "react";
import { BellOff, Check, PanelRight, X } from "lucide-react";
import { toast } from "sonner";
import {
@@ -13,7 +13,10 @@ import {
type NextAction,
} from "@repowise-dev/types/actions";
+import { useAiPromptAction } from "../health/ai-prompt-action";
+import type { AiPromptFlavor } from "../health/ai-prompt-builder";
import { EFFORT_LABEL } from "../health/labels";
+import { RowPromptAction } from "../health/row-prompt-action";
import { SeverityMark } from "../health/severity-mark";
import { CLICKABLE_ROW_CLS, clickableRowProps } from "../shared/responsive-table";
import { RowOverflow } from "../shared/row-overflow";
@@ -52,6 +55,29 @@ export interface NextActionsProps {
LinkComponent?: ElementType | undefined;
}
+type ActionPromptLoader = (action: NextAction, flavor: AiPromptFlavor) => Promise<string>;
+
+/**
+ * The row-level "Copy prompt for your agent": opens the shared prompt modal on
+ * one action's prompt. Render `promptModal` once beside the rows.
+ */
+export function useActionPrompt(): {
+ openActionPrompt: (action: NextAction, load: ActionPromptLoader) => void;
+ promptModal: ReactNode;
+} {
+ const { openPrompt, promptModal } = useAiPromptAction();
+ const openActionPrompt = useCallback(
+ (action: NextAction, load: ActionPromptLoader) =>
+ openPrompt({
+ title: action.title.replace(/`/g, ""),
+ filePath: action.target.path || null,
+ promptSource: (flavor) => load(action, flavor),
+ }),
+ [openPrompt],
+ );
+ return { openActionPrompt, promptModal };
+}
+
/** Split a title on backticks so paths and symbols set in mono. */
export function renderActionTitle(title: string): ReactNode {
return title.split("`").map((part, i) =>
@@ -133,6 +159,7 @@ export function NextActions({
// knows its time frame once a re-read drops the row.
const [answered, setAnswered] = useState<ReadonlyMap<string, NextAction>>(new Map());
const [opened, setOpened] = useState<NextAction | null>(null);
+ const { openActionPrompt, promptModal } = useActionPrompt();
const rows = useMemo(
() => (data ? data.horizons[horizon].actions.filter((a) => !answered.has(a.id)) : []),
@@ -189,7 +216,7 @@ export function NextActions({
return (
<OverviewSection
- title="Do next"
+ title={defaultOpen ? "Do next" : `Do next · ${work(horizon).toLocaleString("en-US")}`}
description={data.summary?.[horizon] ?? fallbackSummary(data, horizon)}
// A folded section has no header action slot, so the time frame sits
// under the summary, above the list it filters, and the toggle carries
@@ -197,7 +224,6 @@ export function NextActions({
action={defaultOpen ? timeFrame : undefined}
collapsible={!defaultOpen}
defaultOpen={defaultOpen}
- hint={defaultOpen ? undefined : `${work(horizon).toLocaleString("en-US")} suggested`}
>
{!defaultOpen && timeFrame}
{shown.length === 0 && [...answered.values()].some((a) => a.horizons.includes(horizon)) ? (
@@ -220,6 +246,7 @@ export function NextActions({
action={action}
selected={opened?.id === action.id}
onOpen={() => setOpened(action)}
+ onPrompt={loadPrompt ? () => openActionPrompt(action, loadPrompt) : undefined}
onAnswer={onSetState ? (state, message) => answer(action, state, message) : undefined}
/>
))}
@@ -281,6 +308,7 @@ export function NextActions({
LinkComponent={LinkComponent}
renderTitle={renderActionTitle}
/>
+ {promptModal}
</OverviewSection>
);
}
@@ -316,12 +344,15 @@ export function ActionRow({
action,
onOpen,
selected = false,
+ onPrompt,
onAnswer,
}: {
action: NextAction;
/** Open the action's drawer; the whole row is the trigger. */
onOpen: () => void;
selected?: boolean | undefined;
+ /** Open the agent prompt for this action. Omit to hide the row's prompt verb. */
+ onPrompt?: (() => void) | undefined;
onAnswer?: ((state: ActionStateValue, message: string) => void) | undefined;
}) {
const plainTitle = action.title.replace(/`/g, "");
@@ -352,7 +383,8 @@ export function ActionRow({
<li
aria-label={`Open ${plainTitle}`}
aria-current={selected ? "true" : undefined}
- className={`${CLICKABLE_ROW_CLS} group flex items-start gap-3 px-1 py-3.5 sm:gap-4 ${
+ data-selected={selected ? "true" : undefined}
+ className={`${CLICKABLE_ROW_CLS} group group/row flex items-start gap-3 px-1 py-3.5 sm:gap-4 ${
selected ? "bg-[var(--color-bg-elevated)]" : "hover:bg-[var(--color-bg-elevated)]"
}`}
{...clickableRowProps(onOpen)}
@@ -404,6 +436,7 @@ export function ActionRow({
</>
)}
</span>
+ {onPrompt && <RowPromptAction subject={plainTitle} onClick={onPrompt} />}
<RowOverflow label={`More for ${plainTitle}`} items={items} />
</div>
</li>
diff --git a/packages/ui/src/overview/overview-body.tsx b/packages/ui/src/overview/overview-body.tsx
index c463dfd55..55d0616d8 100644
--- a/packages/ui/src/overview/overview-body.tsx
+++ b/packages/ui/src/overview/overview-body.tsx
@@ -1,24 +1,19 @@
import * as React from "react";
import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
-import { getDefaultHref } from "../dashboard/attention-href";
import { formatNumber } from "../lib/format";
import { fileEntityPath } from "../shared/entity";
import { PageFrame } from "../shared/page-shell";
-import { StatRibbon } from "../stats/stat-ribbon";
-import { AttentionAreas } from "./attention-areas";
-import { AttentionRows } from "./attention-rows";
-import { CommitRows, DecisionRows, type CommitRow } from "./activity-lists";
+import { AttentionSection } from "./attention-section";
+import type { CommitRow } from "./activity-lists";
import { ChangeLine } from "./change-line";
-import { ExploreList } from "./explore-list";
+import { ExploreCards } from "./explore-cards";
import { HealthLede } from "./health-lede";
import { HotspotTable } from "./hotspot-table";
-import { LanguageBar } from "./language-bar";
import {
buildChangeStats,
buildExplore,
- buildLanguageDistribution,
+ buildExploreCards,
buildReads,
- buildRibbon,
previousSnapshotAt,
resolveOverviewRoutes,
type OverviewRoutes,
@@ -26,9 +21,7 @@ import {
import { ReadsColumn } from "./reads-column";
import { OverviewSection, SectionLink } from "./section";
-/** How many rows each list section shows before deferring to its own page. */
-const ATTENTION_ROWS = 6;
-const DECISION_ROWS = 6;
+/** Hotspot rows shown before deferring to Code Health. */
const HOTSPOT_ROWS = 5;
export interface OverviewBodySlots {
@@ -38,32 +31,45 @@ export interface OverviewBodySlots {
header?: React.ReactNode;
/** Under the reads column. Hosted puts its MCP connect card here. */
afterReads?: React.ReactNode;
- /** A section between Composition and Explore. Hosted's index-coverage
- * panel. */
+ /** A section after Do next and recent wins. Hosted's index-coverage
+ * panel, OSS's publish panel. */
beforeExplore?: React.ReactNode;
- /** Contents of the "Ask this codebase" section. Omitted where the host
- * routes to a chat page from Explore instead, and the section then does not
- * render at all rather than rendering empty. */
+ /** The ask box, full width under the health lede. Omitted where the host
+ * routes to a chat page from Explore instead. */
ask?: React.ReactNode;
/** The "Do next" list, bound to the host's routes and write path. When
* present it leads the page and the per-detector areas fold into an
* inventory lower down; when absent (a host not yet serving actions) the
* areas keep their old place. */
actions?: React.ReactNode;
+ /** What got better recently, directly under "Do next". Omitted, nothing
+ * renders in its place. */
+ wins?: React.ReactNode;
}
export interface OverviewBodyProps {
summary: OverviewSummaryResponse;
routes: OverviewRoutes;
- /** Recent commits, already fetched and bounded by the host. */
+ /** @deprecated Ignored; recent commits live on the Commits page. */
commits?: CommitRow[];
- /** Total lines of code. The two hosts source this differently, so it is a
- * prop rather than a payload read. */
+ /** @deprecated Ignored; size figures live on the Stats page. */
totalNloc?: number | null;
LinkComponent?: React.ElementType;
slots?: OverviewBodySlots;
+ /** Section titles and labels. English by default. */
+ copy?: Partial<OverviewBodyCopy>;
}
+export interface OverviewBodyCopy {
+ exploreTitle: string;
+ exploreMore: string;
+}
+
+export const OVERVIEW_BODY_COPY: OverviewBodyCopy = {
+ exploreTitle: "Explore this codebase",
+ exploreMore: "Also",
+};
+
/**
* The repo Overview, once its data has arrived.
*
@@ -75,75 +81,31 @@ export interface OverviewBodyProps {
* token), so anything that fetches cannot be shared, and anything that does
* not fetch can.
*
- * Section order answers three questions in sequence: what state is this
- * repository in, what needs me, and where do I go. "Needs attention" sits
- * directly under the health hero rather than fourth, because the page is
- * mostly opened by someone who was here last week and wants the delta, not by
- * a stranger who wants the tour.
+ * Short and action-first: the health reading, the ask box, doors into the
+ * pages that own each subject, then what to do now and what got better. Anything
+ * a deeper page already shows in full (commit lists, decisions, size and
+ * language figures) is a link from Explore rather than a copy here.
*
- * When the host supplies actions, "Do next" takes that place: a few things to
- * do, each with its reason, instead of a count per detector. The per-detector
- * areas stay reachable as a folded inventory further down.
+ * When the host supplies actions, "Do next" leads and the per-detector areas
+ * fold into an inventory below it.
*/
export function OverviewBody({
summary,
routes,
- commits = [],
- totalNloc,
LinkComponent,
slots = {},
+ copy,
}: OverviewBodyProps) {
+ const c = { ...OVERVIEW_BODY_COPY, ...copy };
const resolved = resolveOverviewRoutes(routes);
const { base } = resolved;
const { stats, health } = summary;
const reads = buildReads(summary, routes);
- const ribbon = buildRibbon(summary, routes, totalNloc);
- const explore = buildExplore(summary, routes);
+ const cards = buildExploreCards(summary, routes);
+ const carded = new Set(cards.map((card) => card.key));
+ const moreDoors = buildExplore(summary, routes).filter((e) => !carded.has(e.key));
const changeStats = buildChangeStats(summary);
- const langDistribution = buildLanguageDistribution(summary);
-
- // The list is capped per source server-side, so its length is not a total.
- // Falling back to the row count on a server that predates the summary keeps
- // the old (correct-for-that-payload) behaviour rather than rendering
- // nothing.
- const attentionTotal = summary.attention_summary?.total ?? summary.attention.length;
- const areas = summary.attention_summary?.areas ?? [];
- const hasAttention = areas.length > 0 || summary.attention.length > 0;
-
- const attention = (inventory: boolean) => (
- <OverviewSection
- title={inventory ? "Everything we found" : "Needs attention"}
- description={
- inventory
- ? "Every detector's open count by area, each with its worst example. An inventory, not a to-do list: the actions above are the part worth doing."
- : "Every detector, by area of work, each leading with the worst thing in it: code health and the test-quality biomarkers, security, refactoring, documentation drift, decision records, ownership, and dead code."
- }
- collapsible={inventory}
- defaultOpen={!inventory}
- hint={inventory ? `${formatNumber(attentionTotal)} open` : undefined}
- // No section link: these span seven pages, so there is no single
- // destination that holds "all of them", and a count linking to one
- // of them would be a lie about where the rest live.
- action={
- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
- {formatNumber(attentionTotal)} open
- </span>
- }
- >
- {areas.length > 0 ? (
- <AttentionAreas areas={areas} prefix={base} LinkComponent={LinkComponent} />
- ) : (
- // A server predating the area rollup still sends ranked items, and
- // rendering those is strictly better than rendering nothing.
- <AttentionRows
- items={summary.attention.slice(0, ATTENTION_ROWS)}
- hrefFor={(item) => getDefaultHref(item, base)}
- LinkComponent={LinkComponent}
- />
- )}
- </OverviewSection>
- );
return (
<PageFrame>
@@ -151,15 +113,9 @@ export function OverviewBody({
<ChangeLine since={previousSnapshotAt(summary)} stats={changeStats} />
- {/* Health keeps the largest number and the leftmost position. The column
- beside it carries the other reasons someone opens Overview, so a
- visitor who came for docs or costs finds their figure at the same
- altitude rather than three scrolls down. */}
<div className="grid grid-cols-1 items-start gap-8 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-12">
<HealthLede
score={health.average_health}
- maintainability={health.maintainability_average}
- performance={health.performance_average}
hotspotHealth={health.hotspot_health}
hotspotCount={stats.hotspot_count}
fileCount={stats.file_count}
@@ -172,42 +128,23 @@ export function OverviewBody({
</div>
</div>
- {slots.actions ?? (hasAttention && attention(false))}
+ {slots.ask}
- <StatRibbon stats={ribbon} LinkComponent={LinkComponent} />
-
- <OverviewSection
- title="Recent activity"
- action={
- <SectionLink href={`${base}/commits`} LinkComponent={LinkComponent}>
- All commits
- </SectionLink>
- }
- >
- <div className="grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-10">
- <div className="flex min-w-0 flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Commits
- </h3>
- <CommitRows
- commits={commits}
- hrefFor={(sha) => `${base}/commits?commit=${sha}`}
- LinkComponent={LinkComponent}
- />
- </div>
- <div className="flex min-w-0 flex-col gap-2">
- <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Decisions
- </h3>
- <DecisionRows
- decisions={summary.recent_decisions.slice(0, DECISION_ROWS)}
- hrefFor={(decisionId) => `${base}/decisions/${encodeURIComponent(decisionId)}`}
- LinkComponent={LinkComponent}
- />
- </div>
- </div>
+ <OverviewSection title={c.exploreTitle}>
+ <ExploreCards
+ cards={cards}
+ more={moreDoors}
+ moreLabel={c.exploreMore}
+ LinkComponent={LinkComponent}
+ />
</OverviewSection>
+ {slots.actions ?? (
+ <AttentionSection summary={summary} base={base} LinkComponent={LinkComponent} />
+ )}
+
+ {slots.wins}
+
{/* A host without actions keeps the hotspot table: with "Do next", its
files arrive as fragile-file and bug-fix concentration actions with
the reason attached, and a second "riskiest files" list would
@@ -230,34 +167,13 @@ export function OverviewBody({
</OverviewSection>
)}
- {/* The areas, now as the inventory behind "Do next": every detector's
- count and its worst example, folded because the list above already
- says what to do. */}
- {slots.actions && hasAttention && attention(true)}
-
- {summary.languages.length > 0 && (
- <OverviewSection
- title="Composition"
- action={
- <SectionLink
- href={resolved.languageGraph}
- LinkComponent={LinkComponent}
- >
- Open the graph
- </SectionLink>
- }
- >
- <LanguageBar distribution={langDistribution} />
- </OverviewSection>
- )}
-
{slots.beforeExplore}
- {slots.ask && <OverviewSection title="Ask this codebase">{slots.ask}</OverviewSection>}
-
- <OverviewSection title="Explore this codebase">
- <ExploreList entries={explore} LinkComponent={LinkComponent} />
- </OverviewSection>
+ {/* The areas as the inventory behind "Do next", folded at the bottom
+ because the list above already says what to do. */}
+ {slots.actions && (
+ <AttentionSection summary={summary} base={base} inventory LinkComponent={LinkComponent} />
+ )}
</PageFrame>
);
}
diff --git a/packages/ui/src/overview/overview-model.ts b/packages/ui/src/overview/overview-model.ts
index fa58f80b3..596b1220e 100644
--- a/packages/ui/src/overview/overview-model.ts
+++ b/packages/ui/src/overview/overview-model.ts
@@ -15,27 +15,23 @@
* SWR and cannot be a server component) can both call it.
*
* Host-specific rows need no flags. Every one of them is already gated on a
- * field the payload either carries or does not: local index size is absent on
- * hosted because hosted has no `.repowise/` directory, agent savings are
- * absent because they come from a CLI-written sidecar, and score validation is
- * absent on OSS because nothing backtests it there. Asking "is the data here"
+ * field the payload either carries or does not: score validation, for example,
+ * is absent on OSS because nothing backtests it there. Asking "is the data here"
* gets the right answer on both hosts without either one declaring which host
* it is. The one thing that genuinely cannot be inferred is routing, which is
* why {@link OverviewRoutes} exists and is the whole capability surface.
*/
-import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import type {
+ OverviewAttentionAreaRow,
+ OverviewSummaryResponse,
+} from "@repowise-dev/types/overview";
import type { ChangeStat } from "./change-line";
+import type { ExploreCard } from "./explore-cards";
import type { ExploreEntry } from "./explore-list";
import type { ReadItem } from "./reads-column";
import type { RibbonStat } from "../stats/stat-ribbon";
-import {
- formatBytes,
- formatCost,
- formatLOC,
- formatNumber,
- formatTokens,
-} from "../lib/format";
+import { formatLOC, formatNumber } from "../lib/format";
/**
* Where this host's links go.
@@ -61,10 +57,9 @@ export interface OverviewRoutes {
languageGraph?: string;
/** Scoped chat. Hosted only; OSS puts an ask box on the page instead. */
chat?: string;
- /** Local settings, where the on-disk index lives. OSS only. */
+ /** @deprecated Nothing on Overview links to settings. */
settings?: string;
- /** Indexing cost breakdown. Linked from the savings read on both hosts, and
- * listed under Explore only where the page exists. */
+ /** Indexing cost breakdown, listed under Explore only where the page exists. */
costs?: string;
}
@@ -75,7 +70,6 @@ export type ResolvedOverviewRoutes = ReturnType<typeof resolveOverviewRoutes>;
* Resolved routes, with the defaults both hosts share filled in.
*
* Exported so a renderer that needs one of these hrefs outside a built list
- * (the Composition section links to the same language graph the ribbon does)
* reads it from here rather than rebuilding a list to find one entry in it.
*/
export function resolveOverviewRoutes(routes: OverviewRoutes) {
@@ -135,12 +129,12 @@ export function docPageCount(summary: OverviewSummaryResponse): number {
}
/**
- * The column beside the health hero: the other reasons someone opens this
- * page, at the same altitude as the score.
+ * The column beside the health hero: documentation, and on hosts that
+ * backtest it, how well the health ranking predicted bug fixes.
*/
export function buildReads(summary: OverviewSummaryResponse, routes: OverviewRoutes): ReadItem[] {
const r = resolveOverviewRoutes(routes);
- const { stats, health, sync, savings } = summary;
+ const { stats, health } = summary;
const docPages = docPageCount(summary);
const prosePages = stats.doc_prose_page_count;
const reads: ReadItem[] = [];
@@ -200,50 +194,6 @@ export function buildReads(summary: OverviewSummaryResponse, routes: OverviewRou
});
}
- // From a CLI-written `.repowise/omissions` sidecar, so this row is simply
- // absent wherever that sidecar cannot exist. No flag, no empty state
- // pitching a CLI the viewer is not running.
- const savedTokens = savings.saved_input_tokens ?? 0;
- if (savings.available && savedTokens > 0 && r.costs) {
- // "Estimated" while any of the total rests on a counterfactual rather than
- // a measured before and after. The two are different claims, and the row
- // is too small to show the split, so it qualifies the label instead.
- const inferred = savings.inferred_saved_input_tokens ?? 0;
- reads.push({
- key: "savings",
- label: inferred > 0 ? "Estimated agent savings" : "Agent savings",
- value: formatTokens(savedTokens),
- ...(savings.estimated_usd_saved ? { unit: formatCost(savings.estimated_usd_saved) } : {}),
- href: r.costs,
- why:
- inferred > 0
- ? "Input tokens your agent did not have to read, part of it estimated"
- : "Input tokens your agent did not have to read",
- });
- }
-
- if (stats.dead_export_count > 0) {
- reads.push({
- key: "dead-code",
- label: "Dead code",
- value: formatNumber(stats.dead_export_count),
- unit: "exports",
- href: `${r.base}/code-health?tab=dead-code`,
- why: "Unused exports that nothing in the graph reaches",
- });
- }
-
- // A local-disk figure. Hosted stores indexes elsewhere and never has it.
- if (sync.index_storage_bytes && r.settings) {
- reads.push({
- key: "index",
- label: "Index",
- value: formatBytes(sync.index_storage_bytes),
- href: r.settings,
- why: `Wiki, symbols and vectors on disk · ${Math.round(stats.doc_coverage_pct)}% average doc confidence`,
- });
- }
-
return reads;
}
@@ -288,6 +238,97 @@ export function buildRibbon(
return ribbon;
}
+/** Ingests a coverage report; with no path it finds the report itself. */
+export const COVERAGE_ADD_COMMAND = "repowise coverage add";
+
+const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
+
+/** Coverage when a report exists; the ingest command when the server says none does. */
+function testsCard(explore: OverviewSummaryResponse["explore"], base: string): ExploreCard {
+ const card = { key: "tests", label: "Tests", href: `${base}/tests` };
+ const coverage = explore?.coverage;
+ if (coverage) {
+ return {
+ ...card,
+ value: `${coverage.line_coverage_pct.toFixed(1)}%`,
+ caption: "line coverage from the latest report",
+ };
+ }
+ // A server without the counts cannot say whether a report exists.
+ if (!explore) return { ...card, caption: "Coverage and the tests that reach each file" };
+ return {
+ ...card,
+ caption: "No coverage report yet. Run your tests with coverage on, then add the report:",
+ command: COVERAGE_ADD_COMMAND,
+ };
+}
+
+/**
+ * The six main doors off Overview, each with one live figure read through the
+ * function its page leads with (`summary.explore`), so the card and the page
+ * agree. Keys match {@link buildExplore}'s, so the line of further doors can
+ * drop the entries a card already covers.
+ */
+export function buildExploreCards(
+ summary: OverviewSummaryResponse,
+ routes: OverviewRoutes,
+): ExploreCard[] {
+ const { base } = resolveOverviewRoutes(routes);
+ const { stats, explore } = summary;
+ return [
+ { key: "code-health", label: "Code health map", href: `${base}/code-health`, ...healthFigure(stats) },
+ { key: "contributors", label: "Ownership", href: `${base}/owners`, ...ownershipFigure(explore) },
+ {
+ key: "architecture",
+ label: "Architecture",
+ href: `${base}/architecture`,
+ value: formatNumber(stats.module_count),
+ caption: `${plural(stats.module_count, "module", "modules")}, ${formatNumber(stats.entry_point_count)} entry points`,
+ },
+ { key: "decisions", label: "Decisions", href: `${base}/decisions`, ...decisionsFigure(explore) },
+ { key: "refactoring", label: "Refactoring", href: `${base}/refactoring`, ...refactoringFigure(explore) },
+ testsCard(explore, base),
+ ];
+}
+
+type CardFigure = Pick<ExploreCard, "value" | "caption">;
+type Explore = OverviewSummaryResponse["explore"];
+
+function healthFigure(stats: OverviewSummaryResponse["stats"]): CardFigure {
+ if (stats.hotspot_count === 0) return { value: formatNumber(stats.file_count), caption: "files scored" };
+ return {
+ value: formatNumber(stats.hotspot_count),
+ caption: `${plural(stats.hotspot_count, "hotspot", "hotspots")} across ${formatNumber(stats.file_count)} files`,
+ };
+}
+
+function ownershipFigure(explore: Explore): CardFigure {
+ const sole = explore?.ownership?.sole_owned_files;
+ if (sole == null) return { caption: "Who knows each file, and what depends on them" };
+ return {
+ value: formatNumber(sole),
+ caption: `sole-owned ${plural(sole, "file", "files")}: one author, no second reader`,
+ };
+}
+
+function decisionsFigure(explore: Explore): CardFigure {
+ const d = explore?.decisions;
+ if (!d || d.total === 0) return { caption: "No decisions recorded yet" };
+ return {
+ value: formatNumber(d.total),
+ caption: `recorded, of which ${formatNumber(d.accepted)} accepted and ${formatNumber(d.candidates)} awaiting review`,
+ };
+}
+
+function refactoringFigure(explore: Explore): CardFigure {
+ const r = explore?.refactoring;
+ if (!r) return { caption: "No refactoring analysis yet" };
+ return {
+ value: formatNumber(r.opportunities_total),
+ caption: `open ${plural(r.opportunities_total, "opportunity", "opportunities")}, one per file`,
+ };
+}
+
/**
* Front doors to the pages that own each subject.
*
@@ -357,6 +398,12 @@ export function buildExplore(
href: `${r.base}/commits`,
description: "Change-risk ranked history with agent provenance",
},
+ {
+ key: "decisions",
+ label: "Decisions",
+ href: `${r.base}/decisions`,
+ description: "Why the code is shaped this way, from decision records and git history",
+ },
{
key: "contributors",
label: "Contributors",
@@ -391,3 +438,62 @@ export function buildLanguageDistribution(
for (const l of summary.languages) distribution[l.language] = l.file_count;
return distribution;
}
+
+/** An inventory row, with the unit its count is in. */
+export type InventoryRow = OverviewAttentionAreaRow & { unit?: string };
+
+/**
+ * The inventory's area rows, with each count read from the same basis as the
+ * explore card and the page it links to: open findings for code health,
+ * matches in shipped source for security, open opportunities for
+ * refactoring, decisions to review, and sole-owned files for ownership. Rows
+ * whose basis the payload does not carry keep the server's count.
+ */
+export function inventoryRows(summary: OverviewSummaryResponse): InventoryRow[] {
+ const areas = summary.attention_summary?.areas ?? [];
+ const explore = summary.explore;
+ const findings = summary.health.finding_counts?.inventory;
+ return areas.map((area): InventoryRow => {
+ switch (area.key) {
+ case "health":
+ return findings != null ? { ...area, total: findings, unit: "open findings" } : area;
+ case "security": {
+ const s = explore?.security;
+ if (!s) return area;
+ return {
+ ...area,
+ total: s.source,
+ unit: "in shipped source",
+ detail: s.elsewhere > 0 ? `${formatNumber(s.elsewhere)} more in tests and docs` : "",
+ };
+ }
+ case "refactoring": {
+ const r = explore?.refactoring;
+ return r ? { ...area, total: r.opportunities_total, unit: "open opportunities" } : area;
+ }
+ case "decisions": {
+ const d = explore?.decisions;
+ if (!d) return area;
+ return {
+ ...area,
+ total: d.candidates + d.needs_review,
+ unit: "to review",
+ detail: `${formatNumber(d.candidates)} awaiting review, ${formatNumber(d.needs_review)} drifting from the code`,
+ };
+ }
+ case "ownership": {
+ const o = explore?.ownership;
+ return o
+ ? {
+ ...area,
+ total: o.sole_owned_files,
+ unit: "sole-owned files",
+ detail: "One author, no second reader",
+ }
+ : area;
+ }
+ default:
+ return area;
+ }
+ });
+}
diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsx
index c510c05af..765f56f68 100644
--- a/packages/ui/src/security/findings-table.tsx
+++ b/packages/ui/src/security/findings-table.tsx
@@ -13,7 +13,7 @@ import { SeverityMark } from "../health/severity-mark";
import type { Severity } from "../health/tokens";
import { formatDate, formatDateTime, formatRelativeTimeOrNull } from "../lib/format";
import { FilePath } from "../shared/file-path";
-import { securityLevel, securityPathClass, type SecurityLevel } from "./posture";
+import { securityLevel, type SecurityLevel } from "./posture";
import type { SecurityFinding } from "@repowise-dev/types";
// One declaration of the wire shape, not a third hand-kept copy: this file's
@@ -50,7 +50,7 @@ function FindingLocation({ finding }: { finding: SecurityFinding }) {
const line = finding.line_number;
const verified = finding.line_verified;
// Tests and docs are labelled, never headlined: shipped code ranks first.
- const where = securityPathClass(finding.file_path);
+ const where = finding.path_class ?? "source";
const tag =
where === "source" ? null : (
<span className="ml-1.5 font-sans text-2xs text-[var(--color-text-tertiary)]">{where}</span>
@@ -129,7 +129,7 @@ export function SecurityFindingsTable({
// What to do first: shipped source before tests before docs, then severity.
return [...items].sort(
(a, b) =>
- CLASS_RANK[securityPathClass(a.file_path)] - CLASS_RANK[securityPathClass(b.file_path)] ||
+ CLASS_RANK[a.path_class ?? "source"] - CLASS_RANK[b.path_class ?? "source"] ||
LEVEL_RANK[securityLevel(a.severity)] - LEVEL_RANK[securityLevel(b.severity)],
);
}, [findings, q, sev]);
diff --git a/packages/ui/src/security/posture.tsx b/packages/ui/src/security/posture.tsx
index 36f23a278..617d29c73 100644
--- a/packages/ui/src/security/posture.tsx
+++ b/packages/ui/src/security/posture.tsx
@@ -1,40 +1,9 @@
import * as React from "react";
import { PageLede } from "../shared/page-lede";
import { Skeleton, SkeletonRegion } from "../ui/skeleton";
-import type { SecurityFinding } from "@repowise-dev/types";
+import type { SecurityFinding, SecuritySummary } from "@repowise-dev/types";
-export type SecurityPathClass = "source" | "test" | "docs";
-
-// Client-side guess at where a match lives, mirroring the scanner's own
-// low-severity path tokens. Ceiling: a heuristic on the path alone. Hosted
-// serves a server-side `path_class`; switch to it once the OSS endpoint
-// carries one.
-const TEST_SEGMENTS = new Set([
- "test",
- "tests",
- "__tests__",
- "__test__",
- "testdata",
- "e2e",
- "spec",
- "specs",
- "fixtures",
- "__fixtures__",
-]);
-const DOCS_SEGMENTS = new Set(["docs", "doc", "documentation", "example", "examples"]);
-// Mock directories (`mock`, `mocks`, `__mocks__`) as a pattern: the bare word reads as a provider name to the UI guard.
-const MOCK_SEGMENT = /^(__)?mocks?(__)?$/;
-const TEST_FILE = /(^test_|_test\.|\.test\.|\.spec\.|_spec\.)/i;
-const DOCS_FILE = /\.(md|mdx|rst|adoc)$/i;
-
-/** Shipped source, tests, or docs, judged from the path. */
-export function securityPathClass(path: string): SecurityPathClass {
- const parts = path.replace(/\\/g, "/").toLowerCase().split("/");
- const name = parts[parts.length - 1] ?? "";
- if (parts.some((p) => TEST_SEGMENTS.has(p) || MOCK_SEGMENT.test(p)) || TEST_FILE.test(name)) return "test";
- if (parts.some((p) => DOCS_SEGMENTS.has(p)) || DOCS_FILE.test(name)) return "docs";
- return "source";
-}
+export type { SecurityPathClass } from "@repowise-dev/types";
/** The scanner's three severities; anything unrecognised counts as low. */
export type SecurityLevel = "high" | "med" | "low";
@@ -50,27 +19,30 @@ export interface SecurityPostureCounts {
/** Matches in tests and docs. */
elsewhere: number;
sourceHigh: number;
- high: number;
- med: number;
- low: number;
}
-export function countSecurityFindings(findings: SecurityFinding[]): SecurityPostureCounts {
- const c: SecurityPostureCounts = {
- total: findings.length,
- source: 0,
- elsewhere: 0,
- sourceHigh: 0,
- high: 0,
- med: 0,
- low: 0,
+/** The lede's counts from the server's summary; `null` on a server without them. */
+export function postureCountsFromSummary(
+ summary: SecuritySummary | null | undefined,
+): SecurityPostureCounts | null {
+ const c = summary?.class_counts;
+ if (!c || summary?.total == null) return null;
+ const source = c.source ?? 0;
+ return {
+ total: summary.total,
+ source,
+ elsewhere: (c.test ?? 0) + (c.docs ?? 0),
+ sourceHigh: summary.source_high ?? 0,
};
+}
+
+/** The same counts over listed rows, by the class the server gave each one. */
+export function countSecurityFindings(findings: SecurityFinding[]): SecurityPostureCounts {
+ const c: SecurityPostureCounts = { total: findings.length, source: 0, elsewhere: 0, sourceHigh: 0 };
for (const f of findings) {
- const level = securityLevel(f.severity);
- c[level] += 1;
- if (securityPathClass(f.file_path) === "source") {
+ if ((f.path_class ?? "source") === "source") {
c.source += 1;
- if (level === "high") c.sourceHigh += 1;
+ if (securityLevel(f.severity) === "high") c.sourceHigh += 1;
} else {
c.elsewhere += 1;
}
@@ -116,7 +88,10 @@ export const DEFAULT_SECURITY_POSTURE_LABELS: SecurityPostureLabels = {
};
export interface SecurityPostureProps {
- findings: SecurityFinding[];
+ /** The server's counts (`postureCountsFromSummary`); preferred over `findings`. */
+ counts?: SecurityPostureCounts | null;
+ /** Listed rows, counted when the server sent no counts. */
+ findings?: SecurityFinding[];
/** Relative scan time ("3 days ago"), or null when the server has none. */
scannedAgo: string | null;
/** True when the list was cut at the request limit, so counts are a floor. */
@@ -130,16 +105,23 @@ export interface SecurityPostureProps {
* Never coloured: a pattern match is a lead to confirm, not a live path to
* harm.
*/
-export function SecurityPosture({ findings, scannedAgo, capped = false, labels }: SecurityPostureProps) {
+export function SecurityPosture({
+ counts,
+ findings,
+ scannedAgo,
+ capped = false,
+ labels,
+}: SecurityPostureProps) {
const l = { ...DEFAULT_SECURITY_POSTURE_LABELS, ...labels };
- const c = React.useMemo(() => countSecurityFindings(findings), [findings]);
+ const listed = React.useMemo(() => countSecurityFindings(findings ?? []), [findings]);
+ const c = counts ?? listed;
return (
<PageLede
label={l.figure}
labelHint={l.figureHint}
value={n(c.source)}
- unit={l.unit(c.total, capped)}
+ unit={l.unit(c.total, !counts && capped)}
layout="beside"
>
{/* One paragraph so the scan line stays under the sentence when the
diff --git a/packages/ui/src/settings/settings-primitives.tsx b/packages/ui/src/settings/settings-primitives.tsx
index e36d3678e..7c5c80fb8 100644
--- a/packages/ui/src/settings/settings-primitives.tsx
+++ b/packages/ui/src/settings/settings-primitives.tsx
@@ -140,11 +140,14 @@ export function SaveIndicator({
export function CopyLine({
value,
label,
+ copyLabel,
className,
}: {
value: string;
/** Optional micro-label above the value. */
label?: string;
+ /** What the copy button copies, for its accessible name. Defaults to `label`. */
+ copyLabel?: string;
className?: string;
}) {
const [copied, setCopied] = React.useState(false);
@@ -178,7 +181,7 @@ export function CopyLine({
<button
type="button"
onClick={copy}
- aria-label={copied ? "Copied" : `Copy ${label ?? "value"}`}
+ aria-label={copied ? "Copied" : `Copy ${copyLabel ?? label ?? "value"}`}
className="shrink-0 rounded-md p-2 text-[var(--color-text-tertiary)] transition-colors hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
>
{copied ? (
diff --git a/packages/ui/src/stats/stats-report.tsx b/packages/ui/src/stats/stats-report.tsx
index af3602cf1..e5d7c0f4c 100644
--- a/packages/ui/src/stats/stats-report.tsx
+++ b/packages/ui/src/stats/stats-report.tsx
@@ -1,7 +1,7 @@
import * as React from "react";
import type { StatsHighlights } from "@repowise-dev/types/stats";
import { PageLede } from "../shared/page-lede";
-import { formatAgeDays, formatDate, formatNumber } from "../lib/format";
+import { formatAgeDays, formatBytes, formatDate, formatNumber } from "../lib/format";
import { ArrivalsTimeline } from "./arrivals-timeline";
import { ChronotypeList } from "./chronotype-list";
import { ChurnLedger } from "./churn-ledger";
@@ -205,6 +205,15 @@ function SizeLede({ data }: { data: StatsHighlights }) {
.
</>
)}
+ {data.index_storage_bytes ? (
+ <>
+ {" "}Its Repowise index (documentation, symbols and vectors) takes{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {formatBytes(data.index_storage_bytes)}
+ </strong>{" "}
+ on disk.
+ </>
+ ) : null}
</p>
</PageLede>
);
diff --git a/packages/ui/src/workspace/workspace-next-actions.tsx b/packages/ui/src/workspace/workspace-next-actions.tsx
index 967ad0aa3..c8e741d24 100644
--- a/packages/ui/src/workspace/workspace-next-actions.tsx
+++ b/packages/ui/src/workspace/workspace-next-actions.tsx
@@ -10,7 +10,7 @@ import type {
import type { AiPromptFlavor } from "../health/ai-prompt-builder";
import { ActionDrawer } from "../overview/action-drawer";
-import { ActionRow, renderActionTitle } from "../overview/next-actions";
+import { ActionRow, renderActionTitle, useActionPrompt } from "../overview/next-actions";
import { OverviewSection } from "../overview/section";
import { Segmented } from "../shared/segmented";
@@ -61,6 +61,7 @@ export function WorkspaceNextActions({
null,
);
const Link = LinkComponent ?? "a";
+ const { openActionPrompt, promptModal } = useActionPrompt();
const openedRepoId = opened?.repoId;
const loadActionPrompt = useCallback(
(action: NextAction, flavor: AiPromptFlavor) => loadPrompt!(openedRepoId!, action, flavor),
@@ -154,6 +155,11 @@ export function WorkspaceNextActions({
action={action}
selected={opened?.action.id === action.id && opened.repoId === repoId}
onOpen={() => setOpened({ action, repoId })}
+ onPrompt={
+ loadPrompt
+ ? () => openActionPrompt(action, (a, flavor) => loadPrompt(repoId, a, flavor))
+ : undefined
+ }
/>
))}
</ul>
@@ -183,6 +189,7 @@ export function WorkspaceNextActions({
LinkComponent={LinkComponent}
renderTitle={renderActionTitle}
/>
+ {promptModal}
</OverviewSection>
);
}
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index ca7a16eb6..863bd6414 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -1480,7 +1480,11 @@
"suggestion2": "Where is the retry logic?",
"suggestion3": "Why is this module structured this way?",
"label": "Ask a question about this codebase",
- "submit": "Ask"
+ "submit": "Ask",
+ "hotspotOwners": "Who knows {path} best, and why does it change so often?",
+ "worstFile": "What makes {path} the lowest-scoring file?",
+ "decision": "Why did we decide \"{title}\"?",
+ "trend": "How has code health moved since the previous index?"
}
},
"risk": {
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 73b67f3d1..09355e98a 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -1480,7 +1480,11 @@
"suggestion2": "重试逻辑在哪里?",
"suggestion3": "这个模块为什么这样组织?",
"label": "就这个代码库提问",
- "submit": "提问"
+ "submit": "提问",
+ "hotspotOwners": "谁最熟悉 {path}?它为什么改动这么频繁?",
+ "worstFile": "{path} 为什么是得分最低的文件?",
+ "decision": "我们为什么决定「{title}」?",
+ "trend": "自上次索引以来,代码健康度有什么变化?"
}
},
"risk": {
diff --git a/packages/web/src/app/repos/[id]/overview/loading.tsx b/packages/web/src/app/repos/[id]/overview/loading.tsx
index 9b58dea25..5faa6155e 100644
--- a/packages/web/src/app/repos/[id]/overview/loading.tsx
+++ b/packages/web/src/app/repos/[id]/overview/loading.tsx
@@ -4,7 +4,7 @@ import { Skeleton, SkeletonRegion } from "@repowise-dev/ui/ui/skeleton";
/**
* Skeleton mirroring the Overview layout — identity header, change line,
- * health lede beside its reads column, scale ribbon, then sections.
+ * health lede beside its reads column, ask box, explore cards, then sections.
*
* Shapes and widths track the real page deliberately: a skeleton that does not
* match causes a visible reflow the moment content lands, which reads as
@@ -33,24 +33,23 @@ export default async function OverviewLoading() {
<div className="space-y-3">
<Skeleton className="h-3 w-24" />
<Skeleton className="h-12 w-40" />
- <Skeleton className="h-16 w-full max-w-[54ch]" />
+ <Skeleton className="h-4 w-full max-w-[54ch]" />
<Skeleton className="h-4 w-36" />
</div>
<div className="space-y-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-12" />
- ))}
+ <Skeleton className="h-16" />
</div>
</div>
- <div className="grid grid-cols-2 gap-px sm:grid-cols-3 lg:grid-cols-5">
+ {/* Ask box, then the explore cards */}
+ <Skeleton className="h-10 w-full" />
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-5">
{Array.from({ length: 5 }).map((_, i) => (
- <Skeleton key={i} className="h-14" />
+ <Skeleton key={i} className="h-24" />
))}
</div>
- <Skeleton className="h-48" />
- <Skeleton className="h-40" />
+ <Skeleton className="h-12" />
</PageFrame>
</SkeletonRegion>
);
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index e2e264dcb..da13f7168 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -1,12 +1,13 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
+import { getTranslations } from "next-intl/server";
import Link from "next/link";
import { getOverviewSummary } from "@/lib/api/overview";
import { ApiClientError } from "@/lib/api/client";
import { PageFrame } from "@repowise-dev/ui/shared/page-shell";
import { getActions } from "@/lib/api/actions";
import { getProviders } from "@/lib/api/providers";
-import { getCommitsPage } from "@/lib/api/git";
+import { overviewAskSuggestions } from "@/lib/overview-ask";
import { FirstIndexExperience } from "@/components/repos/first-index-experience";
import { QuickActionsWrapper } from "@/components/dashboard/quick-actions-wrapper";
import { AskAnythingRow } from "@/components/overview/ask-anything-row";
@@ -40,10 +41,6 @@ async function safeFetch<T>(fn: () => Promise<T>): Promise<T | null> {
}
}
-/** Rows shown in the activity section. Fetched server-side so the list is in
- * the initial HTML instead of waterfalling in after paint. */
-const COMMIT_LIMIT = 6;
-
/** The header's chips: language, branch, head commit, size and last sync. */
function identityMeta(
summary: OverviewSummaryResponse,
@@ -82,9 +79,8 @@ export default async function OverviewPage({ params }: Props) {
// Every fetch the page needs, in one wave, on the server. Nothing below
// renders client-side: this is a static read, so a hydration boundary would
- // only buy a slower first paint and worse indexability. The commits call
- // replaces a client-side SWR fetch that used to waterfall in after paint.
- const [summary, providers, commitsPage, actions] = await Promise.all([
+ // only buy a slower first paint and worse indexability.
+ const [summary, providers, actions] = await Promise.all([
// Only a 404 means the repo is gone; any other failure reaches the route
// error boundary instead of reading as "not found".
getOverviewSummary(id).catch((err: unknown) => {
@@ -92,11 +88,11 @@ export default async function OverviewPage({ params }: Props) {
throw err;
}),
safeFetch(() => getProviders()),
- safeFetch(() => getCommitsPage(id, { sort: "date", limit: COMMIT_LIMIT })),
safeFetch(() => getActions(id)),
]);
if (!summary) notFound();
+ const tOverview = await getTranslations("overview");
const { repo, stats, health, sync } = summary;
const isFresh = stats.file_count === 0;
const base = `/repos/${id}`;
@@ -148,24 +144,17 @@ export default async function OverviewPage({ params }: Props) {
// Coupling and the language graph take the shared defaults; `chat` is absent
// because this app answers that need with the ask box below instead of a
- // route, and `settings`/`costs` exist here and are what the index-size and
- // savings reads link to.
- const routes: OverviewRoutes = {
- base,
- settings: `${base}/settings`,
- costs: `${base}/costs`,
- };
+ // route.
+ const routes: OverviewRoutes = { base, costs: `${base}/costs` };
return (
<OverviewBody
summary={summary}
routes={routes}
- commits={commitsPage?.items ?? []}
- totalNloc={totalNloc}
LinkComponent={Link}
slots={{
header,
- ask: <AskAnythingRow repoId={id} />,
+ ask: <AskAnythingRow repoId={id} suggestions={overviewAskSuggestions(summary, tOverview)} />,
beforeExplore: <PublishOverviewSection repoId={id} />,
// A server that predates actions returns 404; the page then keeps the
// attention areas in their old place rather than showing an empty list.
diff --git a/packages/web/src/components/overview/ask-anything-row.tsx b/packages/web/src/components/overview/ask-anything-row.tsx
index 97dc8c4ea..9e29729dd 100644
--- a/packages/web/src/components/overview/ask-anything-row.tsx
+++ b/packages/web/src/components/overview/ask-anything-row.tsx
@@ -29,9 +29,16 @@ const SUGGESTION_KEYS = [
* purpose: this is the one row that does something rather than reporting
* something, and it needs to look different enough to be found.
*/
-export function AskAnythingRow({ repoId }: { repoId: string }) {
+export function AskAnythingRow({
+ repoId,
+ suggestions: given,
+}: {
+ repoId: string;
+ /** Openers built from this repo's data; the generic ones when omitted. */
+ suggestions?: string[];
+}) {
const t = useTranslations("overview");
- const suggestions = SUGGESTION_KEYS.map((key) => t(key));
+ const suggestions = given ?? SUGGESTION_KEYS.map((key) => t(key));
const router = useRouter();
const [question, setQuestion] = useState("");
@@ -90,7 +97,7 @@ export function AskAnythingRow({ repoId }: { repoId: string }) {
key={s}
type="button"
onClick={() => ask(s)}
- className="rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-[11px] text-[var(--color-text-tertiary)] transition-colors hover:border-[var(--color-model)] hover:text-[var(--color-model)]"
+ className="max-w-full rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-left text-[11px] [overflow-wrap:anywhere] text-[var(--color-text-tertiary)] transition-colors hover:border-[var(--color-model)] hover:text-[var(--color-model)]"
>
{s}
</button>
diff --git a/packages/web/src/components/overview/next-actions-panel.tsx b/packages/web/src/components/overview/next-actions-panel.tsx
index 71dae5220..f5fb3f59c 100644
--- a/packages/web/src/components/overview/next-actions-panel.tsx
+++ b/packages/web/src/components/overview/next-actions-panel.tsx
@@ -37,6 +37,7 @@ export function NextActionsPanel({ repoId, data }: { repoId: string; data: Actio
return (
<NextActions
data={view ?? data}
+ defaultOpen={false}
loadPrompt={loadPrompt}
LinkComponent={Link}
hrefFor={(action) => actionHref(action, base)}
diff --git a/packages/web/src/components/security/security-view.tsx b/packages/web/src/components/security/security-view.tsx
index bf9ef49f3..e31383ac5 100644
--- a/packages/web/src/components/security/security-view.tsx
+++ b/packages/web/src/components/security/security-view.tsx
@@ -16,6 +16,8 @@ import { SeverityDirectoryMatrix } from "@repowise-dev/ui/security/severity-dire
import {
SecurityPosture,
SecurityPostureSkeleton,
+ postureCountsFromSummary,
+ type SecurityPostureCounts,
type SecurityPostureLabels,
} from "@repowise-dev/ui/security/posture";
import {
@@ -150,6 +152,7 @@ export function SecurityView({ repoId }: { repoId: string }) {
body = (
<SecurityFindingsBody
list={list}
+ counts={postureCountsFromSummary(summary)}
scannedAgo={scannedAgo}
capped={capped}
labels={labels}
@@ -219,6 +222,7 @@ function SecurityEmpty({
function SecurityFindingsBody({
list,
+ counts,
scannedAgo,
capped,
labels,
@@ -227,6 +231,8 @@ function SecurityFindingsBody({
onGenerateBatchPrompt,
}: {
list: SecurityFinding[];
+ /** The server's split over every finding; null on an older server. */
+ counts: SecurityPostureCounts | null;
scannedAgo: string | null;
capped: boolean;
labels: SecurityPostureLabels;
@@ -237,7 +243,13 @@ function SecurityFindingsBody({
const t = useTranslations("risk");
return (
<>
- <SecurityPosture findings={list} scannedAgo={scannedAgo} capped={capped} labels={labels} />
+ <SecurityPosture
+ counts={counts}
+ findings={list}
+ scannedAgo={scannedAgo}
+ capped={capped}
+ labels={labels}
+ />
<OverviewSection title={t("allFindings")} description={t("description")}>
<SecurityFindingsTable
findings={list}
diff --git a/packages/web/src/lib/overview-ask.test.ts b/packages/web/src/lib/overview-ask.test.ts
new file mode 100644
index 000000000..25074449c
--- /dev/null
+++ b/packages/web/src/lib/overview-ask.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from "vitest";
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+import { overviewAskSuggestions } from "./overview-ask";
+
+const t = (key: string, values?: Record<string, string>) =>
+ values ? `${key}:${Object.values(values).join(",")}` : key;
+
+function summary(overrides: {
+ hotspot?: string;
+ worst?: string | null;
+ decision?: string;
+ snapshots?: number;
+}): OverviewSummaryResponse {
+ return {
+ top_hotspots: overrides.hotspot ? [{ file_path: overrides.hotspot }] : [],
+ recent_decisions: overrides.decision ? [{ title: overrides.decision }] : [],
+ health: {
+ worst_performer_path: overrides.worst ?? null,
+ history: Array.from({ length: overrides.snapshots ?? 0 }, () => ({})),
+ },
+ } as unknown as OverviewSummaryResponse;
+}
+
+describe("overviewAskSuggestions", () => {
+ it("asks about this repo's hotspot, worst file, decision and trend, capped at four", () => {
+ expect(
+ overviewAskSuggestions(
+ summary({ hotspot: "a.py", worst: "b.py", decision: "Use SQLite", snapshots: 2 }),
+ t,
+ ),
+ ).toEqual(["ask.hotspotOwners:a.py", "ask.worstFile:b.py", "ask.decision:Use SQLite", "ask.trend"]);
+ });
+
+ it("skips a worst file that is also the hotspot and tops up with generic openers", () => {
+ expect(overviewAskSuggestions(summary({ hotspot: "a.py", worst: "a.py" }), t)).toEqual([
+ "ask.hotspotOwners:a.py",
+ "ask.suggestion1",
+ "ask.suggestion2",
+ ]);
+ });
+
+ it("clips a long decision title", () => {
+ const [q] = overviewAskSuggestions(summary({ decision: "x".repeat(80) }), t);
+ expect(q!.length).toBeLessThan(80);
+ expect(q!.endsWith("…")).toBe(true);
+ });
+});
diff --git a/packages/web/src/lib/overview-ask.ts b/packages/web/src/lib/overview-ask.ts
new file mode 100644
index 000000000..c9aa93344
--- /dev/null
+++ b/packages/web/src/lib/overview-ask.ts
@@ -0,0 +1,37 @@
+import type { OverviewSummaryResponse } from "@repowise-dev/types/overview";
+
+/** A translator for the `overview.ask` keys. */
+export type AskTranslator = (key: string, values?: Record<string, string>) => string;
+
+const MAX_SUGGESTIONS = 4;
+const MIN_SUGGESTIONS = 3;
+const TITLE_CHARS = 60;
+
+function clip(text: string): string {
+ return text.length > TITLE_CHARS ? `${text.slice(0, TITLE_CHARS - 1).trimEnd()}…` : text;
+}
+
+/**
+ * Questions for the ask box built from this repo's own summary: its busiest
+ * hotspot, its lowest-scoring file, its newest decision and its health trend.
+ * Topped up with the generic openers when the index has too little to ask
+ * about.
+ */
+export function overviewAskSuggestions(
+ summary: OverviewSummaryResponse,
+ t: AskTranslator,
+): string[] {
+ const out: string[] = [];
+ const hotspot = summary.top_hotspots[0]?.file_path;
+ if (hotspot) out.push(t("ask.hotspotOwners", { path: hotspot }));
+ const worst = summary.health.worst_performer_path;
+ if (worst && worst !== hotspot) out.push(t("ask.worstFile", { path: worst }));
+ const decision = summary.recent_decisions[0]?.title;
+ if (decision) out.push(t("ask.decision", { title: clip(decision) }));
+ if (summary.health.history.length >= 2) out.push(t("ask.trend"));
+ for (const key of ["ask.suggestion1", "ask.suggestion2", "ask.suggestion3"]) {
+ if (out.length >= MIN_SUGGESTIONS) break;
+ out.push(t(key));
+ }
+ return out.slice(0, MAX_SUGGESTIONS);
+}
diff --git a/tests/unit/ingestion/test_fs_walk.py b/tests/unit/ingestion/test_fs_walk.py
index 136fefdf0..a01934c5b 100644
--- a/tests/unit/ingestion/test_fs_walk.py
+++ b/tests/unit/ingestion/test_fs_walk.py
@@ -560,7 +560,7 @@ _WALK_ALLOWLIST: dict[tuple[str, str], frozenset[str]] = {
# Scans repowise's own packaged web/ui source dirs, not the user repo.
("cli", "commands/serve_cmd/_web_assets.py"): frozenset({"rglob"}),
# Sizes .repowise/ only — repowise-owned, cannot contain junk trees.
- ("server", "services/overview_payload.py"): frozenset({"rglob"}),
+ ("server", "services/index_storage.py"): frozenset({"rglob"}),
}
diff --git a/tests/unit/server/golden/overview_summary.json b/tests/unit/server/golden/overview_summary.json
index 67e08c1d8..9be2496fa 100644
--- a/tests/unit/server/golden/overview_summary.json
+++ b/tests/unit/server/golden/overview_summary.json
@@ -449,12 +449,30 @@
"savings": {
"available": false
},
+ "explore": {
+ "decisions": {
+ "total": 1,
+ "accepted": 0,
+ "candidates": 1,
+ "needs_review": 0
+ },
+ "refactoring": null,
+ "ownership": {
+ "sole_owned_files": 0
+ },
+ "security": {
+ "total": 3,
+ "source": 3,
+ "source_high": 2,
+ "elsewhere": 0
+ },
+ "coverage": null
+ },
"sync": {
"last_sync_at": "2026-09-02T12:00:00",
"last_resync_at": null,
"last_sync_model": null,
"active_job_id": null,
- "page_count": 2,
- "index_storage_bytes": 0
+ "page_count": 2
}
}
diff --git a/tests/unit/server/test_overview_counts.py b/tests/unit/server/test_overview_counts.py
new file mode 100644
index 000000000..82975b729
--- /dev/null
+++ b/tests/unit/server/test_overview_counts.py
@@ -0,0 +1,138 @@
+"""Overview's explore counts agree with the pages they link to."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import GitMetadata, SecurityFinding
+from repowise.server.services.security_classes import path_class
+from tests.unit.server.conftest import create_test_repo
+from tests.unit.server.test_attention_golden import _seed as seed_findings
+from tests.unit.server.test_overview_summary_golden import _seed_index
+
+
+ ("path", "origin", "expected"),
+ [
+ ("src/run.py", "production", "source"),
+ ("config/settings.py", "production", "source"),
+ ("vendor/x.js", "vendored", "source"),
+ ("tests/test_core.py", "test", "test"),
+ ("tests/fixtures/leak.md", "test", "test"),
+ ("docs/setup.py", "docs_example", "docs"),
+ ("CHANGELOG.md", "production", "docs"),
+ ],
+)
+def test_path_class_reads_the_stored_origin(path: str, origin: str, expected: str) -> None:
+ assert path_class(path, origin) == expected
+
+
+async def test_explore_counts_match_each_pages_lede(
+ client: AsyncClient, session_factory, tmp_path
+) -> None:
+ repo = await create_test_repo(client, tmp_path)
+ await seed_findings(session_factory, repo["id"])
+ await _seed_index(session_factory, repo["id"])
+ base = f"/api/repos/{repo['id']}"
+
+ explore = (await client.get(f"{base}/overview-summary")).json()["explore"]
+
+ lanes = (await client.get(f"{base}/decisions/lane-counts")).json()
+ assert explore["decisions"] == {
+ "total": lanes["total"],
+ "accepted": lanes["active"] + lanes["needs_review"] + lanes["uncheckable"],
+ "candidates": lanes["candidates"],
+ "needs_review": lanes["needs_review"],
+ }
+
+ rollup = (await client.get(f"{base}/refactoring/summary")).json()["summary"]
+ if rollup["status"] == "available":
+ assert explore["refactoring"]["opportunities_total"] == rollup["opportunities_total"]
+ else:
+ assert explore["refactoring"] is None
+
+ security = explore["security"]
+ assert security["source"] + security["elsewhere"] == security["total"]
+ # The seeded matches all sit in shipped source.
+ assert security["total"] == security["source"] > 0
+
+ assert explore["ownership"]["sole_owned_files"] >= 0
+ assert explore["coverage"] is None
+
+
+async def test_ownership_and_security_splits(client: AsyncClient, session_factory, tmp_path) -> None:
+ repo = await create_test_repo(client, tmp_path)
+ rid = repo["id"]
+ async with get_session(session_factory) as session:
+ for i, (bus, name, email) in enumerate(
+ [
+ (1, "ann", None), # counted
+ (1, None, "[email protected]"), # counted: an owner by email
+ (1, "", ""), # no owner
+ (0, "ann", None), # no history
+ (2, "ann", None), # a second reader
+ ]
+ ):
+ session.add(
+ GitMetadata(
+ id=f"gm{i}",
+ repository_id=rid,
+ file_path=f"src/f{i}.py",
+ bus_factor=bus,
+ primary_owner_name=name,
+ primary_owner_email=email,
+ )
+ )
+ for i, (path, severity) in enumerate(
+ [
+ ("src/a.py", "high"),
+ ("src/b.py", "low"),
+ ("tests/t.py", "high"),
+ ("docs/a.md", "med"),
+ # A code file whose origin is docs_example, not a prose doc.
+ ("examples/demo.py", "high"),
+ ]
+ ):
+ session.add(
+ SecurityFinding(
+ repository_id=rid,
+ file_path=path,
+ kind="secret",
+ severity=severity,
+ snippet="",
+ line_number=i + 1,
+ )
+ )
+
+ explore = (await client.get(f"/api/repos/{rid}/overview-summary")).json()["explore"]
+ assert explore["ownership"] == {"sole_owned_files": 2}
+ assert explore["security"] == {"total": 5, "source": 2, "source_high": 1, "elsewhere": 3}
+
+ # The Security page lede reads the same split from its summary, and every
+ # listed row carries its class.
+ summary = (await client.get(f"/api/repos/{rid}/security/summary")).json()
+ assert summary["total"] == 5
+ assert summary["class_counts"] == {"source": 2, "test": 1, "docs": 2}
+ assert summary["source_high"] == 1
+ rows = (await client.get(f"/api/repos/{rid}/security", params={"limit": 10})).json()
+ assert {r["file_path"]: r["path_class"] for r in rows} == {
+ "src/a.py": "source",
+ "src/b.py": "source",
+ "tests/t.py": "test",
+ "docs/a.md": "docs",
+ "examples/demo.py": "docs",
+ }
+
+
+async def test_explore_counts_on_an_empty_index(client: AsyncClient, tmp_path) -> None:
+ repo = await create_test_repo(client, tmp_path)
+ explore = (await client.get(f"/api/repos/{repo['id']}/overview-summary")).json()["explore"]
+ assert explore["security"] == {"total": 0, "source": 0, "source_high": 0, "elsewhere": 0}
+ assert explore["ownership"] == {"sole_owned_files": 0}
+ assert explore["refactoring"] is None
+ assert explore["coverage"] is None
diff --git a/tests/unit/server/test_overview_sync.py b/tests/unit/server/test_overview_sync.py
index 877fd1c26..80132becf 100644
--- a/tests/unit/server/test_overview_sync.py
+++ b/tests/unit/server/test_overview_sync.py
@@ -18,6 +18,7 @@ from sqlalchemy import select
from repowise.core.persistence import crud
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import GenerationJob
+from repowise.server.services.index_storage import index_storage_bytes
from tests.unit.server.conftest import create_test_repo
@@ -127,14 +128,17 @@ async def test_head_commit_falls_back_to_db_without_state_json(
@pytest.mark.asyncio
-async def test_sync_includes_index_storage_bytes(client: AsyncClient, tmp_path) -> None:
- """overview-summary reports total .repowise on-disk footprint."""
+async def test_index_storage_bytes_moves_to_stats(client: AsyncClient, tmp_path) -> None:
+ """The .repowise footprint is measured for Stats; overview no longer walks it."""
repo = await create_test_repo(client, tmp_path)
- repo_dir = Path(repo["local_path"])
- repowise = repo_dir / ".repowise"
+ repowise = Path(repo["local_path"]) / ".repowise"
repowise.mkdir()
(repowise / "wiki.db").write_bytes(b"x" * 100)
- resp = await client.get(f"/api/repos/{repo['id']}/overview-summary")
- assert resp.status_code == 200
- assert resp.json()["sync"]["index_storage_bytes"] == 100
+ assert await index_storage_bytes(repo["local_path"]) == 100
+ assert await index_storage_bytes(None) is None
+ assert await index_storage_bytes(str(tmp_path / "no-index")) is None
+
+ overview = await client.get(f"/api/repos/{repo['id']}/overview-summary")
+ assert overview.status_code == 200
+ assert "index_storage_bytes" not in overview.json()["sync"]
diff --git a/tests/unit/server/test_security.py b/tests/unit/server/test_security.py
index 4e7bb767d..d45f8eb9e 100644
--- a/tests/unit/server/test_security.py
+++ b/tests/unit/server/test_security.py
@@ -50,7 +50,12 @@ async def test_list_security_empty(client: AsyncClient) -> None:
async def test_security_summary_scanned_at(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
url = f"/api/repos/{repo['id']}/security/summary"
- assert (await client.get(url)).json() == {"scanned_at": None}
+ assert (await client.get(url)).json() == {
+ "scanned_at": None,
+ "total": 0,
+ "class_counts": {"source": 0, "test": 0, "docs": 0},
+ "source_high": 0,
+ }
await _insert(app.state.session_factory, repo["id"], snippet="x")
assert (await client.get(url)).json()["scanned_at"] is not None