Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(owners): Ownership page around knowledge coverage, risk and off-boarding (#4153)
Raghav Chamadiya95b9af130ff6
diff --git a/packages/api-client/src/owners.ts b/packages/api-client/src/owners.tsindex 09f689cd7..b3b11abfe 100644--- a/packages/api-client/src/owners.ts+++ b/packages/api-client/src/owners.ts@@ -1,4 +1,4 @@-import type { KnowledgeMatrix, OwnersSummary } from "@repowise-dev/types/owners";+import type { IdentityKind, KnowledgeMatrix, OwnersSummary } from "@repowise-dev/types/owners";import { apiGet } from "./client";import { fetchAllPaginated } from "./pagination";import type {@@ -18,6 +18,8 @@ export interface ListOwnersParams {repoId: string;q?: string;sort?: OwnerSortKey;+ /** Only this kind of identity; omitted lists every kind. */+ kind?: IdentityKind;limit?: number;offset?: number;}diff --git a/packages/core/src/repowise/core/analysis/knowledge_matrix.py b/packages/core/src/repowise/core/analysis/knowledge_matrix.pyindex a08031f32..abf9a252c 100644--- a/packages/core/src/repowise/core/analysis/knowledge_matrix.py+++ b/packages/core/src/repowise/core/analysis/knowledge_matrix.py@@ -119,6 +119,8 @@ def build_knowledge_matrix(int(row_field(m, "bus_factor") or 0),author_pos[primary] if primary else None,[(author_pos[key], round(share, 3)) for key, share in shares],+ # Changed in the activity window: knowledge loss only counts code still moving.+ int(row_field(m, "commit_count_90d") or 0) > 0,))return {diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.pyindex 63b179a90..fb0fb6682 100644--- a/packages/server/src/repowise/server/routers/owners.py+++ b/packages/server/src/repowise/server/routers/owners.py@@ -24,6 +24,7 @@ from repowise.server.schemas import (OwnersSummaryResponse,Paginated,)+from repowise.server.schemas.ownership import IdentityKindFieldfrom repowise.server.services.owner_profile import (_OwnerAccumulator,aggregate_owners,@@ -157,6 +158,9 @@ async def list_owners("files_owned",description="One of: files_owned, hotspots_owned, commit_count_90d, dead_code_lines_owned, bus_factor_risk_files",),+ kind: IdentityKindField | None = Query(+ None, description="Only this kind of identity; omitted lists every kind"+ ),limit: int = Query(50, ge=1, le=500),offset: int = Query(0, ge=0),session: AsyncSession = Depends(get_db_session),@@ -164,7 +168,11 @@ async def list_owners("""Directory of contributors with rollup stats — engineering-leader view."""accs, module_totals = await aggregate_owners(session, repo_id)- entries = [_to_list_entry(a, module_totals) for a in accs.values() if a.key]+ entries = [+ _to_list_entry(a, module_totals)+ for a in accs.values()+ if a.key and (kind is None or a.kind == kind)+ ]if q:needle = q.lower()diff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.pyindex e741ea602..d70e0e47a 100644--- a/packages/server/src/repowise/server/schemas/ownership.py+++ b/packages/server/src/repowise/server/schemas/ownership.py@@ -188,9 +188,10 @@ class KnowledgeMatrixAuthor(BaseModel):#: One file: (dir index, file name, nloc, health score, is_hotspot, bus_factor,-#: primary owner author index, [(author index, share of human commits)]).+#: primary owner author index, [(author index, share of human commits)],+#: changed in the last 90 days).KnowledgeMatrixFile = tuple[- int, str, int, float | None, bool, int, int | None, list[tuple[int, float]]+ int, str, int, float | None, bool, int, int | None, list[tuple[int, float]], bool]diff --git a/packages/types/__tests__/owners.test.ts b/packages/types/__tests__/owners.test.tsindex ec1cd6557..27b9dc2a3 100644--- a/packages/types/__tests__/owners.test.ts+++ b/packages/types/__tests__/owners.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";import { knowledgeMatrixPath, type KnowledgeMatrixFile } from "../src/owners.js";describe("knowledgeMatrixPath", () => {- const row = (dir: number, name: string): KnowledgeMatrixFile => [dir, name, 0, null, false, 0, null, []];+ const row = (dir: number, name: string): KnowledgeMatrixFile => [dir, name, 0, null, false, 0, null, [], false];it("joins the row's directory and file name", () => {expect(knowledgeMatrixPath(["", "src/core"], row(1, "a.py"))).toBe("src/core/a.py");diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 57879913d..d2929f5e6 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -2764,7 +2764,7 @@ export interface KnowledgeMatrixAuthor {export interface KnowledgeMatrixResponse {authors: KnowledgeMatrixAuthor[];dirs: string[];- files: ([number, string, number, number | null, boolean, number, number | null, [number, number][]])[];+ files: ([number, string, number, number | null, boolean, number, number | null, [number, number][], boolean])[];}/** One tool in the configurable surface, with the flags a UI needs. */diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 38fa70eea..e272b6ee9 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -179,6 +179,11 @@ export function bandForScore(score: number): HealthBand {return "at_risk";}+/** The two bands below Fair: where a surface calls health weak. */+export function isWeakHealthBand(band: HealthBand): boolean {+ return band === "needs_work" || band === "at_risk";+}+/*** A 1-10 score at one decimal, rounded down, for display beside its band.* Rounding to nearest would print 6.98 as "7.0" beside "Fair"; flooring candiff --git a/packages/types/src/owners.ts b/packages/types/src/owners.tsindex 63cdca060..cd31803ae 100644--- a/packages/types/src/owners.ts+++ b/packages/types/src/owners.ts@@ -177,6 +177,8 @@ export type KnowledgeMatrixFile = [busFactor: number,primaryOwner: number | null,authors: KnowledgeMatrixShare[],+ /** A commit in the 90 days before HEAD. */+ changed90d: boolean,];/**diff --git a/packages/ui/__tests__/owners/offboarding.test.ts b/packages/ui/__tests__/owners/offboarding.test.tsnew file mode 100644index 000000000..edb36e616--- /dev/null+++ b/packages/ui/__tests__/owners/offboarding.test.ts@@ -0,0 +1,211 @@+import { describe, expect, it } from "vitest";+import type { KnowledgeMatrix } from "@repowise-dev/types/owners";+import {+ DEFAULT_OFFBOARDING_THRESHOLD,+ formatLeaveParam,+ formatThresholdParam,+ parseLeaveParam,+ parseThresholdParam,+ simulateOffboarding,+} from "../../src/owners/offboarding";+import { knowledgeRisks } from "../../src/owners/knowledge-risks";+import { isSharedKnowledge, knowledgeCoverage } from "../../src/owners/knowledge-coverage";+import { quietOwnerExposure } from "../../src/owners/knowledge-loss";+import { isLowHealth, isSingleOwner } from "../../src/owners/knowledge-files";+import {+ buildHandoverPrompt,+ offboardingPromptAreas,+ riskPromptAreas,+} from "../../src/owners/handover-prompt";++const author = (key: string, active = true) => ({+ key,+ name: key.toUpperCase(),+ email: `${key}@x.dev`,+ last_commit_at: null,+ active,+});++// Authors: 0 ana, 1 bo, 2 cy. Health 9.0 is good, 3.0 is in a weak band.+const MATRIX: KnowledgeMatrix = {+ authors: [author("ana"), author("bo"), author("cy", false)],+ dirs: ["", "src/api", "src/ui"],+ files: [+ // ana alone, hotspot -> severe when ana leaves+ [1, "routes.py", 100, 9.0, true, 1, 0, [[0, 1.0]], true],+ // ana 60 / bo 40: at risk at 50% (remaining 0.4), safe at 40%+ [1, "auth.py", 50, 9.0, false, 2, 0, [[0, 0.6], [1, 0.4]], false],+ // bo 70 / ana 30: ana leaving keeps 0.7, not at risk+ [2, "view.tsx", 80, 3.0, false, 2, 1, [[1, 0.7], [0, 0.3]], true],+ // cy alone, weak health -> severe when cy leaves+ [0, "setup.py", 20, 3.0, false, 1, 2, [[2, 1.0]], true],+ // no history: bus factor 0 is never single-owner+ [0, "empty.py", 5, null, false, 0, null, [], false],+ ],+};++describe("simulateOffboarding", () => {+ it("flags files whose remaining share drops below the threshold", () => {+ const r = simulateOffboarding(MATRIX, ["ana"]);+ expect(r.threshold).toBe(DEFAULT_OFFBOARDING_THRESHOLD);+ expect(r.areas.flatMap((a) => a.files.map((f) => f.path))).toEqual(["src/api/routes.py", "src/api/auth.py"]);+ expect(r.totals.touchedFiles).toBe(3);+ expect(r.totals.atRiskFiles).toBe(2);+ expect(r.totals.severeFiles).toBe(1);+ expect(r.totals.hotspots).toBe(1);+ expect(r.totals.atRiskNloc).toBe(150);+ expect(r.totals.totalNloc).toBe(255);+ expect(r.totals.nlocShare).toBeCloseTo(150 / 255);+ expect(r.leaving.map((p) => p.key)).toEqual(["ana"]);+ });++ it("grades severity and names the strongest author who stays", () => {+ const [routes, auth] = simulateOffboarding(MATRIX, ["ana"]).areas[0]!.files;+ expect(routes?.severity).toBe("severe");+ expect(routes?.inheritor).toBeNull();+ expect(auth?.severity).toBe("at_risk");+ expect(auth?.lostShare).toBeCloseTo(0.6);+ expect(auth?.remainingShare).toBeCloseTo(0.4);+ expect(auth?.inheritor).toMatchObject({ key: "bo", share: 0.4 });+ });++ it("rolls files up by directory with one suggested inheritor", () => {+ const { areas } = simulateOffboarding(MATRIX, ["ana"]);+ expect(areas).toHaveLength(1);+ expect(areas[0]).toMatchObject({ dir: "src/api", fileCount: 2, severe: 1, hotspots: 1, nloc: 150 });+ expect(areas[0]?.inheritor).toMatchObject({ person: { key: "bo" }, files: 1 });+ });++ it("moves with the threshold", () => {+ expect(simulateOffboarding(MATRIX, ["ana"], 0.4).totals.atRiskFiles).toBe(1);+ expect(simulateOffboarding(MATRIX, ["ana"], 0.75).totals.atRiskFiles).toBe(3);+ });++ it("adds up several leavers and sorts areas severe first", () => {+ const r = simulateOffboarding(MATRIX, ["ana", "bo"]);+ expect(r.totals.atRiskFiles).toBe(3);+ expect(r.areas.map((a) => a.dir)).toEqual(["src/api", "src/ui"]);+ });++ it("counts only changing files when asked, denominators included", () => {+ const r = simulateOffboarding(MATRIX, ["ana"], 0.5, { changedOnly: true });+ expect(r.areas.flatMap((a) => a.files.map((f) => f.path))).toEqual(["src/api/routes.py"]);+ expect(r.totals.touchedFiles).toBe(2);+ expect(r.totals.totalNloc).toBe(200);+ expect(r.totals.trackedFiles).toBe(3);+ expect(r.totals.nlocShare).toBeCloseTo(100 / 200);+ });++ it("ignores unknown keys and an empty selection", () => {+ const r = simulateOffboarding(MATRIX, ["nobody"]);+ expect(r.leaving).toEqual([]);+ expect(r.areas).toEqual([]);+ expect(r.totals.totalNloc).toBe(255);+ });+});++describe("knowledgeRisks", () => {+ it("keeps single-owner files that are hotspots or weak, grouped by directory", () => {+ const r = knowledgeRisks(MATRIX);+ expect(r.files).toBe(2);+ expect(r.hotspots).toBe(1);+ expect(r.lowHealth).toBe(1);+ expect(r.areas.map((a) => a.dir)).toEqual(["src/api", ""]);+ expect(r.areas[0]?.holder).toMatchObject({ person: { key: "ana" }, files: 1 });+ expect(r.areas[1]?.files[0]).toMatchObject({ path: "setup.py", lowHealth: true, second: null });+ });+});++describe("knowledgeCoverage", () => {+ it("weighs changing code with history by lines, shared when two or more hold it", () => {+ const c = knowledgeCoverage(MATRIX);+ // routes (100, one holder), view (80, shared), setup (20, one holder); auth and empty did not change.+ expect(c).toMatchObject({ files: 3, sharedFiles: 1, nloc: 200, sharedNloc: 80, basis: "nloc" });+ expect(c.share).toBeCloseTo(0.4);+ expect(c.singleHolderFiles).toBe(2);+ expect(c.singleHolderAreas.map((a) => a.dir)).toEqual(["src/api", ""]);+ });++ it("falls back to file counts without sizes and is null when nothing changed", () => {+ const sizeless = { ...MATRIX, files: MATRIX.files.map((f) => [f[0], f[1], 0, ...f.slice(3)] as typeof f) };+ expect(knowledgeCoverage(sizeless)).toMatchObject({ basis: "files", share: 1 / 3 });+ const still = { ...MATRIX, files: MATRIX.files.map((f) => [...f.slice(0, 8), false] as unknown as typeof f) };+ expect(knowledgeCoverage(still).share).toBeNull();+ });++ it("never counts a file without history as shared", () => {+ expect(isSharedKnowledge(0)).toBe(false);+ expect(isSharedKnowledge(1)).toBe(false);+ expect(isSharedKnowledge(2)).toBe(true);+ });+});++describe("quietOwnerExposure", () => {+ it("reads each quiet owner as a single-person off-boarding", () => {+ const rows = quietOwnerExposure(MATRIX, [+ { key: "cy", name: "CY", last_commit_at: null, files_owned: 1, changing_files_owned: 1 },+ ]);+ expect(rows[0]?.result.totals).toMatchObject({ atRiskFiles: 1, severeFiles: 1 });+ });+});++describe("predicates", () => {+ it("never counts bus factor 0 as single-owner", () => {+ expect(isSingleOwner(1)).toBe(true);+ expect(isSingleOwner(0)).toBe(false);+ expect(isSingleOwner(2)).toBe(false);+ });+ it("reads weak health from the bands and treats unscored as not weak", () => {+ expect(isLowHealth(3.0)).toBe(true);+ expect(isLowHealth(9.0)).toBe(false);+ expect(isLowHealth(null)).toBe(false);+ });+});++describe("URL params", () => {+ it("round-trips keys holding commas and percent signs", () => {+ const keys = ["[email protected]", "name:Doe, Jane", "50%off"];+ expect(parseLeaveParam(formatLeaveParam(keys))).toEqual(keys);+ expect(parseLeaveParam("a,,a,b")).toEqual(["a", "b"]);+ expect(parseLeaveParam(null)).toEqual([]);+ });+ it("clamps whole percents to the offered range and falls back otherwise", () => {+ expect(parseThresholdParam("30")).toBe(0.3);+ expect(parseThresholdParam("0")).toBe(0.1);+ expect(parseThresholdParam("100")).toBe(0.9);+ expect(parseThresholdParam("12.5")).toBe(DEFAULT_OFFBOARDING_THRESHOLD);+ expect(parseThresholdParam("abc")).toBe(DEFAULT_OFFBOARDING_THRESHOLD);+ expect(parseThresholdParam(null)).toBe(DEFAULT_OFFBOARDING_THRESHOLD);+ expect(formatThresholdParam(0.3)).toBe("30");+ });+});++describe("buildHandoverPrompt", () => {+ it("lists areas, files and the suggested person", () => {+ const prompt = buildHandoverPrompt({+ purpose: "handover",+ people: ["ANA"],+ areas: offboardingPromptAreas(simulateOffboarding(MATRIX, ["ana"]).areas),+ });+ expect(prompt).toContain("\n\n## Knowledge handover from ANA");+ expect(prompt).toContain("`src/api/routes.py` (100% of commits, hotspot)");+ expect(prompt).toContain("Could take over: BO");+ expect(prompt).toContain("\n\n## Hard constraints\n");+ expect(prompt).toContain("less than 50% of the commits");+ });+ it("states the scenario's threshold", () => {+ const prompt = buildHandoverPrompt({ purpose: "handover", people: ["ANA"], areas: [], threshold: 0.7 });+ expect(prompt).toContain("less than 70% of the commits");+ });+ it("frames a spread plan around the holder", () => {+ const prompt = buildHandoverPrompt({+ purpose: "spread",+ people: ["CY"],+ areas: riskPromptAreas(knowledgeRisks(MATRIX).areas.filter((a) => a.dir === "")),+ flavor: "claude-code-mcp",+ });+ expect(prompt).toContain("## Spread knowledge held only by CY");+ expect(prompt).toContain("`(repository root)`");+ expect(prompt).toContain("get_risk");+ });+});diff --git a/packages/ui/__tests__/owners/owner-labels.test.tsx b/packages/ui/__tests__/owners/owner-labels.test.tsxnew file mode 100644index 000000000..09668a91e--- /dev/null+++ b/packages/ui/__tests__/owners/owner-labels.test.tsx@@ -0,0 +1,83 @@+import { describe, expect, it } from "vitest";+import { render, screen } from "@testing-library/react";+import type { OwnerListEntry, OwnerProfile } from "@repowise-dev/types/owners";++import { OwnerProfileView } from "../../src/owners/owner-profile";+import { OwnerTable } from "../../src/owners/owner-table";++const profile: OwnerProfile = {+ key: "[email protected]",+ name: "Ana",+ email: "[email protected]",+ kind: "human",+ aliases: { names: ["Ana"], emails: ["[email protected]", "[email protected]"] },+ files_owned: 2,+ hotspots_owned: 0,+ silo_modules: 0,+ dead_code_files_owned: 0,+ dead_code_lines_owned: 0,+ commit_count_90d: 3,+ last_commit_at: null,+ first_commit_at: null,+ bus_factor_risk_files: 0,+ lines_added_90d_est: 0,+ lines_deleted_90d_est: 0,+ modules: [{ module_path: "src", file_count: 2, hotspot_count: 0, dominant_pct: 0.5 }],+ top_files: [],+ co_authors: [],+ commit_categories: {},+};++const owner: OwnerListEntry = {+ key: "bot",+ name: "renovate[bot]",+ email: null,+ kind: "bot",+ files_owned: 1,+ hotspots_owned: 0,+ silo_modules: 0,+ dead_code_files_owned: 0,+ dead_code_lines_owned: 0,+ commit_count_90d: 1,+ last_commit_at: null,+ bus_factor_risk_files: 0,+};++describe("ownership labels on the person page and the people table", () => {+ it("renders English defaults without labels", () => {+ render(<OwnerProfileView owner={profile} base="/repos/1" dependsOn={null} />);+ expect(screen.getByText("What depends on them")).toBeTruthy();+ expect(screen.getByText("Where they work")).toBeTruthy();+ expect(screen.getByText("Active: 3 commits in the last 90 days")).toBeTruthy();+ expect(screen.getByText("[email protected]")).toBeTruthy();+ });++ it("renders the host's labels", () => {+ render(+ <OwnerProfileView+ owner={profile}+ base="/repos/1"+ dependsOn={null}+ labels={{+ dependsTitle: "依赖于他们的代码",+ footprintTitle: "他们的工作范围",+ activeLine: (n) => `活跃:${n}`,+ aliasesLabel: "其他提交身份",+ }}+ />,+ );+ expect(screen.getByText("依赖于他们的代码")).toBeTruthy();+ expect(screen.getByText("他们的工作范围")).toBeTruthy();+ expect(screen.getByText("活跃:3")).toBeTruthy();+ expect(screen.getByText("其他提交身份")).toBeTruthy();+ });++ it("labels the table's columns and automation kinds", () => {+ render(+ <OwnerTable owners={[owner]} sort="files_owned" labels={{ colContributor: "贡献者", kindBot: "机器人" }} />,+ );+ expect(screen.getByText("贡献者")).toBeTruthy();+ expect(screen.getByText("机器人")).toBeTruthy();+ expect(screen.getByText("Files owned")).toBeTruthy();+ });+});diff --git a/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsx b/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsxdeleted file mode 100644index eb0d53631..000000000--- a/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { describe, it, expect } from "vitest";-import { render, screen, within } from "@testing-library/react";-import type { OwnerListEntry } from "@repowise-dev/types/owners";--import { OwnershipDistributionBar } from "../../src/owners/ownership-distribution-bar";--const owner = (name: string, files: number): OwnerListEntry => ({- key: name,- name,- email: null,- kind: "human",- files_owned: files,- hotspots_owned: 0,- silo_modules: 0,- dead_code_files_owned: 0,- dead_code_lines_owned: 0,- commit_count_90d: null,- last_commit_at: null,- bus_factor_risk_files: 0,-});--describe("OwnershipDistributionBar", () => {- it("names the top five, links them, and folds every other contributor", () => {- const owners = [10, 60, 5, 40, 30, 20, 2].map((n, i) => owner(`dev${i}`, n));- const { container } = render(- <OwnershipDistributionBar- owners={owners}- totalContributors={40}- hrefFor={(o) => `/owners/${o.key}`}- />,- );- const items = within(screen.getByRole("list", { name: "Owned files by contributor" }))- .getAllByRole("listitem")- .map((li) => li.textContent);- // 167 owned files across the seven loaded contributors.- expect(items).toEqual(["dev136%", "dev324%", "dev418%", "dev512%", "dev06%", "35 others4%"]);- expect(screen.getByRole("link", { name: /dev1/ })).toHaveAttribute("href", "/owners/dev1");- // The same series colours as every other proportion, never the accent token.- expect(container.innerHTML).toContain("--color-series-1");- expect(container.innerHTML).not.toContain("accent");- });-});diff --git a/packages/ui/__tests__/owners/ownership-lede.test.tsx b/packages/ui/__tests__/owners/ownership-lede.test.tsxnew file mode 100644index 000000000..4104452f1--- /dev/null+++ b/packages/ui/__tests__/owners/ownership-lede.test.tsx@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";+import { render, screen } from "@testing-library/react";+import type { OwnersSummary } from "@repowise-dev/types/owners";++import { OwnershipLede } from "../../src/owners/ownership-lede";+import type { KnowledgeCoverage } from "../../src/owners/knowledge-coverage";++const summary: OwnersSummary = {+ truck_factor: 1,+ people: 3,+ automation_identities: 0,+ owners: 2,+ tracked_files: 10,+ owned_files: 10,+ single_owner_files: 6,+ single_owner_hotspots: 2,+ concentration: { top_n: 3, share: 0.9, owners: [{ key: "[email protected]", name: "Ana Example", files_owned: 9, share: 0.9 }] },+ silo_modules: [],+ activity_window_days: 90,+ active_contributors: 2,+ activity_complete: true,+ quiet_owners: [],+ quiet_owners_total: 0,+};++const coverage = (share: number | null): KnowledgeCoverage => ({+ files: 4,+ sharedFiles: 3,+ nloc: 100,+ sharedNloc: 74,+ share,+ basis: "nloc",+ singleHolderAreas: [],+ singleHolderFiles: 1,+});++const href = (tab: string, leave?: string[]) => `?tab=${tab}${leave?.length ? `&leave=${leave.join(",")}` : ""}`;++describe("OwnershipLede", () => {+ it("leads with knowledge coverage, calm green when well shared", () => {+ render(<OwnershipLede coverage={coverage(0.74)} summary={summary} hrefForTab={href} />);+ expect(screen.getByText("74%", { selector: "*:not(p)" })).toBeTruthy();+ expect(screen.getByText("Well shared")).toBeTruthy();+ expect(screen.getByText(/has two or more people who know it/)).toBeTruthy();+ expect(screen.getByRole("button", { name: /Copy prompt for your agent/ })).toBeTruthy();+ });++ it("reads plain when low and never names the truck-factor person", () => {+ const { container } = render(<OwnershipLede coverage={coverage(0.3)} summary={summary} hrefForTab={href} />);+ expect(screen.queryByText("Well shared")).toBeNull();+ expect(screen.getByText("Fewest people holding half the owned files")).toBeTruthy();+ expect(container.textContent).not.toContain("Ana Example");+ });++ it("says so when nothing with history changed", () => {+ render(<OwnershipLede coverage={coverage(null)} summary={summary} hrefForTab={href} />);+ expect(screen.getByText(/no moving\s+code to measure/)).toBeTruthy();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex a4cdfc17b..a327cc104 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -54,6 +54,9 @@"./symbols/normalize-calls": "./src/symbols/normalize-calls.ts","./symbols/*": "./src/symbols/*.tsx","./owners": "./src/owners/index.ts",+ "./owners/offboarding": "./src/owners/offboarding.ts",+ "./owners/knowledge-coverage": "./src/owners/knowledge-coverage.ts",+ "./owners/labels": "./src/owners/labels.ts","./owners/*": "./src/owners/*.tsx","./modules": "./src/modules/index.ts","./modules/*": "./src/modules/*.tsx",diff --git a/packages/ui/src/health/coverage-view.tsx b/packages/ui/src/health/coverage-view.tsxindex 9df90bfc7..8c5017819 100644--- a/packages/ui/src/health/coverage-view.tsx+++ b/packages/ui/src/health/coverage-view.tsx@@ -56,13 +56,12 @@ import {buildCoverageBatchAiPrompt,type CoverageFilePromptInput,} from "./ai-prompt-builder";-import { bandForScore } from "@repowise-dev/types/health";+import { bandForScore, isWeakHealthBand } from "@repowise-dev/types/health";import { scoreTextColor } from "./tokens";/** Plain figure; the band colour appears only where health is actually weak. */function quietScoreText(score: number): string {- const band = bandForScore(score);- return band === "needs_work" || band === "at_risk"+ return isWeakHealthBand(bandForScore(score))? scoreTextColor(score): "text-[var(--color-text-secondary)]";}diff --git a/packages/ui/src/owners/handover-prompt.ts b/packages/ui/src/owners/handover-prompt.tsnew file mode 100644index 000000000..bff52d386--- /dev/null+++ b/packages/ui/src/owners/handover-prompt.ts@@ -0,0 +1,178 @@+/**+ * The agent prompt for knowledge handover. Two purposes share one shape:+ *+ * - `handover`: people are leaving (or have gone quiet); plan how the code+ * they hold passes to whoever stays.+ * - `spread`: one person holds busy or weak code alone; plan how a second+ * person comes to know it.+ *+ * Both list the areas, the files that matter most in each, and the suggested+ * person, then ask for a plan the team can run, not a code change.+ */++import {+ bulletList,+ closingSections,+ joinSections,+ pluralS,+ preamble,+ repoSuffix,+ type AiPromptFlavor,+} from "../health/ai-prompts/shared";+import { joinNames, mostNamed } from "./knowledge-files";+import type { KnowledgeRiskArea } from "./knowledge-risks";+import type { OffboardingArea } from "./offboarding";++export type HandoverPurpose = "handover" | "spread";++export interface HandoverPromptFile {+ path: string;+ isHotspot: boolean;+ lowHealth: boolean;+ /** Share of commits the holder or leavers made (0-1). */+ share: number;+}++export interface HandoverPromptArea {+ dir: string;+ files: HandoverPromptFile[];+ /** Who could take over (`handover`) or learn it (`spread`). */+ suggested?: string | null;+}++export interface BuildHandoverPromptOptions {+ purpose: HandoverPurpose;+ /** Leavers for `handover`, the holder(s) for `spread`. */+ people: string[];+ areas: HandoverPromptArea[];+ flavor?: AiPromptFlavor;+ repoName?: string;+ /** `handover`: the share the people who stay fall below (0-1). Default 0.5. */+ threshold?: number;+ /** `spread`: why these files matter now. Default: hotspots or weak health. */+ spreadReason?: string;+}++/** Named people past which the prompt says "and N others". */+const MAX_NAMED = 4;++function namePeople(people: readonly string[]): string {+ const named =+ people.length > MAX_NAMED+ ? [...people.slice(0, MAX_NAMED), `${people.length - MAX_NAMED} others`]+ : people;+ return joinNames(named) || "the selected people";+}++/** Past these the prompt says how many more there are instead of listing them. */+const MAX_AREAS = 8;+const MAX_FILES_PER_AREA = 6;++const PARTS = {+ source:+ "Repowise read the git history below: who wrote the commits behind each file, which files churn most (hotspots), and which sit in a weak health band. Shares are of commits, so they describe history, not who understands the code today.",+ open: "each file listed, its tests and its callers",+ mcpTail:+ "Call `get_context([...])` on each area for its documentation and owners, `get_risk([...])` for co-change partners and test gaps, and `get_why(...)` for the decisions behind the code.",+};++const CONSTRAINTS = [+ "Do not change code. This is a plan for people; propose code changes only where they lower the cost of the handover (a missing test, an undocumented invariant), and list them separately.",+ "Ground every claim in the files: name the function, the invariant or the test you are pointing at.",+ "Keep it proportionate: a file that is small and well tested needs a line, not a section.",+];++const EXPECTED = {+ handover: [+ "1. Per area: what someone taking over must know first (entry points, invariants, the risky paths), and where it is written down today, if anywhere.",+ "2. A handover order: which area first and why (hotspots and weak health before quiet code).",+ "3. For each area, a concrete session the leaver and the suggested person can run (what to walk through, which change to pair on), or the reading list if the leaver is already gone.",+ "4. The documentation and tests that would make the handover stick, as a short checklist.",+ ],+ spread: [+ "1. Per area: what only the holder knows today (entry points, invariants, the risky paths), and where it is written down, if anywhere.",+ "2. Who should learn it and how: the suggested person, a first change they could make with the holder reviewing, and what to read before it.",+ "3. The documentation and tests that would let a second person review changes here with confidence, as a short checklist.",+ ],+} as const;++function fileLine(f: HandoverPromptFile): string {+ const marks = [f.isHotspot ? "hotspot" : null, f.lowHealth ? "weak health" : null].filter(Boolean);+ return `\`${f.path}\` (${Math.round(f.share * 100)}% of commits${marks.length ? `, ${marks.join(", ")}` : ""})`;+}++function areaSection(area: HandoverPromptArea, purpose: HandoverPurpose): string {+ const shown = area.files.slice(0, MAX_FILES_PER_AREA);+ const more = area.files.length - shown.length;+ const who = purpose === "handover" ? "Could take over" : "Could learn it";+ return joinSections([+ `\n### \`${area.dir || "(repository root)"}\` (${area.files.length} file${pluralS(area.files.length)})`,+ area.suggested ? `${who}: ${area.suggested}` : "",+ bulletList([...shown.map(fileLine), more > 0 ? `…and ${more} more in this directory` : null]),+ ]);+}++export function buildHandoverPrompt({+ purpose,+ people,+ areas,+ flavor = "generic",+ repoName,+ threshold = 0.5,+ spreadReason = "each one is a hotspot or in a weak health band",+}: BuildHandoverPromptOptions): string {+ const shown = areas.slice(0, MAX_AREAS);+ const hidden = areas.length - shown.length;+ const files = areas.reduce((s, a) => s + a.files.length, 0);+ const names = namePeople(people);+ const heading =+ purpose === "handover"+ ? `## Knowledge handover from ${names}${repoSuffix(repoName)}`+ : `## Spread knowledge held only by ${names}${repoSuffix(repoName)}`;+ const situation =+ purpose === "handover"+ ? `Without ${names}, the people who stay would hold less than ${Math.round(threshold * 100)}% of the commits behind these ${files} file${pluralS(files)}.`+ : `One person made at least 80% of the commits behind each of these ${files} file${pluralS(files)} (${names}), and ${spreadReason}.`;+ // joinSections drops "" entries, so each section carries its own blank line.+ return joinSections([+ preamble(flavor, PARTS),+ `\n${heading}`,+ `\n${situation}`,+ ...shown.map((a) => areaSection(a, purpose)),+ hidden > 0 ? `\n…and ${hidden} more director${hidden === 1 ? "y" : "ies"}; plan them after the above.` : "",+ `\n${closingSections(CONSTRAINTS, [...EXPECTED[purpose]]).join("\n")}`,+ ]);+}++// ---------------------------------------------------------------------------+// From the derivations to the prompt's areas+// ---------------------------------------------------------------------------++/** Off-boarding areas: the share is what the leavers made. */+export function offboardingPromptAreas(areas: readonly OffboardingArea[]): HandoverPromptArea[] {+ return areas.map((a) => ({+ dir: a.dir,+ suggested: a.inheritor?.person.name ?? null,+ files: a.files.map((f) => ({+ path: f.path,+ isHotspot: f.isHotspot,+ lowHealth: f.lowHealth,+ share: f.lostShare,+ })),+ }));+}++/** Knowledge-risk areas: the share is the holder's, the suggestion the commonest next author. */+export function riskPromptAreas(areas: readonly KnowledgeRiskArea[]): HandoverPromptArea[] {+ return areas.map((a) => ({+ dir: a.dir,+ suggested: mostNamed(a.files.flatMap((f) => (f.second ? [{ person: f.second, nloc: f.nloc }] : [])))+ ?.person.name ?? null,+ files: a.files.map((f) => ({+ path: f.path,+ isHotspot: f.isHotspot,+ lowHealth: f.lowHealth,+ share: f.holder.share,+ })),+ }));+}diff --git a/packages/ui/src/owners/index.ts b/packages/ui/src/owners/index.tsindex 1112b27f5..b591054f7 100644--- a/packages/ui/src/owners/index.ts+++ b/packages/ui/src/owners/index.ts@@ -1,5 +1,19 @@export * from "./owner-directory";export * from "./owner-table";-export * from "./ownership-distribution-bar";export * from "./owner-profile";export * from "./owner-avatar";+export * from "./ownership-lede";+export * from "./knowledge-coverage";+export * from "./labels";+export * from "./prompt-requests";+export * from "./knowledge-files";+export * from "./knowledge-risks";+export * from "./knowledge-loss";+export * from "./offboarding";+export * from "./handover-prompt";+export * from "./knowledge-area-list";+export * from "./knowledge-risks-view";+export * from "./knowledge-loss-view";+export * from "./offboarding-result";+export * from "./offboarding-view";+export * from "./people-picker";diff --git a/packages/ui/src/owners/knowledge-area-list.tsx b/packages/ui/src/owners/knowledge-area-list.tsxnew file mode 100644index 000000000..6586db7c6--- /dev/null+++ b/packages/ui/src/owners/knowledge-area-list.tsx@@ -0,0 +1,224 @@+"use client";++import * as React from "react";+import { formatScore } from "@repowise-dev/types/health";+import { RowPromptAction } from "../health/row-prompt-action";+import { scoreTextColor } from "../health/tokens";+import { fileEntityPath } from "../shared/entity";+import { PathText } from "../shared/path-text";+import type { OwnershipLabels } from "./labels";++/**+ * Directories of files that carry knowledge risk, area first and files on+ * demand: the shape the Knowledge risks, Knowledge loss and Off-boarding views+ * and the person page all share. Each area carries a quiet prompt for its+ * files, shown on hover and focus; the one filled prompt sits on the section.+ */++export interface KnowledgeAreaFile {+ path: string;+ nloc: number;+ healthScore: number | null;+ isHotspot: boolean;+ lowHealth: boolean;+ /** Right-aligned detail, e.g. "ana 92%" or "loses 60%". */+ note?: string;+}++export interface KnowledgeAreaRowProps {+ dir: string;+ files: KnowledgeAreaFile[];+ /** One line under the path: who holds it, who could take over. */+ summary?: React.ReactNode;+ onPrompt: () => void;+ /** `/repos/{id}`: file rows link to the file page under it. */+ base?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ defaultOpen?: boolean;+ labels: OwnershipLabels;+}++/** Files listed before "Show all N". */+const FILE_LIMIT = 12;++function FileMarks({ file, hotspot }: { file: KnowledgeAreaFile; hotspot: string }) {+ return (+ <span className="flex shrink-0 items-baseline gap-2 font-mono text-[10px] uppercase tracking-[0.08em] text-[var(--color-text-tertiary)]">+ {file.isHotspot && <span>{hotspot}</span>}+ {file.lowHealth && file.healthScore != null && (+ <span className={`normal-case tracking-normal ${scoreTextColor(file.healthScore)}`}>+ {formatScore(file.healthScore)}+ </span>+ )}+ </span>+ );+}++export function KnowledgeAreaRow({+ dir,+ files,+ summary,+ onPrompt,+ base,+ LinkComponent,+ defaultOpen = false,+ labels,+}: KnowledgeAreaRowProps) {+ const [open, setOpen] = React.useState(defaultOpen);+ const panelId = React.useId();++ return (+ <li className="group/row border-b border-[var(--color-border-default)] py-3">+ <div className="flex flex-wrap items-start gap-x-3 gap-y-2">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={panelId}+ onClick={() => setOpen((o) => !o)}+ className="group flex min-w-0 flex-1 items-start gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <span+ aria-hidden+ className={`mt-0.5 text-[var(--color-text-tertiary)] transition-transform ${open ? "rotate-90" : ""}`}+ >+ ▸+ </span>+ <span className="min-w-0">+ <span className="flex flex-wrap items-baseline gap-x-2">+ <PathText path={dir ? `${dir}/` : labels.repositoryRoot} className="text-[13px]" />+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {labels.files(files.length)}+ </span>+ </span>+ {summary && (+ <span className="mt-0.5 block text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {summary}+ </span>+ )}+ </span>+ </button>+ <RowPromptAction+ onClick={onPrompt}+ label={labels.promptForGroup(files.length)}+ subject={dir || labels.repositoryRoot}+ />+ </div>++ {open && (+ <AreaFiles id={panelId} dir={dir} files={files} base={base} LinkComponent={LinkComponent} labels={labels} />+ )}+ </li>+ );+}++/** An open area's files, named relative to the area, the first few then "Show all". */+function AreaFiles({+ id,+ dir,+ files,+ base,+ LinkComponent,+ labels,+}: {+ id: string;+ dir: string;+ files: KnowledgeAreaFile[];+ base?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels: OwnershipLabels;+}) {+ const [all, setAll] = React.useState(false);+ const shown = all ? files : files.slice(0, FILE_LIMIT);+ return (+ <ul id={id} className="mt-2 flex flex-col pl-5">+ {shown.map((f) => (+ <AreaFileRow key={f.path} file={f} dir={dir} base={base} LinkComponent={LinkComponent} hotspot={labels.hotspot} />+ ))}+ {files.length > shown.length && (+ <li>+ <button+ type="button"+ onClick={() => setAll(true)}+ className="mt-1 text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ {labels.showAllFiles(files.length)}+ </button>+ </li>+ )}+ </ul>+ );+}++function AreaFileRow({+ file,+ dir,+ base,+ LinkComponent,+ hotspot,+}: {+ file: KnowledgeAreaFile;+ dir: string;+ base?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ hotspot: string;+}) {+ const A = LinkComponent ?? "a";+ const name = <PathText path={dir ? file.path.slice(dir.length + 1) : file.path} />;+ return (+ <li className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5 py-1">+ <span className="flex min-w-0 items-baseline gap-2">+ {base ? (+ <A href={fileEntityPath(base, file.path)} className="group min-w-0 no-underline" title={file.path}>+ {name}+ </A>+ ) : (+ name+ )}+ <FileMarks file={file} hotspot={hotspot} />+ </span>+ {file.note && (+ <span className="font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">{file.note}</span>+ )}+ </li>+ );+}++/** Areas in order, the first `initial` shown, the rest behind one button. */+export function KnowledgeAreaList<T>({+ areas,+ keyOf,+ renderArea,+ initial = 8,+ label,+ showAllLabel,+}: {+ areas: readonly T[];+ keyOf: (area: T) => string;+ renderArea: (area: T, index: number) => React.ReactNode;+ initial?: number;+ /** Accessible name of the list, e.g. "Areas at risk". */+ label: string;+ /** "Show all N directories". */+ showAllLabel: (count: number) => string;+}) {+ const [limit, setLimit] = React.useState(initial);+ const shown = areas.slice(0, limit);+ return (+ <div className="flex flex-col gap-2">+ <ul aria-label={label} className="flex flex-col border-t border-[var(--color-border-default)]">+ {shown.map((a, i) => (+ <React.Fragment key={keyOf(a)}>{renderArea(a, i)}</React.Fragment>+ ))}+ </ul>+ {areas.length > shown.length && (+ <button+ type="button"+ onClick={() => setLimit(areas.length)}+ className="self-start text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ {showAllLabel(areas.length)}+ </button>+ )}+ </div>+ );+}diff --git a/packages/ui/src/owners/knowledge-coverage.ts b/packages/ui/src/owners/knowledge-coverage.tsnew file mode 100644index 000000000..0345bf3ae--- /dev/null+++ b/packages/ui/src/owners/knowledge-coverage.ts@@ -0,0 +1,69 @@+/**+ * Knowledge coverage: of the code changed in the last 90 days, how much has+ * two or more people who know it (bus factor 2 or more). Files with no+ * indexed history (bus factor 0) are left out of both sides. Weighted by+ * lines of code; when no changing file has a measured size, by file count.+ *+ * Pure and O(files). The single-holder changing files come back grouped by+ * directory for the "spread the knowledge" prompt.+ */++import type { KnowledgeMatrix } from "@repowise-dev/types/owners";+import { isSingleOwner } from "./knowledge-files";+import { singleHolderFiles, type KnowledgeRiskArea } from "./knowledge-risks";++/**+ * At or above this share the lede reads as good news (calm green); below it,+ * plain. A product judgement, not a health band: half the moving code with a+ * second reader is where a single absence stops stalling most work.+ */+export const WELL_SHARED_MIN = 0.5;++export interface KnowledgeCoverage {+ /** Changing files with indexed history. */+ files: number;+ /** Of those, files two or more people hold. */+ sharedFiles: number;+ nloc: number;+ sharedNloc: number;+ /** Shared share (0-1) by `basis`; null when no file with history changed. */+ share: number | null;+ basis: "nloc" | "files";+ /** Changing files one person holds, by directory, most severe first. */+ singleHolderAreas: KnowledgeRiskArea[];+ singleHolderFiles: number;+}++/** Two or more people hold it; a file with no history is neither shared nor single. */+export function isSharedKnowledge(busFactor: number): boolean {+ return busFactor > 0 && !isSingleOwner(busFactor);+}++export function knowledgeCoverage(matrix: KnowledgeMatrix): KnowledgeCoverage {+ let files = 0;+ let sharedFiles = 0;+ let nloc = 0;+ let sharedNloc = 0;+ for (const row of matrix.files) {+ if (!row[8] || row[5] <= 0) continue;+ files += 1;+ nloc += row[2];+ if (isSharedKnowledge(row[5])) {+ sharedFiles += 1;+ sharedNloc += row[2];+ }+ }+ const basis = nloc > 0 ? "nloc" : "files";+ const share = files === 0 ? null : basis === "nloc" ? sharedNloc / nloc : sharedFiles / files;+ const single = singleHolderFiles(matrix, (f) => f.changed90d);+ return {+ files,+ sharedFiles,+ nloc,+ sharedNloc,+ share,+ basis,+ singleHolderAreas: single.areas,+ singleHolderFiles: single.files.length,+ };+}diff --git a/packages/ui/src/owners/knowledge-files.ts b/packages/ui/src/owners/knowledge-files.tsnew file mode 100644index 000000000..0fc42c5be--- /dev/null+++ b/packages/ui/src/owners/knowledge-files.ts@@ -0,0 +1,119 @@+/**+ * Shared readings over the knowledge matrix: who a row index is, whether a+ * file has one author, whether its health is weak, and how areas sort. The+ * off-boarding simulation, the knowledge-risk grouping and the person page all+ * read files through these, so a file means the same thing on every surface.+ *+ * Pure, no React. An "area" here is a file's own directory, the unit the+ * matrix already indexes, so grouping costs nothing.+ */++import { bandForScore, isWeakHealthBand } from "@repowise-dev/types/health";+import {+ knowledgeMatrixPath,+ type KnowledgeMatrix,+ type KnowledgeMatrixFile,+} from "@repowise-dev/types/owners";++export interface KnowledgePerson {+ key: string;+ name: string;+ email: string | null;+}++/** "A", "A and B", "A, B and C": people named in a sentence. */+export function joinNames(names: readonly string[]): string {+ if (names.length <= 1) return names[0] ?? "";+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;+}++/** The person at a matrix author index. */+export function personAt(matrix: KnowledgeMatrix, index: number): KnowledgePerson {+ const a = matrix.authors[index];+ return a+ ? { key: a.key, name: a.name || a.email || a.key, email: a.email }+ : { key: String(index), name: "unknown", email: null };+}++/**+ * One author holds the file: the indexer's bus factor is exactly 1. A bus+ * factor of 0 means no history was indexed, which is not a risk.+ */+export function isSingleOwner(busFactor: number): boolean {+ return busFactor === 1;+}++/** Weak health by the canonical bands; a file without a score is not weak. */+export function isLowHealth(score: number | null): boolean {+ return score != null && isWeakHealthBand(bandForScore(score));+}++/** The facts every list row shows about one matrix file. */+export interface KnowledgeFileFacts {+ path: string;+ dir: string;+ nloc: number;+ healthScore: number | null;+ isHotspot: boolean;+ lowHealth: boolean;+ /** A commit in the 90 days before HEAD. */+ changed90d: boolean;+}++export function fileFacts(matrix: KnowledgeMatrix, file: KnowledgeMatrixFile): KnowledgeFileFacts {+ return {+ path: knowledgeMatrixPath(matrix.dirs, file),+ dir: matrix.dirs[file[0]] ?? "",+ nloc: file[2],+ healthScore: file[3],+ isHotspot: file[4],+ lowHealth: isLowHealth(file[3]),+ changed90d: file[8],+ };+}++/** Hotspot and weak health together first, then either, then by size. */+export function compareFileFacts(a: KnowledgeFileFacts, b: KnowledgeFileFacts): number {+ const weight = (f: KnowledgeFileFacts) => Number(f.isHotspot) + Number(f.lowHealth);+ return weight(b) - weight(a) || b.nloc - a.nloc || a.path.localeCompare(b.path);+}++/** Areas with the most severe files first, then the most files, then the most code. */+export function compareAreas(+ a: { severe: number; fileCount: number; nloc: number; dir: string },+ b: { severe: number; fileCount: number; nloc: number; dir: string },+): number {+ return (+ b.severe - a.severe || b.fileCount - a.fileCount || b.nloc - a.nloc || a.dir.localeCompare(b.dir)+ );+}++/**+ * The person most often named across `picks`, ties broken by the code they+ * cover. Used to suggest one name per area rather than one per file.+ */+export function mostNamed(+ picks: Iterable<{ person: KnowledgePerson; nloc: number }>,+): { person: KnowledgePerson; files: number } | null {+ type Tally = { person: KnowledgePerson; files: number; nloc: number };+ const tally = new Map<string, Tally>();+ for (const { person, nloc } of picks) {+ const t = tally.get(person.key) ?? { person, files: 0, nloc: 0 };+ t.files += 1;+ t.nloc += nloc;+ tally.set(person.key, t);+ }+ const ranked = [...tally.values()].sort((a, b) => b.files - a.files || b.nloc - a.nloc);+ return ranked[0] ? { person: ranked[0].person, files: ranked[0].files } : null;+}++/** Items bucketed by their directory, buckets in first-seen order. */+export function groupByDir<T extends { dir: string }>(items: readonly T[]): Map<string, T[]> {+ const byDir = new Map<string, T[]>();+ for (const item of items) {+ const bucket = byDir.get(item.dir);+ if (bucket) bucket.push(item);+ else byDir.set(item.dir, [item]);+ }+ return byDir;+}diff --git a/packages/ui/src/owners/knowledge-loss-view.tsx b/packages/ui/src/owners/knowledge-loss-view.tsxnew file mode 100644index 000000000..bfe2aa367--- /dev/null+++ b/packages/ui/src/owners/knowledge-loss-view.tsx@@ -0,0 +1,198 @@+"use client";++import * as React from "react";+import type { KnowledgeMatrix, OwnersSummary } from "@repowise-dev/types/owners";+import { AiPromptButton } from "../health/ai-prompt-button";+import { useAiPromptAction } from "../health/ai-prompt-action";+import { RowPromptAction } from "../health/row-prompt-action";+import { formatRelativeTimeOrNull } from "../lib/format";+import { CleanState } from "../shared/clean-state";+import { quietOwnerExposure, quietOwnersTogether, type QuietOwnerExposure } from "./knowledge-loss";+import { ownershipLabels, type OwnershipLabels } from "./labels";+import { OffboardingAreas } from "./offboarding-result";+import { handoverPromptRequest } from "./prompt-requests";+import { OwnerAvatar } from "./owner-avatar";++export interface KnowledgeLossViewProps {+ matrix: KnowledgeMatrix;+ summary: OwnersSummary;+ /** Person page for an owner key. */+ hrefForPerson?: ((key: string) => string) | undefined;+ /** The off-boarding what-if for one owner key. */+ hrefForScenario?: ((key: string) => string) | undefined;+ base?: string | undefined;+ repoName?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels?: Partial<OwnershipLabels> | undefined;+}++/**+ * Code that still changes while its main author has gone quiet. Each quiet+ * owner reads as an off-boarding that already happened, over the files that+ * changed in the last 90 days: what lost its majority author, and who is left+ * to carry it. The section's one filled prompt plans all of them together.+ */+export function KnowledgeLossView({+ matrix,+ summary,+ hrefForPerson,+ hrefForScenario,+ base,+ repoName,+ LinkComponent,+ labels: overrides,+}: KnowledgeLossViewProps) {+ const labels = React.useMemo(() => ownershipLabels(overrides), [overrides]);+ const rows = React.useMemo(+ () => quietOwnerExposure(matrix, summary.quiet_owners),+ [matrix, summary.quiet_owners],+ );+ const together = React.useMemo(+ () => quietOwnersTogether(matrix, summary.quiet_owners),+ [matrix, summary.quiet_owners],+ );+ const { openPrompt, promptModal } = useAiPromptAction();++ if (summary.quiet_owners_total === 0) {+ return (+ <CleanState+ align="start"+ title={labels.lossCleanTitle(summary.activity_window_days)}+ description={labels.lossCleanDescription(summary.people, summary.owned_files)}+ />+ );+ }++ return (+ <div className="flex flex-col gap-4">+ <p className="max-w-[68ch] text-[15px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {labels.lossIntro(summary.quiet_owners_total, summary.activity_window_days, rows.length)}+ </p>+ {together.totals.atRiskFiles > 0 ? (+ <AiPromptButton+ className="self-start"+ onClick={() => openPrompt(handoverPromptRequest(together, together.areas, labels, repoName))}+ label={labels.agentPrompt}+ />+ ) : (+ <CleanState+ align="start"+ title={labels.lossCarriedTitle}+ description={labels.lossCarriedDescription(summary.activity_window_days, summary.quiet_owners_total)}+ />+ )}+ <ul aria-label={labels.lossListLabel} className="flex flex-col border-t border-[var(--color-border-default)]">+ {rows.map((row) => (+ <QuietOwnerRow+ key={row.owner.key}+ row={row}+ onPrompt={(areas) => openPrompt(handoverPromptRequest(row.result, areas, labels, repoName))}+ labels={labels}+ hrefForPerson={hrefForPerson}+ hrefForScenario={hrefForScenario}+ base={base}+ LinkComponent={LinkComponent}+ />+ ))}+ </ul>+ {promptModal}+ </div>+ );+}++/** One quiet owner in words: when they last committed, what of theirs changed, what loses its majority. */+function quietOwnerSentence(+ { owner, result: { totals } }: QuietOwnerExposure,+ last: string | null,+ labels: OwnershipLabels,+): string {+ return [+ last ? labels.lossLastCommit(last) : null,+ labels.lossChanging(owner.changing_files_owned, owner.files_owned),+ totals.atRiskFiles > 0 ? labels.lossAtRisk(totals.atRiskFiles, totals.severeFiles) : labels.lossNoneAtRisk,+ ]+ .filter(Boolean)+ .join(" ");+}++function QuietOwnerRow({+ row,+ onPrompt,+ hrefForPerson,+ hrefForScenario,+ base,+ LinkComponent,+ labels,+}: {+ row: QuietOwnerExposure;+ onPrompt: (areas: QuietOwnerExposure["result"]["areas"]) => void;+ hrefForPerson?: ((key: string) => string) | undefined;+ hrefForScenario?: ((key: string) => string) | undefined;+ base?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels: OwnershipLabels;+}) {+ const [open, setOpen] = React.useState(false);+ const A = LinkComponent ?? "a";+ const { owner, result } = row;+ const { totals } = result;+ const panelId = React.useId();+ const personHref = hrefForPerson?.(owner.key);++ return (+ <li className="group/row border-b border-[var(--color-border-default)] py-3">+ <div className="flex flex-wrap items-start gap-x-3 gap-y-2">+ <OwnerAvatar name={owner.name} size="md" />+ <div className="min-w-0 flex-1">+ {personHref ? (+ <A href={personHref} className="font-medium text-[var(--color-text-primary)] no-underline hover:text-[var(--color-accent-primary)]">+ {owner.name}+ </A>+ ) : (+ <span className="font-medium text-[var(--color-text-primary)]">{owner.name}</span>+ )}+ <p className="text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {quietOwnerSentence(row, formatRelativeTimeOrNull(owner.last_commit_at), labels)}+ </p>+ <div className="mt-1 flex flex-wrap gap-x-4 text-xs">+ {totals.atRiskFiles > 0 && (+ <button+ type="button"+ aria-expanded={open}+ aria-controls={panelId}+ onClick={() => setOpen((o) => !o)}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ {labels.lossDirectories(open, result.areas.length)}+ </button>+ )}+ {hrefForScenario && (+ <A href={hrefForScenario(owner.key)} className="text-[var(--color-accent-primary)] hover:underline">+ {labels.openInOffboarding}+ </A>+ )}+ </div>+ </div>+ {totals.atRiskFiles > 0 && (+ <RowPromptAction+ onClick={() => onPrompt(result.areas)}+ label={labels.promptForGroup(totals.atRiskFiles)}+ subject={owner.name}+ />+ )}+ </div>+ {open && (+ <div id={panelId} className="mt-3 pl-11">+ <OffboardingAreas+ areas={result.areas}+ onPrompt={(area) => onPrompt([area])}+ labels={labels}+ base={base}+ LinkComponent={LinkComponent}+ initial={5}+ />+ </div>+ )}+ </li>+ );+}diff --git a/packages/ui/src/owners/knowledge-loss.ts b/packages/ui/src/owners/knowledge-loss.tsnew file mode 100644index 000000000..33a5b496f--- /dev/null+++ b/packages/ui/src/owners/knowledge-loss.ts@@ -0,0 +1,50 @@+/**+ * Knowledge loss: people who have gone quiet while still owning code that+ * changes. Each one is read as a single-person off-boarding over the files+ * changed in the last 90 days, since in effect they already left: what code+ * still moving lost its majority author, and who stays to take it.+ *+ * Pure. The quiet list is capped server side (25), so this is at most 25+ * passes over the matrix.+ */++import type { KnowledgeMatrix, QuietOwner } from "@repowise-dev/types/owners";+import { simulateOffboarding, type OffboardingResult } from "./offboarding";++export interface QuietOwnerExposure {+ owner: QuietOwner;+ result: OffboardingResult;+}++/** Every quiet owner gone at once, over changing code: the section-level handover. */+export function quietOwnersTogether(+ matrix: KnowledgeMatrix,+ owners: readonly QuietOwner[],+ threshold?: number,+): OffboardingResult {+ return simulateOffboarding(+ matrix,+ owners.map((o) => o.key),+ threshold,+ { changedOnly: true },+ );+}++/** Quiet owners with their exposure, the most severe files first. */+export function quietOwnerExposure(+ matrix: KnowledgeMatrix,+ owners: readonly QuietOwner[],+ threshold?: number,+): QuietOwnerExposure[] {+ return owners+ .map((owner) => ({+ owner,+ result: simulateOffboarding(matrix, [owner.key], threshold, { changedOnly: true }),+ }))+ .sort(+ (a, b) =>+ b.result.totals.severeFiles - a.result.totals.severeFiles ||+ b.result.totals.atRiskFiles - a.result.totals.atRiskFiles ||+ b.owner.changing_files_owned - a.owner.changing_files_owned,+ );+}diff --git a/packages/ui/src/owners/knowledge-risks-view.tsx b/packages/ui/src/owners/knowledge-risks-view.tsxnew file mode 100644index 000000000..3f02791ed--- /dev/null+++ b/packages/ui/src/owners/knowledge-risks-view.tsx@@ -0,0 +1,82 @@+"use client";++import * as React from "react";+import type { KnowledgeMatrix } from "@repowise-dev/types/owners";+import { AiPromptButton } from "../health/ai-prompt-button";+import { useAiPromptAction } from "../health/ai-prompt-action";+import { CleanState } from "../shared/clean-state";+import { KnowledgeAreaList, KnowledgeAreaRow } from "./knowledge-area-list";+import { knowledgeRisks, type KnowledgeRiskArea } from "./knowledge-risks";+import { ownershipLabels, type OwnershipLabels } from "./labels";+import { spreadPromptRequest } from "./prompt-requests";++export interface KnowledgeRisksViewProps {+ matrix: KnowledgeMatrix;+ base?: string | undefined;+ repoName?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels?: Partial<OwnershipLabels> | undefined;+}++const pct = (share: number) => `${Math.round(share * 100)}%`;++function areaSummary(area: KnowledgeRiskArea, labels: OwnershipLabels): string {+ const who =+ area.holders === 1 && area.holder+ ? labels.risksOneHolder(area.holder.person.name)+ : labels.risksManyHolders(area.holders, area.holder?.person.name ?? null, area.holder?.files ?? 0);+ return area.severe > 0 ? `${who}. ${labels.risksSevere(area.severe)}.` : `${who}.`;+}++/**+ * Where one person holds code that matters now: single-author files that are+ * hotspots or in weak health, by directory. The action is a plan to spread+ * that knowledge, handed to the reader's agent.+ */+export function KnowledgeRisksView({ matrix, base, repoName, LinkComponent, labels: overrides }: KnowledgeRisksViewProps) {+ const labels = React.useMemo(() => ownershipLabels(overrides), [overrides]);+ const risks = React.useMemo(() => knowledgeRisks(matrix), [matrix]);+ const { openPrompt, promptModal } = useAiPromptAction();+ // One area from its row, or every area (ranked, the prompt lists the first few) from the section.+ const promptFor = React.useCallback(+ (areas: readonly KnowledgeRiskArea[]) => openPrompt(spreadPromptRequest(areas, labels, { repoName })),+ [openPrompt, labels, repoName],+ );++ if (risks.files === 0) {+ return (+ <CleanState+ align="start"+ title={labels.risksCleanTitle(risks.trackedFiles)}+ description={labels.risksCleanDescription}+ />+ );+ }++ return (+ <div className="flex flex-col gap-4">+ <p className="max-w-[68ch] text-[15px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {labels.risksIntro(risks.files, risks.hotspots, risks.lowHealth, risks.areas.length)}+ </p>+ <AiPromptButton className="self-start" onClick={() => promptFor(risks.areas)} label={labels.agentPrompt} />+ <KnowledgeAreaList+ label={labels.risksListLabel}+ showAllLabel={labels.showAllDirectories}+ areas={risks.areas}+ keyOf={(a) => a.dir}+ renderArea={(area) => (+ <KnowledgeAreaRow+ dir={area.dir}+ summary={areaSummary(area, labels)}+ files={area.files.map((f) => ({ ...f, note: `${f.holder.name} ${pct(f.holder.share)}` }))}+ onPrompt={() => promptFor([area])}+ base={base}+ LinkComponent={LinkComponent}+ labels={labels}+ />+ )}+ />+ {promptModal}+ </div>+ );+}diff --git a/packages/ui/src/owners/knowledge-risks.ts b/packages/ui/src/owners/knowledge-risks.tsnew file mode 100644index 000000000..ad8294da7--- /dev/null+++ b/packages/ui/src/owners/knowledge-risks.ts@@ -0,0 +1,108 @@+/**+ * Knowledge risks: files one person holds (bus factor 1) that also matter+ * right now, because they are hotspots or in a weak health band, grouped by+ * directory. Each file names its holder and the next author, the natural+ * person to spread the knowledge to.+ *+ * Pure and O(files). Holder is the file's strongest commit author, the same+ * measure the bus factor counts, not the blame owner.+ */++import type { KnowledgeMatrix, KnowledgeMatrixFile } from "@repowise-dev/types/owners";+import {+ compareAreas,+ compareFileFacts,+ fileFacts,+ groupByDir,+ isSingleOwner,+ mostNamed,+ personAt,+ type KnowledgeFileFacts,+ type KnowledgePerson,+} from "./knowledge-files";++export interface KnowledgeRiskFile extends KnowledgeFileFacts {+ holder: KnowledgePerson & { share: number };+ /** The next author, if anyone else has committed. */+ second: (KnowledgePerson & { share: number }) | null;+ /** Hotspot and weak health together. */+ both: boolean;+}++export interface KnowledgeRiskArea {+ dir: string;+ files: KnowledgeRiskFile[];+ fileCount: number;+ /** Files that are both a hotspot and weak health. */+ severe: number;+ nloc: number;+ /** Who holds most of these files. */+ holder: { person: KnowledgePerson; files: number } | null;+ /** How many different people hold them. */+ holders: number;+}++export interface KnowledgeRisks {+ areas: KnowledgeRiskArea[];+ files: number;+ hotspots: number;+ lowHealth: number;+ /** Code files the matrix covers, for the clean state's scope. */+ trackedFiles: number;+}++/** The file as held by one person, or null when it has a second author or `keep` passes on it. */+function riskFile(+ matrix: KnowledgeMatrix,+ row: KnowledgeMatrixFile,+ keep: (facts: KnowledgeFileFacts) => boolean,+): KnowledgeRiskFile | null {+ const [top, next] = row[7];+ if (!isSingleOwner(row[5]) || !top) return null;+ const facts = fileFacts(matrix, row);+ if (!keep(facts)) return null;+ return {+ ...facts,+ holder: { ...personAt(matrix, top[0]), share: top[1] },+ second: next ? { ...personAt(matrix, next[0]), share: next[1] } : null,+ both: facts.isHotspot && facts.lowHealth,+ };+}++function riskArea(dir: string, files: KnowledgeRiskFile[]): KnowledgeRiskArea {+ files.sort(compareFileFacts);+ return {+ dir,+ files,+ fileCount: files.length,+ severe: files.filter((f) => f.both).length,+ nloc: files.reduce((s, f) => s + f.nloc, 0),+ holder: mostNamed(files.map((f) => ({ person: f.holder, nloc: f.nloc }))),+ holders: new Set(files.map((f) => f.holder.key)).size,+ };+}++/**+ * Single-holder files that pass `keep`, grouped by directory, most severe+ * first. Knowledge risks keeps hotspots and weak files; knowledge coverage+ * keeps code changed lately.+ */+export function singleHolderFiles(+ matrix: KnowledgeMatrix,+ keep: (facts: KnowledgeFileFacts) => boolean,+): { files: KnowledgeRiskFile[]; areas: KnowledgeRiskArea[] } {+ const files = matrix.files.flatMap((row) => riskFile(matrix, row, keep) ?? []);+ const areas = Array.from(groupByDir(files), ([dir, group]) => riskArea(dir, group)).sort(compareAreas);+ return { files, areas };+}++export function knowledgeRisks(matrix: KnowledgeMatrix): KnowledgeRisks {+ const { files, areas } = singleHolderFiles(matrix, (f) => f.isHotspot || f.lowHealth);+ return {+ areas,+ files: files.length,+ hotspots: files.filter((f) => f.isHotspot).length,+ lowHealth: files.filter((f) => f.lowHealth).length,+ trackedFiles: matrix.files.length,+ };+}diff --git a/packages/ui/src/owners/labels.ts b/packages/ui/src/owners/labels.tsnew file mode 100644index 000000000..2cb780012--- /dev/null+++ b/packages/ui/src/owners/labels.ts@@ -0,0 +1,369 @@+/**+ * Every string the Ownership page's views render, so a host can translate+ * them. The views take `labels?: Partial<OwnershipLabels>` and fall back to+ * these English defaults; the web app passes en and zh-CN from its messages.+ * Agent prompt text stays English: it is written for the agent, not the page.+ */++import { AGENT_PROMPT_LABEL, bulkAgentPromptLabel } from "../health/ai-prompt-action";++const s = (n: number, one: string, many: string) => `${n.toLocaleString()} ${n === 1 ? one : many}`;++export interface OwnershipLabels {+ // Shared+ agentPrompt: string;+ /** A group's prompt: "Copy prompt for these 4". */+ promptForGroup: (count: number) => string;+ repositoryRoot: string;+ hotspot: string;+ files: (count: number) => string;+ showAllFiles: (count: number) => string;+ showAllDirectories: (count: number) => string;+ noOtherAuthor: string;+ openInOffboarding: string;++ // Lede+ coverageLabel: string;+ coverageHint: (byLines: boolean, days: number) => string;+ coverageUnit: (byLines: boolean) => string;+ wellShared: string;+ coverageSentence: (pct: string, byLines: boolean, days: number) => string;+ singleHolderSentence: (single: number, files: number) => string;+ noChanges: (days: number) => string;+ spreadTitle: string;+ spreadDescription: (files: number) => string;+ readHotspots: string;+ readHotspotsUnit: (singleOwnerFiles: number) => string;+ readHotspotsWhy: string;+ readQuiet: string;+ readQuietUnit: (count: number) => string;+ readQuietWhy: (days: number) => string;+ readTruck: string;+ readTruckWhy: string;++ // Everyone table+ everyone: string;+ everyoneDescription: string;+ people: (count: number, withAutomation: boolean) => string;+ searchPlaceholder: string;+ searchLabel: string;+ showAutomation: (count: number) => string;+ noMatch: string;+ clearSearch: string;+ noPeople: string;+ noPeopleDescription: string;+ showAllPeople: (count: number, withAutomation: boolean) => string;+ loading: string;++ // Knowledge risks+ risksIntro: (files: number, hotspots: number, lowHealth: number, dirs: number) => string;+ risksCleanTitle: (files: number) => string;+ risksCleanDescription: string;+ risksOneHolder: (name: string) => string;+ risksManyHolders: (holders: number, name: string | null, files: number) => string;+ risksSevere: (count: number) => string;+ risksListLabel: string;++ // Knowledge loss+ lossIntro: (total: number, days: number, shown: number) => string;+ lossCleanTitle: (days: number) => string;+ lossCleanDescription: (people: number, files: number) => string;+ lossCarriedTitle: string;+ lossCarriedDescription: (days: number, quiet: number) => string;+ lossLastCommit: (when: string) => string;+ lossChanging: (changing: number, owned: number) => string;+ lossAtRisk: (files: number, severe: number) => string;+ lossNoneAtRisk: string;+ lossDirectories: (open: boolean, count: number) => string;+ lossListLabel: string;++ // Off-boarding+ leavingLabel: string;+ leavingPicker: string;+ thresholdLabel: (pct: number) => string;+ thresholdHelp: string;+ tryLabel: string;+ pickPrompt: string;+ pickerPlaceholder: string;+ removePerson: (name: string) => string;+ selectedPeople: string;+ unknownPeople: string;+ nothingDependsTitle: (names: string) => string;+ nothingDependsDescription: (threshold: string, files: number, names: string) => string;+ noShareTitle: (names: string, count: number) => string;+ noShareDescription: string;+ resultSentence: (p: {+ names: string;+ files: number;+ threshold: string;+ codeShare: string;+ severe: number;+ kept: number;+ }) => string;+ statAtRisk: string;+ statHotspots: string;+ statHotspotsHint: string;+ statShare: string;+ statShareHint: (nloc: number, files: number) => string;+ statDirectories: string;+ heir: (name: string, files: number, of: number) => string;+ noHeir: string;+ heirSevere: (count: number) => string;+ handoverTitle: string;+ handoverDescription: (files: number, names: string) => string;+ offboardingListLabel: string;+ underOnePercent: string;++ // Person page+ dependsTitle: string;+ dependsDescription: string;+ ownershipLink: string;+ filesCarryTitle: string;+ filesCarryHint: (shown: number, touched: number) => string;+ filesCarryDescription: (soleCarried: number, shown: number) => string;+ commitMixTitle: string;+ commitMixDescription: (total: number) => string;+ commitMixEmptyTitle: string;+ commitMixEmptyDescription: string;+ commitMixBarLabel: string;+ creditTitle: string;+ creditLink: string;+ creditSentence: (days: number, files: number, findings: number) => string;+ activityLabel: string;+ activeLine: (commits: number, floor: boolean) => string;+ quietLine: string;+ emailLabel: string;+ aliasesLabel: string;+ footprintTitle: string;+ footprintDescription: string;+ footprintEmptyTitle: string;+ footprintEmptyDescription: string;+ footprintBarLabel: string;+ footprintDetail: (files: number, pct: number) => string;+ relationshipsTitle: string;+ relationshipsDescription: string;+ relationshipsEmptyTitle: string;+ relationshipsEmptyDescription: string;+ relationshipsAlone: string;+ relationshipsNext: (others: number, pct: string) => string;+ relationshipsOthers: (others: number) => string;+ partnerLine: (files: number, pct: string) => string;+ unknownName: string;+ fileTableEmptyTitle: string;+ fileTableEmptyDescription: string;+ colFile: string;+ colCommits90d: string;+ colChurn: string;+ colChurnHint: string;+ colTheirCommits: string;+ colTheirCommitsHint: string;+ colTouched: string;+ soleCarriedTitle: string;+ fileMeta: (commits: number, churn: number, ownPct: string, touched: string) => string;++ // People table+ colContributor: string;+ colFilesOwned: string;+ colFilesOwnedHint: string;+ colHotspots: string;+ colHotspotsHint: string;+ colSoleOwner: string;+ colSoleOwnerHint: string;+ colDeadLines: string;+ colDeadLinesHint: string;+ colLastTouched: string;+ kindPerson: string;+ kindBot: string;+ kindAgent: string;+ soleInactiveTitle: string;+ atLeastTitle: string;+}++export const DEFAULT_OWNERSHIP_LABELS: OwnershipLabels = {+ agentPrompt: AGENT_PROMPT_LABEL,+ promptForGroup: bulkAgentPromptLabel,+ repositoryRoot: "(repository root)",+ hotspot: "Hotspot",+ files: (n) => s(n, "file", "files"),+ showAllFiles: (n) => `Show all ${n.toLocaleString()} files`,+ showAllDirectories: (n) => `Show all ${n.toLocaleString()} directories`,+ noOtherAuthor: "no other author",+ openInOffboarding: "Open in off-boarding",++ coverageLabel: "Knowledge coverage",+ coverageHint: (byLines, days) =>+ `Share ${byLines ? "of the code" : "of the files"} changed in the last ${days} days in files two or more people hold (bus factor 2 or more), ${byLines ? "weighted by lines of code" : "by file count"}. Files with no indexed history are left out.`,+ coverageUnit: (byLines) => `${byLines ? "of the code" : "of the files"} changed lately`,+ wellShared: "Well shared",+ coverageSentence: (pct, byLines, days) =>+ `${pct} ${byLines ? "of the code" : "of the files"} changed in the last ${days} days${byLines ? ", by lines," : ""} has two or more people who know it.`,+ singleHolderSentence: (single, files) =>+ `${single.toLocaleString()} of the ${s(files, "changing file", "changing files")} ${single === 1 ? "has" : "have"} one main author; your agent can plan how a second person learns them.`,+ noChanges: (days) =>+ `No code with history changed in the last ${days} days, so there is no moving code to measure knowledge coverage on.`,+ spreadTitle: "Spread the knowledge",+ spreadDescription: (n) => `A plan for a second person to learn ${s(n, "file", "files")} one person holds.`,+ readHotspots: "Single-author hotspots",+ readHotspotsUnit: (n) => `of ${s(n, "single-author file", "single-author files")}`,+ readHotspotsWhy: "Busy files only one person has written. The cheapest place to get a second reader.",+ readQuiet: "Quiet owners of changing code",+ readQuietUnit: (n) => (n === 1 ? "person" : "people"),+ readQuietWhy: (days) => `No commit in ${days} days, yet files they own changed in that time.`,+ readTruck: "Fewest people holding half the owned files",+ readTruckWhy: "The truck factor. Open the off-boarding view to see what depends on them.",++ everyone: "Everyone",+ everyoneDescription:+ "A dot marks sole-owned files held by someone who has stopped committing, so a clean column means nothing to chase.",+ people: (n, all) => (all ? s(n, "contributor", "contributors") : s(n, "person", "people")),+ searchPlaceholder: "Filter by name or email…",+ searchLabel: "Filter people by name or email",+ showAutomation: (n) => `Show ${n.toLocaleString()} bot and agent ${n === 1 ? "identity" : "identities"}`,+ noMatch: "Nobody matches this search",+ clearSearch: "Clear search",+ noPeople: "No people yet",+ noPeopleDescription: "People land with the first git index.",+ showAllPeople: (n, all) => `Show all ${all ? s(n, "contributor", "contributors") : s(n, "person", "people")}`,+ loading: "Loading…",++ risksIntro: (files, hotspots, lowHealth, dirs) =>+ `${s(files, "file has", "files have")} one author and matter right now: ${hotspots.toLocaleString()} ${hotspots === 1 ? "is a hotspot" : "are hotspots"} and ${lowHealth.toLocaleString()} ${lowHealth === 1 ? "is" : "are"} in weak health, across ${s(dirs, "directory", "directories")}. Hand them to your agent for a plan to get a second person reading each one.`,+ risksCleanTitle: (files) =>+ `Every hotspot and weak file has a second author, across ${files.toLocaleString()} files`,+ risksCleanDescription: "Knowledge here is shared: no busy or weak file depends on a single person's history.",+ risksOneHolder: (name) => `${name} wrote nearly all of it`,+ risksManyHolders: (holders, name, files) =>+ `${holders.toLocaleString()} people each hold their own files${name ? `, ${name} the most (${files.toLocaleString()})` : ""}`,+ risksSevere: (n) => `${n.toLocaleString()} ${n === 1 ? "is" : "are"} both a hotspot and in weak health`,+ risksListLabel: "Directories with knowledge held by one person",++ lossIntro: (total, days, shown) =>+ `${s(total, "person has", "people have")} not committed in ${days} days but still own files that changed in that time. Each row shows which of the files that changed lately would have no majority author without them, and who is best placed to pick each directory up.${total > shown ? ` Showing the ${shown.toLocaleString()} with the most changing code.` : ""}`,+ lossCleanTitle: (days) => `Everyone who owns changing code has committed in the last ${days} days`,+ lossCleanDescription: (people, files) =>+ `Across ${s(people, "person", "people")} and ${s(files, "owned file", "owned files")}, no file that changed lately belongs to someone who has stopped committing.`,+ lossCarriedTitle: "Others already carry the code that is still changing",+ lossCarriedDescription: (days, quiet) =>+ `Every file that changed in the last ${days} days keeps a majority of its commits with people who are still here, even without all ${s(quiet, "quiet owner", "quiet owners")}.`,+ lossLastCommit: (when) => `Last commit ${when}.`,+ lossChanging: (changing, owned) =>+ owned === 1+ ? "The one file they own changed lately."+ : `${changing.toLocaleString()} of the ${owned.toLocaleString()} files they own changed lately.`,+ lossAtRisk: (files, severe) =>+ `Without them, ${s(files, "file that changed lately has", "files that changed lately have")} no majority author left${severe > 0 ? `, ${severe.toLocaleString()} of them hotspots or in weak health` : ""}.`,+ lossNoneAtRisk: "The people who stay hold the majority of every changing file they worked on.",+ lossDirectories: (open, n) => `${open ? "Hide" : "Show"} ${s(n, "directory", "directories")}`,+ lossListLabel: "Quiet owners of changing code",++ leavingLabel: "If these people left",+ leavingPicker: "People leaving",+ thresholdLabel: (pct) => `At risk below ${pct}% kept`,+ thresholdHelp: "A file is at risk when the people who stay made less than this share of its commits.",+ tryLabel: "Try:",+ pickPrompt:+ "Pick one or more people to see which files would lose most of the knowledge behind them, and who is best placed to take each directory over. Nothing is saved; the scenario lives in the page address, so you can share it.",+ pickerPlaceholder: "Search by name or email…",+ removePerson: (name) => `Remove ${name}`,+ selectedPeople: "Selected people",+ unknownPeople:+ "None of the selected people appear in the indexed history. They may have committed under a different address; search for them by name.",+ nothingDependsTitle: (names) => `Nothing depends on ${names} alone`,+ nothingDependsDescription: (threshold, files, names) =>+ `The people who stay hold at least ${threshold} of the commits on all ${s(files, "file", "files")} ${names} worked on.`,+ noShareTitle: (names, count) => `${names} ${count === 1 ? "holds" : "hold"} no share of the indexed code`,+ noShareDescription: "No code file lists them among its top five authors.",+ resultSentence: ({ names, files, threshold, codeShare, severe, kept }) =>+ `Without ${names}, ${s(files, "file", "files")} would be left with authors holding under ${threshold} of the commits: ${codeShare} of the code${severe > 0 ? `, ${severe.toLocaleString()} of them hotspots or in weak health` : ""}. ${kept.toLocaleString()} more carry some of their history but keep at least ${threshold} with the people who stay.`,+ statAtRisk: "Files at risk",+ statHotspots: "Hotspots among them",+ statHotspotsHint: "At-risk files in the repository's high-churn band",+ statShare: "Share of code",+ statShareHint: (nloc, files) =>+ `Lines of code in at-risk files, of ${nloc.toLocaleString()} across ${s(files, "file", "files")}`,+ statDirectories: "Directories",+ heir: (name, files, of) =>+ `${name} could take over: the strongest remaining author on ${files.toLocaleString()} of ${of.toLocaleString()}`,+ noHeir: "Nobody who stays is among these files' main authors",+ heirSevere: (n) => `${n.toLocaleString()} ${n === 1 ? "is a hotspot or in" : "are hotspots or in"} weak health`,+ handoverTitle: "Plan the handover",+ handoverDescription: (files, names) => `A handover plan for ${s(files, "file", "files")} that depend on ${names}.`,+ offboardingListLabel: "Directories that would lose their majority author",+ underOnePercent: "under 1%",++ dependsTitle: "What depends on them",+ dependsDescription:+ "Files where this person made most of the commits, so the people who stay would hold under half of the history, and who is best placed to take each directory over.",+ ownershipLink: "Ownership",+ filesCarryTitle: "Files they carry",+ filesCarryHint: (shown, touched) => `${shown.toLocaleString()} of ${touched.toLocaleString()} touched`,+ filesCarryDescription: (sole, shown) =>+ `The files with the most commits attributed to this person. Churn is a percentile against every file in the repo. A dot marks a high-churn file they alone maintain and wrote at least 90% of the commits for${sole > 0 ? `: ${sole.toLocaleString()} of these ${shown.toLocaleString()}` : ", and none of these qualify"}.`,+ commitMixTitle: "What they commit",+ commitMixDescription: (total) =>+ `${s(total, "commit", "commits")} classified from the subject line, across every file this person has touched.`,+ commitMixEmptyTitle: "No classified commits yet",+ commitMixEmptyDescription: "Commit classification runs during indexing and fills this in on the next sync.",+ commitMixBarLabel: "Commits by type",+ creditTitle: "What they improved",+ creditLink: "See the commits",+ creditSentence: (days, files, findings) =>+ `In the last ${days} days their commits made ${s(files, "file", "files")} healthier and resolved ${s(findings, "finding", "findings")}.`,+ activityLabel: "Activity",+ activeLine: (commits, floor) =>+ `Active: ${floor ? "at least " : ""}${s(commits, "commit", "commits")} in the last 90 days`,+ quietLine: "Quiet: no commit in the last 90 days",+ emailLabel: "Email",+ aliasesLabel: "Also commits as",+ footprintTitle: "Where they work",+ footprintDescription:+ "Files they are the main owner of, by top-level directory. Share is the fraction of each directory's files where this person wrote most of the surviving lines.",+ footprintEmptyTitle: "No directory attribution yet",+ footprintEmptyDescription: "Ownership by directory appears after the next git sync.",+ footprintBarLabel: "Owned files by directory",+ footprintDetail: (files, pct) => `${s(files, "file", "files")} · ${pct}% theirs`,+ relationshipsTitle: "Who else works here",+ relationshipsDescription:+ "People editing the same files. Overlap is the share of this person's files the other has also committed to, so it reads as how much of their work is genuinely shared.",+ relationshipsEmptyTitle: "Nobody else has touched these files",+ relationshipsEmptyDescription: "Co-authorship appears once a second person commits to a file this person owns.",+ relationshipsAlone: "Nobody else shares a file with this person.",+ relationshipsNext: (others, pct) =>+ `The next closest of ${s(others, "other person", "other people")} overlaps on ${pct}%, so there is one natural reviewer here rather than a shortlist.`,+ relationshipsOthers: (others) => `${s(others, "other person shares", "other people share")} at least one file.`,+ partnerLine: (files, pct) => `${s(files, "shared file", "shared files")} · ${pct}% of this person's work overlaps theirs`,+ unknownName: "unknown",+ fileTableEmptyTitle: "No file attribution yet",+ fileTableEmptyDescription: "File-level ownership appears after the next git sync.",+ colFile: "File",+ colCommits90d: "Commits 90d",+ colChurn: "Churn",+ colChurnHint: "Percentile rank of this file's change frequency against every file in the repo",+ colTheirCommits: "Their commits",+ colTheirCommitsHint: "Share of this file's commits written by this person",+ colTouched: "Touched",+ soleCarriedTitle: "High-churn file this person alone maintains",+ fileMeta: (commits, churn, ownPct, touched) =>+ `${s(commits, "commit", "commits")} in 90d · churn ${churn} · ${ownPct} of its commits · touched ${touched}`,++ colContributor: "Contributor",+ colFilesOwned: "Files owned",+ colFilesOwnedHint: "Files where this person wrote most of the surviving lines",+ colHotspots: "Hotspots",+ colHotspotsHint: "Owned files that are also high-churn",+ colSoleOwner: "Sole owner",+ colSoleOwnerHint: "Owned files nobody else has touched",+ colDeadLines: "Dead lines",+ colDeadLinesHint: "Unreachable lines still attributed here",+ colLastTouched: "Last touched",+ kindPerson: "Person",+ kindBot: "Bot",+ kindAgent: "Coding agent",+ soleInactiveTitle: "Sole-owned files held by someone inactive for 90 days",+ atLeastTitle: "At least this many: the indexed commits stop inside the 90 days",+};++/** The defaults with a host's overrides on top. */+export function ownershipLabels(overrides?: Partial<OwnershipLabels>): OwnershipLabels {+ return overrides ? { ...DEFAULT_OWNERSHIP_LABELS, ...overrides } : DEFAULT_OWNERSHIP_LABELS;+}diff --git a/packages/ui/src/owners/offboarding-result.tsx b/packages/ui/src/owners/offboarding-result.tsxnew file mode 100644index 000000000..97635f438--- /dev/null+++ b/packages/ui/src/owners/offboarding-result.tsx@@ -0,0 +1,176 @@+"use client";++import * as React from "react";+import { AiPromptButton } from "../health/ai-prompt-button";+import { useAiPromptAction } from "../health/ai-prompt-action";+import { CleanState } from "../shared/clean-state";+import { StatRibbon } from "../stats/stat-ribbon";+import { KnowledgeAreaList, KnowledgeAreaRow } from "./knowledge-area-list";+import { joinNames } from "./knowledge-files";+import { ownershipLabels, type OwnershipLabels } from "./labels";+import type { OffboardingArea, OffboardingResult } from "./offboarding";+import { handoverPromptRequest } from "./prompt-requests";++/**+ * How an off-boarding result reads, wherever it is shown: the what-if on the+ * Ownership page, a quiet owner on Knowledge loss, and "What depends on+ * them" on a person page. Summary first, then directories, then files.+ */++const pct = (share: number) => `${Math.round(share * 100)}%`;++/** A share of the codebase; a sliver reads "under 1%", never "0%". */+const codeShare = (share: number, labels: OwnershipLabels) =>+ share > 0 && share < 0.005 ? labels.underOnePercent : pct(share);++function areaSummary(area: OffboardingArea, labels: OwnershipLabels): string {+ const heir = area.inheritor+ ? labels.heir(area.inheritor.person.name, area.inheritor.files, area.fileCount)+ : labels.noHeir;+ return area.severe > 0 ? `${heir}. ${labels.heirSevere(area.severe)}.` : `${heir}.`;+}++export interface OffboardingAreasProps {+ areas: readonly OffboardingArea[];+ onPrompt: (area: OffboardingArea) => void;+ labels: OwnershipLabels;+ base?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ initial?: number;+}++export function OffboardingAreas({ areas, onPrompt, labels, base, LinkComponent, initial }: OffboardingAreasProps) {+ return (+ <KnowledgeAreaList+ label={labels.offboardingListLabel}+ showAllLabel={labels.showAllDirectories}+ areas={areas}+ keyOf={(a) => a.dir}+ {...(initial ? { initial } : {})}+ renderArea={(area) => (+ <KnowledgeAreaRow+ dir={area.dir}+ summary={areaSummary(area, labels)}+ files={area.files.map((f) => ({+ ...f,+ note: f.inheritor ? `${f.inheritor.name} ${pct(f.inheritor.share)}` : labels.noOtherAuthor,+ }))}+ onPrompt={() => onPrompt(area)}+ base={base}+ LinkComponent={LinkComponent}+ labels={labels}+ />+ )}+ />+ );+}++export interface OffboardingResultViewProps {+ result: OffboardingResult;+ base?: string | undefined;+ repoName?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ /** Beside the primary prompt, e.g. "Open in off-boarding". */+ secondaryAction?: React.ReactNode;+ /** Directories shown before "Show all". */+ initialAreas?: number;+ labels?: Partial<OwnershipLabels> | undefined;+}++/** Nothing at risk: either nothing depends on them, or they hold no share at all. */+function NothingAtRisk({+ result,+ names,+ labels,+ children,+}: {+ result: OffboardingResult;+ names: string;+ labels: OwnershipLabels;+ children?: React.ReactNode;+}) {+ const touched = result.totals.touchedFiles;+ return (+ <CleanState+ align="start"+ title={touched > 0 ? labels.nothingDependsTitle(names) : labels.noShareTitle(names, result.leaving.length)}+ description={+ touched > 0 ? labels.nothingDependsDescription(pct(result.threshold), touched, names) : labels.noShareDescription+ }+ >+ {children}+ </CleanState>+ );+}++export function OffboardingResultView({+ result,+ base,+ repoName,+ LinkComponent,+ secondaryAction,+ initialAreas,+ labels: overrides,+}: OffboardingResultViewProps) {+ const labels = React.useMemo(() => ownershipLabels(overrides), [overrides]);+ const { openPrompt, promptModal } = useAiPromptAction();+ const { totals } = result;+ const names = joinNames(result.leaving.map((p) => p.name));+ const promptArea = React.useCallback(+ (area: OffboardingArea) => openPrompt(handoverPromptRequest(result, [area], labels, repoName)),+ [openPrompt, result, labels, repoName],+ );++ if (result.leaving.length === 0) {+ return <p className="text-[15px] leading-relaxed text-[var(--color-text-secondary)]">{labels.unknownPeople}</p>;+ }+ if (totals.atRiskFiles === 0) {+ return (+ <NothingAtRisk result={result} names={names} labels={labels}>+ {secondaryAction}+ </NothingAtRisk>+ );+ }++ const share = codeShare(totals.nlocShare, labels);+ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-3">+ <p className="max-w-[68ch] text-[15px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {labels.resultSentence({+ names,+ files: totals.atRiskFiles,+ threshold: pct(result.threshold),+ codeShare: share,+ severe: totals.severeFiles,+ kept: totals.touchedFiles - totals.atRiskFiles,+ })}+ </p>+ <div className="flex flex-wrap items-center gap-3">+ <AiPromptButton+ onClick={() => openPrompt(handoverPromptRequest(result, result.areas, labels, repoName))}+ label={labels.agentPrompt}+ />+ {secondaryAction}+ </div>+ </div>+ <StatRibbon+ stats={[+ { label: labels.statAtRisk, value: totals.atRiskFiles.toLocaleString() },+ { label: labels.statHotspots, value: totals.hotspots.toLocaleString(), hint: labels.statHotspotsHint },+ { label: labels.statShare, value: share, hint: labels.statShareHint(totals.totalNloc, totals.trackedFiles) },+ { label: labels.statDirectories, value: result.areas.length.toLocaleString() },+ ]}+ />+ <OffboardingAreas+ areas={result.areas}+ onPrompt={promptArea}+ labels={labels}+ base={base}+ LinkComponent={LinkComponent}+ {...(initialAreas ? { initial: initialAreas } : {})}+ />+ {promptModal}+ </div>+ );+}diff --git a/packages/ui/src/owners/offboarding-view.tsx b/packages/ui/src/owners/offboarding-view.tsxnew file mode 100644index 000000000..e631f4a2a--- /dev/null+++ b/packages/ui/src/owners/offboarding-view.tsx@@ -0,0 +1,129 @@+"use client";++import * as React from "react";+import type { KnowledgeMatrix } from "@repowise-dev/types/owners";+import { Slider } from "../ui/slider";+import { personAt, type KnowledgePerson } from "./knowledge-files";+import { ownershipLabels, type OwnershipLabels } from "./labels";+import { OFFBOARDING_THRESHOLD_RANGE, simulateOffboarding } from "./offboarding";+import { OffboardingResultView } from "./offboarding-result";+import { PeoplePicker } from "./people-picker";++export interface OffboardingScenario {+ leaving: string[];+ /** 0-1. */+ threshold: number;+}++export interface OffboardingViewProps {+ matrix: KnowledgeMatrix;+ scenario: OffboardingScenario;+ onScenarioChange: (next: OffboardingScenario) => void;+ /** One-click starting points, e.g. the people behind the truck factor. */+ suggestions?: { label: string; keys: string[] }[];+ base?: string | undefined;+ repoName?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels?: Partial<OwnershipLabels> | undefined;+}++/**+ * The off-boarding what-if: pick people, set how much of a file's history the+ * people who stay must hold, read what would be at risk. The scenario lives+ * with the host (the URL), so every view is a link.+ */+export function OffboardingView({+ matrix,+ scenario,+ onScenarioChange,+ suggestions = [],+ base,+ repoName,+ LinkComponent,+ labels: overrides,+}: OffboardingViewProps) {+ const labels = React.useMemo(() => ownershipLabels(overrides), [overrides]);+ const people = React.useMemo<KnowledgePerson[]>(+ () => matrix.authors.map((_, i) => personAt(matrix, i)),+ [matrix],+ );+ // The slider moves locally and commits on release, so a drag recomputes+ // and rewrites the URL once rather than on every step.+ const [draft, setDraft] = React.useState(Math.round(scenario.threshold * 100));+ React.useEffect(() => setDraft(Math.round(scenario.threshold * 100)), [scenario.threshold]);++ const result = React.useMemo(+ () => simulateOffboarding(matrix, scenario.leaving, scenario.threshold),+ [matrix, scenario.leaving, scenario.threshold],+ );++ return (+ <div className="flex flex-col gap-6">+ <div className="grid grid-cols-1 gap-6 md:grid-cols-[minmax(0,1fr)_260px]">+ <div className="flex min-w-0 flex-col gap-2">+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {labels.leavingLabel}+ </span>+ <PeoplePicker+ people={people}+ selected={scenario.leaving}+ onChange={(leaving) => onScenarioChange({ ...scenario, leaving })}+ label={labels.leavingPicker}+ placeholder={labels.pickerPlaceholder}+ removeLabel={labels.removePerson}+ selectedLabel={labels.selectedPeople}+ />+ {scenario.leaving.length === 0 && suggestions.length > 0 && (+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">+ {labels.tryLabel}+ {suggestions.map((s) => (+ <button+ key={s.label}+ type="button"+ onClick={() => onScenarioChange({ ...scenario, leaving: s.keys })}+ className="text-[var(--color-accent-primary)] hover:underline"+ >+ {s.label}+ </button>+ ))}+ </div>+ )}+ </div>+ <div className="flex flex-col gap-2">+ <span+ id="offboarding-threshold"+ className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"+ >+ {labels.thresholdLabel(draft)}+ </span>+ <Slider+ aria-labelledby="offboarding-threshold"+ min={OFFBOARDING_THRESHOLD_RANGE.min}+ max={OFFBOARDING_THRESHOLD_RANGE.max}+ step={OFFBOARDING_THRESHOLD_RANGE.step}+ value={[draft]}+ onValueChange={([v]) => v != null && setDraft(v)}+ onValueCommit={([v]) => v != null && onScenarioChange({ ...scenario, threshold: v / 100 })}+ />+ <span className="text-xs leading-relaxed text-[var(--color-text-tertiary)]">+ {labels.thresholdHelp}+ </span>+ </div>+ </div>++ {scenario.leaving.length === 0 ? (+ <p className="max-w-[62ch] text-[15px] leading-relaxed text-[var(--color-text-secondary)]">+ {labels.pickPrompt}+ </p>+ ) : (+ <OffboardingResultView+ result={result}+ base={base}+ repoName={repoName}+ LinkComponent={LinkComponent}+ labels={labels}+ />+ )}+ </div>+ );+}diff --git a/packages/ui/src/owners/offboarding.ts b/packages/ui/src/owners/offboarding.tsnew file mode 100644index 000000000..8424acf02--- /dev/null+++ b/packages/ui/src/owners/offboarding.ts@@ -0,0 +1,223 @@+/**+ * Off-boarding what-if: if these people left, which files would lose most of+ * the knowledge behind them, and who is left to take each area over.+ *+ * Rule (D4): a file is at risk when the authors who stay hold less than+ * `threshold` of its commits. The matrix lists each file's top five people;+ * anyone outside them holds less than the fifth share, so a leaver outside the+ * top five is read as holding none, and everything not lost counts as staying.+ * A file is severe when it is also a hotspot or in a weak health band.+ *+ * Pure and O(files) per call; the result type is the contract the Ownership+ * page, the person page and the area map's off-boarding lens all render.+ */++import type {+ KnowledgeMatrix,+ KnowledgeMatrixFile,+ KnowledgeMatrixShare,+} from "@repowise-dev/types/owners";+import {+ compareAreas,+ compareFileFacts,+ fileFacts,+ groupByDir,+ mostNamed,+ personAt,+ type KnowledgeFileFacts,+ type KnowledgePerson,+} from "./knowledge-files";++/** D4's default: at risk when the people who stay hold under half the commits. */+export const DEFAULT_OFFBOARDING_THRESHOLD = 0.5;++/** `at_risk`: the rule above. `severe`: at risk and a hotspot or weak health. */+export type OffboardingSeverity = "at_risk" | "severe";++export interface OffboardingFile extends KnowledgeFileFacts {+ /** Share of the file's commits the leavers made (0-1). */+ lostShare: number;+ /** 1 - lostShare. */+ remainingShare: number;+ severity: OffboardingSeverity;+ /** The strongest author who stays, with their share; null when nobody listed stays. */+ inheritor: (KnowledgePerson & { share: number }) | null;+}++export interface OffboardingArea {+ /** Directory; "" is the repository root. */+ dir: string;+ /** At-risk files, severe first, then by size. */+ files: OffboardingFile[];+ fileCount: number;+ severe: number;+ hotspots: number;+ nloc: number;+ /** Who most often stays as the strongest author here, and on how many of these files. */+ inheritor: { person: KnowledgePerson; files: number } | null;+}++export interface OffboardingTotals {+ /** Files with a share held by a leaver. */+ touchedFiles: number;+ atRiskFiles: number;+ severeFiles: number;+ hotspots: number;+ atRiskNloc: number;+ /** NLOC across the files in scope (every file, or only changing ones). */+ totalNloc: number;+ /** atRiskNloc / totalNloc, 0 when the matrix has no code. */+ nlocShare: number;+ /** Files in scope. */+ trackedFiles: number;+}++export interface OffboardingResult {+ /** The leavers found in the matrix, in the order asked. */+ leaving: KnowledgePerson[];+ threshold: number;+ totals: OffboardingTotals;+ /** Directories with at-risk files; together they hold every at-risk file once. */+ areas: OffboardingArea[];+}++/** Matrix indices of the leavers it knows, in the order asked. */+function leaverIndices(matrix: KnowledgeMatrix, keys: readonly string[]): Set<number> {+ const keyIndex = new Map(matrix.authors.map((a, i) => [a.key, i]));+ return new Set(keys.flatMap((key) => (keyIndex.has(key) ? [keyIndex.get(key)!] : [])));+}++/** What the leavers hold of one file, and the strongest author who stays. */+function fileExposure(+ shares: KnowledgeMatrixShare[],+ leaving: ReadonlySet<number>,+): { lost: number; heir: KnowledgeMatrixShare | null } {+ let lost = 0;+ let heir: KnowledgeMatrixShare | null = null;+ for (const entry of shares) {+ if (leaving.has(entry[0])) lost += entry[1];+ else if (!heir || entry[1] > heir[1]) heir = entry;+ }+ return { lost, heir };+}++function atRiskFile(+ matrix: KnowledgeMatrix,+ row: KnowledgeMatrixFile,+ lost: number,+ heir: KnowledgeMatrixShare | null,+): OffboardingFile {+ const facts = fileFacts(matrix, row);+ return {+ ...facts,+ lostShare: Math.min(1, lost),+ // Rounded shares can sum a hair past 1; clamp so "remaining" never reads negative.+ remainingShare: Math.max(0, 1 - lost),+ severity: facts.isHotspot || facts.lowHealth ? "severe" : "at_risk",+ inheritor: heir ? { ...personAt(matrix, heir[0]), share: heir[1] } : null,+ };+}++const isSevere = (f: OffboardingFile) => f.severity === "severe";+const isHotspot = (f: OffboardingFile) => f.isHotspot;+const nlocOf = (files: readonly OffboardingFile[]) => files.reduce((s, f) => s + f.nloc, 0);++function rollUpAreas(files: OffboardingFile[]): OffboardingArea[] {+ return Array.from(groupByDir(files), ([dir, group]) => ({+ dir,+ files: group,+ fileCount: group.length,+ severe: group.filter(isSevere).length,+ hotspots: group.filter(isHotspot).length,+ nloc: nlocOf(group),+ inheritor: mostNamed(+ group.flatMap((f) => (f.inheritor ? [{ person: f.inheritor, nloc: f.nloc }] : [])),+ ),+ })).sort(compareAreas);+}++export interface OffboardingOptions {+ /**+ * Only files changed in the last 90 days count: code still moving, as+ * knowledge loss reads it. Every total, denominators included, is then+ * over those files.+ */+ changedOnly?: boolean;+}++export function simulateOffboarding(+ matrix: KnowledgeMatrix,+ leavingKeys: readonly string[],+ threshold: number = DEFAULT_OFFBOARDING_THRESHOLD,+ { changedOnly = false }: OffboardingOptions = {},+): OffboardingResult {+ const leaving = leaverIndices(matrix, leavingKeys);+ const files: OffboardingFile[] = [];+ let touchedFiles = 0;+ let trackedFiles = 0;+ let totalNloc = 0;+ for (const row of matrix.files) {+ if (changedOnly && !row[8]) continue;+ trackedFiles += 1;+ totalNloc += row[2];+ const { lost, heir } = fileExposure(row[7], leaving);+ if (lost <= 0) continue;+ touchedFiles += 1;+ if (1 - lost < threshold) files.push(atRiskFile(matrix, row, lost, heir));+ }+ files.sort(compareFileFacts);++ const atRiskNloc = nlocOf(files);+ return {+ leaving: Array.from(leaving, (i) => personAt(matrix, i)),+ threshold,+ totals: {+ touchedFiles,+ atRiskFiles: files.length,+ severeFiles: files.filter(isSevere).length,+ hotspots: files.filter(isHotspot).length,+ atRiskNloc,+ totalNloc,+ nlocShare: totalNloc > 0 ? atRiskNloc / totalNloc : 0,+ trackedFiles,+ },+ areas: rollUpAreas(files),+ };+}++// ---------------------------------------------------------------------------+// URL state: `?leave=a,b&threshold=50`+// ---------------------------------------------------------------------------++/** Owner keys can hold a comma (`name:Doe, Jane`), so each one escapes it. */+export function formatLeaveParam(keys: readonly string[]): string {+ return keys.map((k) => k.replaceAll("%", "%25").replaceAll(",", "%2C")).join(",");+}++export function parseLeaveParam(raw: string | null | undefined): string[] {+ if (!raw) return [];+ const keys = raw+ .split(",")+ .map((k) => k.replaceAll("%2C", ",").replaceAll("%25", "%"))+ .filter(Boolean);+ return Array.from(new Set(keys));+}++/** The thresholds the page offers, in whole percent. */+export const OFFBOARDING_THRESHOLD_RANGE = { min: 10, max: 90, step: 5 } as const;++/**+ * Whole percent in the URL, clamped to the offered range so a hand-edited+ * link never shows a figure the slider cannot; anything unparsable falls+ * back to the default.+ */+export function parseThresholdParam(raw: string | null | undefined): number {+ const n = raw == null || raw === "" ? NaN : Number(raw);+ if (!Number.isInteger(n)) return DEFAULT_OFFBOARDING_THRESHOLD;+ const { min, max } = OFFBOARDING_THRESHOLD_RANGE;+ return Math.min(max, Math.max(min, n)) / 100;+}++export function formatThresholdParam(threshold: number): string {+ return String(Math.round(threshold * 100));+}diff --git a/packages/ui/src/owners/owner-commit-mix.tsx b/packages/ui/src/owners/owner-commit-mix.tsxnew file mode 100644index 000000000..59769d8e6--- /dev/null+++ b/packages/ui/src/owners/owner-commit-mix.tsx@@ -0,0 +1,56 @@+import * as React from "react";+import { ProportionBar } from "../shared/proportion-bar";+import { EmptyState } from "../shared/empty-state";+import { commitCategoryColor } from "../shared/series";+import type { OwnershipLabels } from "./labels";++const pct = (part: number, whole: number): number =>+ whole > 0 ? Math.round((part / whole) * 100) : 0;++/**+ * Commit mix, as one share bar. Each category keeps its fixed colour+ * (commitCategoryColor), the same as on every other chart of commit types.+ * Zero-count categories are dropped: the endpoint returns the full key set,+ * and a labelled bar with nothing in it reports a measurement of nothing.+ */+export function OwnerCommitMix({+ categories,+ labels,+}: {+ categories: Record<string, number>;+ labels: OwnershipLabels;+}) {+ const entries = Object.entries(categories ?? {})+ .filter(([, n]) => n > 0)+ .sort((a, b) => b[1] - a[1]);+ const total = entries.reduce((sum, [, n]) => sum + n, 0);++ if (entries.length === 0) {+ return (+ <EmptyState+ className="p-6"+ title={labels.commitMixEmptyTitle}+ description={labels.commitMixEmptyDescription}+ />+ );+ }++ return (+ <div className="flex flex-col gap-2">+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)]">+ {labels.commitMixDescription(total)}+ </p>+ <ProportionBar+ className="max-w-[420px]"+ label={labels.commitMixBarLabel}+ segments={entries.map(([category, n]) => ({+ key: category,+ label: category.charAt(0).toUpperCase() + category.slice(1),+ value: n,+ detail: `${n.toLocaleString()} · ${pct(n, total)}%`,+ color: commitCategoryColor(category),+ }))}+ />+ </div>+ );+}diff --git a/packages/ui/src/owners/owner-directory.tsx b/packages/ui/src/owners/owner-directory.tsxindex 6081b39f7..1ea63c101 100644--- a/packages/ui/src/owners/owner-directory.tsx+++ b/packages/ui/src/owners/owner-directory.tsx@@ -5,351 +5,141 @@ import { Users, Search } from "lucide-react";import type { OwnerListEntry } from "@repowise-dev/types/owners";import { Input } from "../ui/input";import { Skeleton } from "../ui/skeleton";+import { Switch } from "../ui/switch";import { EmptyState } from "../shared/empty-state";-import { ResultsFooter } from "../shared/results-footer";-import { PageLede } from "../shared/page-lede";-import { OverviewSection, SectionLink } from "../overview/section";-import { ReadsColumn, type ReadItem } from "../overview/reads-column";-import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";+import { OverviewSection } from "../overview/section";+import { ownershipLabels, type OwnershipLabels } from "./labels";import { OwnerTable, type OwnerSortKey } from "./owner-table";-import { OwnershipDistributionBar } from "./ownership-distribution-bar";export type { OwnerSortKey };export interface OwnerDirectoryFilters {q: string;sort: OwnerSortKey;+ /** List bots and coding agents beside people. Off by default. */+ includeAutomation: boolean;}export interface OwnerDirectoryProps {owners: OwnerListEntry[];- /** Optional full owner set for the distribution bar and the lede (e.g.- * fetched via listAllOwners when the contributor count is small). Falls- * back to `owners` when omitted. */- distributionOwners?: OwnerListEntry[];isLoading: boolean;isValidating: boolean;total: number;hasMore: boolean;filters: OwnerDirectoryFilters;onFiltersChange: (next: OwnerDirectoryFilters) => void;- onLoadMore: () => void;+ /** Load every remaining row; offered while `hasMore`. */+ onShowAll: () => void;onSelect: (owner: OwnerListEntry) => void;+ /** Bot and agent identities in the index; the toggle shows only when there are some. */+ automationCount?: number;/** Preferred over `onSelect`: gives every row a real URL. */hrefFor?: (owner: OwnerListEntry) => string;- /** Base path for the section jump links, e.g. `/repos/42`. */- base?: string;LinkComponent?: React.ElementType | undefined;/** Rendered in place of the table when the list could not load. */error?: React.ReactNode;-}--const INACTIVE_DAYS = 90;--function daysSince(iso: string | null): number | null {- if (!iso) return null;- const t = Date.parse(iso);- if (Number.isNaN(t)) return null;- return (Date.now() - t) / 86_400_000;+ labels?: Partial<OwnershipLabels> | undefined;}/**- * Who knows what, as a lede plus one table.- *- * This page used to open on four bordered counters — one of them "Bus-factor- * risk: 12" in red — above a 3-up grid of contributor cards. The counters told- * a reader to worry without saying what about, and the grid could not answer- * the question people actually arrive with, which is how two contributors- * compare: that needs the figures in a column, which a card grid makes- * impossible. Both are now one figure with a sentence, and one aligned table.+ * Everyone, as one aligned table under the page's lede: the first rows, then+ * "Show all N". People only by default; bots and coding agents are a toggle+ * away.*/export function OwnerDirectory({owners,- distributionOwners,isLoading,isValidating,total,hasMore,filters,onFiltersChange,- onLoadMore,+ onShowAll,onSelect,+ automationCount = 0,hrefFor,- base,LinkComponent,error,+ labels: overrides,}: OwnerDirectoryProps) {- // The lede is a claim about the whole repo, so it is computed off the full- // set when the caller has one. Computed off the loaded page instead, "68% of- // files" would silently mean "68% of the 30 rows currently rendered" and- // would change as you scrolled — a figure that moves while the data does not- // is a wrong figure, not a live one.- const source = distributionOwners ?? owners;- const complete = distributionOwners != null || (!hasMore && filters.q === "");-- const summary = React.useMemo(() => {- const sorted = [...source].sort((a, b) => b.files_owned - a.files_owned);- const totalFiles = sorted.reduce((s, o) => s + o.files_owned, 0);- const top3 = sorted.slice(0, 3).reduce((s, o) => s + o.files_owned, 0);- const soleFiles = sorted.reduce((s, o) => s + o.bus_factor_risk_files, 0);- const soleFilesInactive = sorted.reduce((s, o) => {- const d = daysSince(o.last_commit_at);- return d != null && d > INACTIVE_DAYS ? s + o.bus_factor_risk_files : s;- }, 0);- const siloOwners = sorted.filter((o) => o.silo_modules > 0).length;- const siloModules = sorted.reduce((s, o) => s + o.silo_modules, 0);- const deadLines = sorted.reduce((s, o) => s + o.dead_code_lines_owned, 0);- const deadOwners = sorted.filter((o) => o.dead_code_lines_owned > 0).length;- const deadFiles = sorted.reduce((s, o) => s + o.dead_code_files_owned, 0);- // Null when the indexed commits do not cover the last 90 days: unknown, not zero.- const active = sorted.some((o) => o.commit_count_90d != null)- ? sorted.filter((o) => (o.commit_count_90d ?? 0) > 0).length- : null;- const hotspots = sorted.reduce((s, o) => s + o.hotspots_owned, 0);- const commits90d = sorted.reduce(- (s, o) => s + (o.commit_count_90d ?? o.commit_count_90d_at_least ?? 0),- 0,- );- // Any floor makes the total a floor too.- const commits90dFloor = sorted.some((o) => o.commit_count_90d == null && o.commit_count_90d_at_least);- return {- deadFiles,- hotspots,- commits90d,- commits90dFloor,- topName: sorted[0]?.name ?? null,- topFiles: sorted[0]?.files_owned ?? 0,- totalFiles,- top3Pct: totalFiles > 0 ? Math.round((top3 / totalFiles) * 100) : 0,- soleFiles,- soleFilesInactive,- siloOwners,- siloModules,- deadLines,- deadOwners,- active,- };- }, [source]);-- // Built rather than declared: a repo with no dead code and no silos should- // get a shorter column, not four rows of zeroes. An empty state that says- // "0" is claiming a measurement; omitting the row says there is nothing to- // report, which is what is true.- const reads: ReadItem[] = [];- if (summary.soleFiles > 0) {- reads.push({- key: "sole",- label: "Sole-owned files",- value: summary.soleFiles.toLocaleString(),- ...(summary.totalFiles > 0- ? { unit: `of ${summary.totalFiles.toLocaleString()}` }- : {}),- why:- summary.soleFilesInactive > 0- ? `One author, no second reader. ${summary.soleFilesInactive.toLocaleString()} belong to someone who has not committed in ${INACTIVE_DAYS} days.`- : "One author and no second reader, though all of them belong to someone still active.",- href: base ? `${base}/owners` : "#",- });- }- if (summary.siloModules > 0) {- reads.push({- key: "silo",- label: "Silo modules",- value: summary.siloModules.toLocaleString(),- unit: `${summary.siloOwners} ${summary.siloOwners === 1 ? "person" : "people"}`,- why: "A single person owns more than 80% of the module.",- href: base ? `${base}/modules` : "#",- });- }- if (summary.active != null) {- reads.push({- key: "active",- label: "Active this quarter",- value: summary.active.toLocaleString(),- unit: `of ${total.toLocaleString()}`,- why: `Committed in the last ${INACTIVE_DAYS} days. The rest are history, not staffing.`,- href: base ? `${base}/commits` : "#",- });- }- if (summary.deadLines > 0) {- reads.push({- key: "dead",- label: "Dead lines owned",- value: summary.deadLines.toLocaleString(),- unit: `${summary.deadOwners} ${summary.deadOwners === 1 ? "person" : "people"}`,- why: "Unreachable code still attributed to whoever wrote it.",- href: base ? `${base}/code-health?tab=dead-code` : "#",- });- }-- // Deliberately disjoint from `reads` above. The first cut of this row- // restated Active, Sole-owned and Silo modules from the column immediately- // beside it, so three of five cells were the same figure twice on one- // screen. StatRibbon drops empty-valued entries itself, so an unmeasured- // figure leaves no gap.- const ribbon: RibbonStat[] = [- {- label: "Contributors",- value: total.toLocaleString(),- hint: "Distinct commit authors in the indexed history",- },- {- label: "Files attributed",- value: summary.totalFiles > 0 ? summary.totalFiles.toLocaleString() : "",- },- {- label: "Hotspots owned",- value: summary.hotspots > 0 ? summary.hotspots.toLocaleString() : "",- hint: "Owned files that are also high-churn",- },- {- label: "Commits 90d",- value:- summary.commits90d > 0- ? `${summary.commits90dFloor ? "≥" : ""}${summary.commits90d.toLocaleString()}`- : "",- },- {- label: "Dead-code files",- value: summary.deadFiles > 0 ? summary.deadFiles.toLocaleString() : "",- hint: "Files carrying unreachable code, counted separately from the line total",- },- ];-+ const labels = React.useMemo(() => ownershipLabels(overrides), [overrides]);+ const all = filters.includeAutomation;return (- <div className="flex flex-col gap-6 sm:gap-8">- {summary.totalFiles > 0 && (- <section className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-10">- <PageLede- label="Knowledge concentration"- value={`${summary.top3Pct}%`}- band={{ label: summary.top3Pct >= 60 ? "Concentrated" : "Spread" }}- {...(complete ? {} : { unit: "of the contributors loaded so far" })}- >- <p>- The top three of {total.toLocaleString()} contributors own{" "}- <strong className="font-semibold text-[var(--color-text-primary)]">- {summary.top3Pct}%- </strong>{" "}- of the {summary.totalFiles.toLocaleString()} attributed files- {summary.topName- ? `, with ${summary.topName} on ${summary.topFiles.toLocaleString()} of them`- : ""}- . Ownership is attributed by who wrote the surviving lines, not by who- committed last, so a formatting sweep does not hand someone a file they- have never read.- {summary.soleFiles > 0 && (- <>- {" "}- <strong className="font-semibold text-[var(--color-text-primary)]">- {summary.soleFiles.toLocaleString()}- </strong>{" "}- of those files have a single author and no second reader, which is- where the knowledge actually walks out.- </>- )}- </p>- </PageLede>- {reads.length > 0 && <ReadsColumn items={reads} LinkComponent={LinkComponent} />}- </section>- )}-- {/* Same guard as the lede. Before an index lands, every figure here is- zero and StatRibbon's empty-value filter leaves a single "Contributors- 0" cell stranded in a five-column row. Nothing measured, nothing- drawn. */}- {summary.totalFiles > 0 && (- <StatRibbon stats={ribbon} LinkComponent={LinkComponent} />- )}-- {source.length > 0 && (- <OverviewSection- title="How ownership is spread"- description="Share of attributed files per contributor, largest first, with the long tail collapsed into one segment."- {...(base- ? {- action: (- <SectionLink href={`${base}/owners`} LinkComponent={LinkComponent}>- Ownership map- </SectionLink>- ),- }- : {})}- >- <OwnershipDistributionBar- owners={source}- totalContributors={total}- {...(hrefFor ? { hrefFor } : { onSelect })}- {...(LinkComponent ? { LinkComponent } : {})}- />- </OverviewSection>- )}-- <OverviewSection- title="Everyone"- description="A dot marks sole-owned files held by someone who has stopped committing, so a clean column means nothing to chase."- action={- <span className="font-mono text-caption uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- {total.toLocaleString()} {total === 1 ? "contributor" : "contributors"}- </span>- }- >- <div className="relative max-w-sm">+ <OverviewSection+ title={labels.everyone}+ description={labels.everyoneDescription}+ action={+ <span className="font-mono text-caption uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {labels.people(total, all)}+ </span>+ }+ >+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2">+ <div className="relative w-full max-w-sm"><Search className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-[var(--color-text-tertiary)]" /><Inputvalue={filters.q}onChange={(e) => onFiltersChange({ ...filters, q: e.target.value })}- placeholder="Filter by name or email…"- aria-label="Filter contributors by name or email"+ placeholder={labels.searchPlaceholder}+ aria-label={labels.searchLabel}className="pl-8"/></div>-- {error ? (- error- ) : isLoading && owners.length === 0 ? (- // Row-height skeletons, not tiles: a skeleton whose shape misses the- // real layout reflows when content lands, which reads as slower than- // showing nothing.- <div className="flex flex-col gap-px">- {Array.from({ length: 8 }).map((_, i) => (- <Skeleton key={i} className="h-[54px] w-full" />- ))}- </div>- ) : owners.length === 0 ? (- filters.q ? (- <EmptyState- tone="filtered"- title="No contributors match this search"- action={{ label: "Clear search", onClick: () => onFiltersChange({ ...filters, q: "" }) }}- />- ) : (- <EmptyState- icon={<Users />}- title="No contributors yet"- description="Contributors land with the first git index."+ {automationCount > 0 && (+ <label className="flex items-center gap-2 text-xs text-[var(--color-text-secondary)]">+ <Switch+ checked={filters.includeAutomation}+ onCheckedChange={(includeAutomation) => onFiltersChange({ ...filters, includeAutomation })}/>- )+ {labels.showAutomation(automationCount)}+ </label>+ )}+ </div>++ {error ? (+ error+ ) : isLoading && owners.length === 0 ? (+ <div className="flex flex-col gap-px">+ {Array.from({ length: 8 }).map((_, i) => (+ <Skeleton key={i} className="h-[54px] w-full" />+ ))}+ </div>+ ) : owners.length === 0 ? (+ filters.q ? (+ <EmptyState+ tone="filtered"+ title={labels.noMatch}+ action={{ label: labels.clearSearch, onClick: () => onFiltersChange({ ...filters, q: "" }) }}+ />) : (- <OwnerTable- owners={owners}- sort={filters.sort}- onSortChange={(sort) => onFiltersChange({ ...filters, sort })}- hrefFor={hrefFor}- onSelect={hrefFor ? undefined : onSelect}- LinkComponent={LinkComponent}+ <EmptyState+ icon={<Users />}+ title={labels.noPeople}+ description={labels.noPeopleDescription}/>- )}-- <ResultsFooter- shown={owners.length}- total={total}- hasMore={hasMore}- loading={isValidating && !isLoading}- onLoadMore={onLoadMore}- noun="contributor"+ )+ ) : (+ <OwnerTable+ owners={owners}+ sort={filters.sort}+ onSortChange={(sort) => onFiltersChange({ ...filters, sort })}+ hrefFor={hrefFor}+ onSelect={hrefFor ? undefined : onSelect}+ LinkComponent={LinkComponent}+ labels={labels}/>- </OverviewSection>- </div>+ )}++ {hasMore && (+ <button+ type="button"+ onClick={onShowAll}+ disabled={isValidating}+ className="self-start text-xs text-[var(--color-accent-primary)] hover:underline disabled:text-[var(--color-text-tertiary)] disabled:no-underline"+ >+ {isValidating ? labels.loading : labels.showAllPeople(total, all)}+ </button>+ )}+ </OverviewSection>);}diff --git a/packages/ui/src/owners/owner-file-table.tsx b/packages/ui/src/owners/owner-file-table.tsxnew file mode 100644index 000000000..a7ada0f5e--- /dev/null+++ b/packages/ui/src/owners/owner-file-table.tsx@@ -0,0 +1,140 @@+import * as React from "react";+import type { OwnerFileEntry } from "@repowise-dev/types/owners";+import { EmptyState } from "../shared/empty-state";+import { PathText } from "../shared/path-text";+import { formatRelativeTimeOrNull } from "../lib/format";+import { isSingleOwner } from "./knowledge-files";+import type { OwnershipLabels } from "./labels";++/**+ * The only marker on the file table.+ *+ * Sole ownership on its own marks 80% of this contributor's files, and a+ * hotspot flag 80% again, so either alone marks nothing. The conjunction — a+ * high-churn file, one author, and this person wrote at least 90% of its+ * commits — lands on a quarter of rows at most and describes one specific+ * situation worth acting on.+ */+function isSoleCarried(f: OwnerFileEntry): boolean {+ return f.is_hotspot && isSingleOwner(f.bus_factor) && (f.primary_owner_commit_pct ?? 0) >= 0.9;+}++export function soleCarriedCount(files: readonly OwnerFileEntry[]): number {+ return files.filter(isSoleCarried).length;+}++/**+ * The file table.+ *+ * Hand-rolled rather than `ResponsiveTable` for the same reason `OwnerTable`+ * is: that primitive is a client component, and nothing here needs one.+ *+ * Below `sm` it stops being a table. Five columns cannot share 390px without+ * starving the primary one, and the primary one is a file path that may not be+ * truncated — so the path takes the full width and the four figures collapse+ * into a single meta line beneath it.+ */+export function OwnerFileTable({+ files,+ hrefForFile,+ LinkComponent,+ labels,+}: {+ files: OwnerFileEntry[];+ hrefForFile?: ((filePath: string) => string) | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels: OwnershipLabels;+}) {+ const A = LinkComponent ?? "a";++ if (files.length === 0) {+ return (+ <EmptyState+ className="p-6"+ title={labels.fileTableEmptyTitle}+ description={labels.fileTableEmptyDescription}+ />+ );+ }++ const headCls =+ "border-b border-[var(--color-border-default)] pb-2 font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";+ const numCls = "whitespace-nowrap py-2.5 pl-3 text-right align-top tabular-nums max-sm:hidden";++ return (+ <div className="-mx-[var(--page-pad)] overflow-x-auto px-[var(--page-pad)] sm:mx-0 sm:px-0">+ <table className="w-full border-collapse text-[13.5px]">+ <thead className="max-sm:hidden">+ <tr>+ <th scope="col" className={`${headCls} pr-3 text-left`}>+ {labels.colFile}+ </th>+ <th scope="col" className={`${headCls} whitespace-nowrap pl-3 text-right`}>+ {labels.colCommits90d}+ </th>+ <th+ scope="col"+ title={labels.colChurnHint}+ className={`${headCls} cursor-help whitespace-nowrap pl-3 text-right`}+ >+ {labels.colChurn}+ </th>+ <th+ scope="col"+ title={labels.colTheirCommitsHint}+ className={`${headCls} cursor-help whitespace-nowrap pl-3 text-right`}+ >+ {labels.colTheirCommits}+ </th>+ <th scope="col" className={`${headCls} whitespace-nowrap pl-3 text-right`}>+ {labels.colTouched}+ </th>+ </tr>+ </thead>+ <tbody>+ {files.map((f) => {+ const href = hrefForFile?.(f.file_path);+ const ownPct =+ f.primary_owner_commit_pct != null+ ? `${Math.round(f.primary_owner_commit_pct * 100)}%`+ : "—";+ const touched = formatRelativeTimeOrNull(f.last_commit_at) ?? "—";+ return (+ <tr+ key={f.file_path}+ className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] max-sm:block"+ >+ <td className="py-2.5 pr-3 align-top max-sm:block max-sm:pr-0">+ {href ? (+ <A href={href} className="group no-underline">+ <PathText path={f.file_path} />+ </A>+ ) : (+ <PathText path={f.file_path} />+ )}+ {isSoleCarried(f) && (+ <span+ title={labels.soleCarriedTitle}+ className="ml-1.5 inline-block h-[5px] w-[5px] shrink-0 rounded-full bg-[var(--color-warning)] align-middle"+ />+ )}+ {/* The four figures as one line, below `sm` only. Reads as a+ sentence rather than as a table row that lost its header. */}+ <span className="mt-1 hidden text-[11.5px] tabular-nums text-[var(--color-text-tertiary)] max-sm:block">+ {labels.fileMeta(f.commit_count_90d, Math.round(f.churn_percentile), ownPct, touched)}+ </span>+ </td>+ <td className={numCls}>{f.commit_count_90d.toLocaleString()}</td>+ <td className={`${numCls} text-[var(--color-text-tertiary)]`}>+ {Math.round(f.churn_percentile)}+ </td>+ <td className={`${numCls} text-[var(--color-text-tertiary)]`}>{ownPct}</td>+ <td className={`${numCls} text-[var(--color-text-tertiary)]`}>{touched}</td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}diff --git a/packages/ui/src/owners/owner-footprint.tsx b/packages/ui/src/owners/owner-footprint.tsxnew file mode 100644index 000000000..253d08f2a--- /dev/null+++ b/packages/ui/src/owners/owner-footprint.tsx@@ -0,0 +1,60 @@+import * as React from "react";+import type { OwnerModuleRollup } from "@repowise-dev/types/owners";+import { OverviewSection } from "../overview/section";+import { EmptyState } from "../shared/empty-state";+import { ProportionBar } from "../shared/proportion-bar";+import type { OwnershipLabels } from "./labels";++/**+ * Where a person works, as one stacked bar rather than a row of bars.+ *+ * The endpoint only attributes top-level directories, so this list is two to+ * four entries on a real repo. Four rows each carrying a label, a count, a+ * track and a percentage is more chrome than four numbers can pay for, and it+ * invites comparing bars that measure different denominators. One bar shows+ * the split, and the key carries the share. Position is the encoding.+ */+export function OwnerFootprint({+ modules,+ hrefForModule,+ LinkComponent,+ labels,+}: {+ modules: OwnerModuleRollup[];+ hrefForModule?: ((modulePath: string) => string) | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels: OwnershipLabels;+}) {+ const ordered = [...modules].sort((a, b) => b.file_count - a.file_count);+ const total = ordered.reduce((sum, m) => sum + m.file_count, 0);++ return (+ <OverviewSection+ title={labels.footprintTitle}+ description={labels.footprintDescription}+ >+ {total === 0 ? (+ <EmptyState+ className="p-6"+ title={labels.footprintEmptyTitle}+ description={labels.footprintEmptyDescription}+ />+ ) : (+ <ProportionBar+ className="max-w-[560px]"+ label={labels.footprintBarLabel}+ // Every directory keeps its own link; past the fifth they share the tail step.+ maxSegments={Infinity}+ segments={ordered.map((m) => ({+ key: m.module_path,+ label: m.module_path,+ value: m.file_count,+ detail: labels.footprintDetail(m.file_count, Math.round(m.dominant_pct * 100)),+ ...(hrefForModule ? { href: hrefForModule(m.module_path) } : {}),+ }))}+ LinkComponent={LinkComponent}+ />+ )}+ </OverviewSection>+ );+}diff --git a/packages/ui/src/owners/owner-identity.tsx b/packages/ui/src/owners/owner-identity.tsxnew file mode 100644index 000000000..e2fc71b61--- /dev/null+++ b/packages/ui/src/owners/owner-identity.tsx@@ -0,0 +1,53 @@+import * as React from "react";+import type { OwnerProfile } from "@repowise-dev/types/owners";+import type { OwnershipLabels } from "./labels";++/** Active, quiet, or unknown when the indexed commits do not reach back far enough. */+export function ownerActivity(owner: Pick<OwnerProfile, "commit_count_90d" | "commit_count_90d_at_least">):+ | "active"+ | "quiet"+ | null {+ if (owner.commit_count_90d != null) return owner.commit_count_90d > 0 ? "active" : "quiet";+ return owner.commit_count_90d_at_least ? "active" : null;+}++/**+ * Who this is: whether they still commit, and every name and address the+ * index folded into them, so a reader looking for "jdoe@old-corp" finds the+ * person they know. Plain words, no badges: activity is a fact, not a grade.+ */+function activityLine(owner: OwnerProfile, labels: OwnershipLabels): string | null {+ const activity = ownerActivity(owner);+ if (activity !== "active") return activity && labels.quietLine;+ const exact = owner.commit_count_90d;+ return labels.activeLine(exact ?? owner.commit_count_90d_at_least ?? 0, exact == null);+}++/** Every folded-in name and address other than the ones the page already shows. */+function otherIdentities(owner: OwnerProfile): string[] {+ return [+ ...owner.aliases.names.filter((n) => n !== owner.name),+ ...owner.aliases.emails.filter((e) => e !== owner.email),+ ];+}++export function OwnerIdentity({ owner, labels }: { owner: OwnerProfile; labels: OwnershipLabels }) {+ const aliases = otherIdentities(owner);+ const rows = [+ { label: labels.activityLabel, hidden: true, value: activityLine(owner, labels), mono: false },+ { label: labels.emailLabel, hidden: false, value: owner.email !== owner.name ? owner.email : null, mono: true },+ { label: labels.aliasesLabel, hidden: false, value: aliases.join(", ") || null, mono: true },+ ].filter((r) => r.value);++ if (rows.length === 0) return null;+ return (+ <dl className="flex flex-col gap-1.5 text-xs text-[var(--color-text-secondary)]">+ {rows.map((r) => (+ <div key={r.label} className="flex flex-wrap gap-x-2">+ <dt className={r.hidden ? "sr-only" : "text-[var(--color-text-tertiary)]"}>{r.label}</dt>+ <dd className={r.mono ? "font-mono [overflow-wrap:anywhere]" : undefined}>{r.value}</dd>+ </div>+ ))}+ </dl>+ );+}diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsxindex 82faac54d..ab0d5c58c 100644--- a/packages/ui/src/owners/owner-profile.tsx+++ b/packages/ui/src/owners/owner-profile.tsx@@ -1,590 +1,143 @@import * as React from "react";-import type {- OwnerProfile,- OwnerFileEntry,- OwnerModuleRollup,- OwnerCoAuthor,-} from "@repowise-dev/types/owners";-import { PageLede } from "../shared/page-lede";+import type { OwnerProfile, OwnerCoAuthor } from "@repowise-dev/types/owners";import { OverviewSection, SectionLink } from "../overview/section";-import { ReadsColumn, type ReadItem } from "../overview/reads-column";-import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";-import { EmptyState } from "../shared/empty-state";-import { ProportionBar } from "../shared/proportion-bar";-import { commitCategoryColor } from "../shared/series";-import { formatCompact, formatRelativeTimeOrNull } from "../lib/format";-import { OwnerAvatar } from "./owner-avatar";+import { OwnerCommitMix } from "./owner-commit-mix";+import { OwnerFileTable, soleCarriedCount } from "./owner-file-table";+import { OwnerFootprint } from "./owner-footprint";+import { OwnerIdentity } from "./owner-identity";+import { OwnerRelationships } from "./owner-relationships";+import { ownershipLabels, type OwnershipLabels } from "./labels";/**- * The contributor profile, rebuilt on the section style.+ * A person page about knowledge and handover, never a scorecard: who they+ * are, what depends on them and who could take it over, where they work, who+ * they work with, then the full file table and commit mix behind disclosure.+ * No rankings and no per-person negatives.*- * It was nine bordered containers at near-identical weight — a header card, a- * four-tile risk strip, and five more cards in a 2 + 1 grid — so the page had- * nothing to lead with and no way to say which of the nine mattered.- *- * Three things drove the rewrite, all of them measured against a real index- * before being changed rather than after:- *- * 1. **Every marker fired on nearly every row.** The hotspot flame hit 80% /- * 70% / 55% of the top files for the three contributors with real history;- * the churn pill's red band hit 80% / 85% / 55%; the bus-factor scale's- * green band had no members at all. A badge most rows carry says nothing.- * The one marker left is hotspot *and* sole owner *and* ≥90% of the file's- * commits, which lands on 25% / 25% / 15% and names a single thing: a- * high-churn file this person alone maintains.- *- * 2. **Colour was doing work it is not allowed to do.** Lines added rendered- * green and lines deleted red, as though deleting code were an error; churn- * percentile and bus factor got the health triad for what are plain counts.- * Green / amber / red belong to health bands. What is left uses the accent- * ramp, where position carries magnitude.- *- * 3. **The figures restated each other.** Modules was a headline tile *and* a- * section; co-authors was a headline tile *and* a section. Each figure in- * this file now appears exactly once, in the place that can explain it:- * sole ownership in the lede, the three secondary reads in the column beside- * it, five volume figures in the ribbon, and the rest inside the section- * that owns the subject.- *- * Server-renderable: no state, no handlers, `hrefFor*` instead of `onSelect*`.- * Every row is then a real URL that survives a middle-click, and the page above- * it stops needing a client boundary.+ * Server-renderable. The off-boarding section is interactive (prompts, file+ * lists), so the host renders it as a client component and passes it in.+ */++/**+ * Positive credit for one person, from `/wins?author=` (lane L-history). The+ * endpoint is not on this branch's base yet, so this is a typed slot the host+ * fills once it lands; nothing renders without it.*/+export interface OwnerCredit {+ filesImproved: number;+ findingsResolved: number;+ /** The window the counts cover, in days. */+ windowDays: number;+ href?: string;+}export interface OwnerProfileViewProps {owner: OwnerProfile;/** `/repos/{id}` — the prefix for every drill-in on this page. */base: string;+ /** "What depends on them": the host's single-person off-boarding view. */+ dependsOn: React.ReactNode;+ credit?: OwnerCredit | undefined;hrefForFile?: ((filePath: string) => string) | undefined;hrefForModule?: ((modulePath: string) => string) | undefined;hrefForCoAuthor?: ((coAuthor: OwnerCoAuthor) => string) | undefined;LinkComponent?: React.ElementType | undefined;+ labels?: Partial<OwnershipLabels> | undefined;}-/**- * A break opportunity after each path separator.- *- * Without it a 72-character path in a narrow column breaks mid-identifier and- * wraps to ten lines; with it, it breaks between directories and wraps to two.- * `<wbr>` rather than a zero-width space so the path is still clean when it is- * copied out of the page.- */-function PathText({ path }: { path: string }) {- const segments = path.split("/");- return (- <span className="font-mono text-xs text-[var(--color-text-primary)] transition-colors group-hover:text-[var(--color-accent-primary)] [overflow-wrap:anywhere]">- {segments.map((seg, i) => (- <React.Fragment key={i}>- {i > 0 && (- <>- /<wbr />- </>- )}- {seg}- </React.Fragment>- ))}- </span>- );-}--/**- * The only marker on the file table.- *- * Sole ownership on its own marks 80% of this contributor's files, and a- * hotspot flag 80% again, so either alone marks nothing. The conjunction — a- * high-churn file, no second author, and this person wrote at least 90% of its- * commits — lands on a quarter of rows at most and describes one specific- * situation worth acting on.- */-function isSoleCarried(f: OwnerFileEntry): boolean {- return f.is_hotspot && f.bus_factor <= 1 && (f.primary_owner_commit_pct ?? 0) >= 0.9;-}--const pct = (part: number, whole: number): number =>- whole > 0 ? Math.round((part / whole) * 100) : 0;-export function OwnerProfileView({owner,base,+ dependsOn,+ credit,hrefForFile,hrefForModule,hrefForCoAuthor,LinkComponent,+ labels: overrides,}: OwnerProfileViewProps) {- const solePct = pct(owner.bus_factor_risk_files, owner.files_owned);+ const labels = ownershipLabels(overrides);const filesShown = owner.top_files.slice(0, 20);- const soleCarried = filesShown.filter(isSoleCarried).length;-- // Every read here is a figure that appears nowhere else on the page, and- // every one is a link: this column doubles as navigation for someone who- // opened the profile for one specific thing.- const reads: ReadItem[] = [];- if (owner.dead_code_files_owned > 0) {- reads.push({- key: "dead",- label: "Dead code owned",- value: owner.dead_code_files_owned.toLocaleString(),- unit: "files",- why: `${owner.dead_code_lines_owned.toLocaleString()} unreachable lines still attributed here. Usually the cheapest thing on this page to act on.`,- href: `${base}/code-health?tab=dead-code`,- });- }- if (owner.silo_modules > 0) {- reads.push({- key: "silos",- label: "Silo directories",- value: owner.silo_modules.toLocaleString(),- unit: owner.silo_modules === 1 ? "directory" : "directories",- why: "Top-level directories where this person owns more than 80% of the files, so a review has nobody obvious to route to.",- href: `${base}/owners`,- });- }- // Volume figures, none of which appear in the lede, the reads column or a- // section below. The two line counts are the payload's `_est` fields, so an- // exact six-digit figure would claim a precision the number does not have.- const ribbon: RibbonStat[] = [- // Null when the indexed commits do not reach back 90 days: not a zero.- {- label: "Commits, 90d",- // A floor when the indexed commits stop inside the window.- value:- owner.commit_count_90d?.toLocaleString() ??- (owner.commit_count_90d_at_least ? `≥${owner.commit_count_90d_at_least.toLocaleString()}` : "—"),- },- {- label: "Lines added",- value: formatCompact(owner.lines_added_90d_est),- hint: "Estimated from commit stats over the last 90 days",- },- {- label: "Lines removed",- value: formatCompact(owner.lines_deleted_90d_est),- hint: "Estimated from commit stats over the last 90 days",- },- {- label: "Files touched",- value: (owner.files_touched_total ?? owner.top_files.length).toLocaleString(),- hint: "Files with at least one commit attributed to this person",- },- {- label: "High-churn owned",- value: owner.hotspots_owned.toLocaleString(),- hint: "Owned files that are also in the repo's high-churn band",- },- ];+ const soleCarried = soleCarriedCount(filesShown);+ const touched = owner.files_touched_total ?? owner.top_files.length;return (<div className="flex flex-col gap-6 sm:gap-8">- <section className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-10">- <PageLede- label="Sole-owned files"- value={owner.bus_factor_risk_files.toLocaleString()}- unit={`of ${owner.files_owned.toLocaleString()} owned`}- action={- <SectionLink href={`${base}/owners`} LinkComponent={LinkComponent}>- All contributors- </SectionLink>- }- >- <p>- {owner.bus_factor_risk_files > 0 ? (- <>- <strong className="font-semibold text-[var(--color-text-primary)]">- {owner.bus_factor_risk_files.toLocaleString()} files- </strong>{" "}- where this person wrote most of the surviving lines and nobody- else has committed, which is {solePct}% of everything they own.- Ownership follows the surviving lines rather than the last- commit, so this is knowledge held rather than activity logged.- </>- ) : (- <>- Every one of the{" "}- {owner.files_owned.toLocaleString()} files this person owns has a- second author. Ownership follows the surviving lines rather than- the last commit, so this is knowledge held rather than activity- logged.- </>- )}- </p>- </PageLede>- <ReadsColumn items={reads} LinkComponent={LinkComponent} />- </section>+ <OwnerIdentity owner={owner} labels={labels} />- <StatRibbon stats={ribbon} />+ <OverviewSection+ flush+ title={labels.dependsTitle}+ description={labels.dependsDescription}+ action={+ <SectionLink href={`${base}/owners`} LinkComponent={LinkComponent}>+ {labels.ownershipLink}+ </SectionLink>+ }+ >+ {dependsOn}+ </OverviewSection>- <OwnershipFootprint+ <OwnerFootprintmodules={owner.modules}- base={base}hrefForModule={hrefForModule}LinkComponent={LinkComponent}+ labels={labels}/>- <OverviewSection- title="Files they carry"- description={`The ${filesShown.length} ${filesShown.length === 1 ? "file" : "files"} with the most commits attributed to this person, of ${(owner.files_touched_total ?? owner.top_files.length).toLocaleString()} touched. Churn is a percentile against every file in the repo. A dot marks a high-churn file they alone maintain and wrote at least 90% of the commits for${soleCarried > 0 ? `: ${soleCarried} of these ${filesShown.length}` : ", and none of these qualify"}.`}- >- <OwnerFileTable- files={filesShown}- hrefForFile={hrefForFile}- LinkComponent={LinkComponent}- />- </OverviewSection>+ {credit && <OwnerCreditSection credit={credit} LinkComponent={LinkComponent} labels={labels} />}- <WorkingRelationships+ <OwnerRelationshipscoAuthors={owner.co_authors}total={owner.co_authors_total ?? owner.co_authors.length}hrefForCoAuthor={hrefForCoAuthor}LinkComponent={LinkComponent}+ labels={labels}/>- <CommitMix categories={owner.commit_categories} />- </div>- );-}--/* -------------------------------------------------------------------------- */--/**- * Where the ownership sits, as one stacked bar rather than a row of bars.- *- * The endpoint only attributes top-level directories, so this list is two to- * four entries on a real repo — this one has `packages`, `tests`, `scripts`- * and `docker`. Four rows each carrying a label, a count, a track and a- * percentage is more chrome than four numbers can pay for, and it invites the- * reader to compare bars that are all measuring different denominators. One- * bar shows the split, and the key carries the share.- *- * The share steps, the series colours by rank: these are ordered shares of- * one whole, so position is the encoding.- */-function OwnershipFootprint({- modules,- base,- hrefForModule,- LinkComponent,-}: {- modules: OwnerModuleRollup[];- base: string;- hrefForModule?: ((modulePath: string) => string) | undefined;- LinkComponent?: React.ElementType | undefined;-}) {- const ordered = [...modules].sort((a, b) => b.file_count - a.file_count);- const total = ordered.reduce((sum, m) => sum + m.file_count, 0);-- return (- <OverviewSection- title="Where the ownership sits"- description="Share is the fraction of each directory's files where this person wrote most of the surviving lines. Only top-level directories are attributed, so this is a coarse map rather than a per-module one."- action={- <SectionLink href={`${base}/owners`} LinkComponent={LinkComponent}>- Ownership- </SectionLink>- }- >- {total === 0 ? (- <EmptyState- className="p-6"- title="No directory attribution yet"- description="Ownership by directory appears after the next git sync."- />- ) : (- <ProportionBar- label="Owned files by directory"- // Every directory keeps its own link; past the fifth they share the tail step.- maxSegments={Infinity}- segments={ordered.map((m) => ({- key: m.module_path,- label: m.module_path,- value: m.file_count,- detail: `${m.file_count.toLocaleString()} ${m.file_count === 1 ? "file" : "files"} · ${Math.round(m.dominant_pct * 100)}% theirs`,- ...(hrefForModule ? { href: hrefForModule(m.module_path) } : {}),- }))}- LinkComponent={LinkComponent}- />- )}- </OverviewSection>- );-}--/* -------------------------------------------------------------------------- */--/**- * The file table.- *- * Hand-rolled rather than `ResponsiveTable` for the same reason `OwnerTable`- * is: that primitive is a client component, and nothing here needs one.- *- * Below `sm` it stops being a table. Five columns cannot share 390px without- * starving the primary one, and the primary one is a file path that may not be- * truncated — so the path takes the full width and the four figures collapse- * into a single meta line beneath it.- */-function OwnerFileTable({- files,- hrefForFile,- LinkComponent,-}: {- files: OwnerFileEntry[];- hrefForFile?: ((filePath: string) => string) | undefined;- LinkComponent?: React.ElementType | undefined;-}) {- const A = LinkComponent ?? "a";-- if (files.length === 0) {- return (- <EmptyState- className="p-6"- title="No file attribution yet"- description="File-level ownership appears after the next git sync."- />- );- }-- const headCls =- "border-b border-[var(--color-border-default)] pb-2 font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";- const numCls = "whitespace-nowrap py-2.5 pl-3 text-right align-top tabular-nums max-sm:hidden";+ <OverviewSection+ title={labels.filesCarryTitle}+ collapsible+ defaultOpen={false}+ hint={labels.filesCarryHint(filesShown.length, touched)}+ description={labels.filesCarryDescription(soleCarried, filesShown.length)}+ >+ <OwnerFileTable files={filesShown} hrefForFile={hrefForFile} LinkComponent={LinkComponent} labels={labels} />+ </OverviewSection>- return (- <div className="-mx-[var(--page-pad)] overflow-x-auto px-[var(--page-pad)] sm:mx-0 sm:px-0">- <table className="w-full border-collapse text-[13.5px]">- <thead className="max-sm:hidden">- <tr>- <th scope="col" className={`${headCls} pr-3 text-left`}>- File- </th>- <th scope="col" className={`${headCls} whitespace-nowrap pl-3 text-right`}>- Commits 90d- </th>- <th- scope="col"- title="Percentile rank of this file's change frequency against every file in the repo"- className={`${headCls} cursor-help whitespace-nowrap pl-3 text-right`}- >- Churn- </th>- <th- scope="col"- title="Share of this file's commits written by this person"- className={`${headCls} cursor-help whitespace-nowrap pl-3 text-right`}- >- Their commits- </th>- <th scope="col" className={`${headCls} whitespace-nowrap pl-3 text-right`}>- Touched- </th>- </tr>- </thead>- <tbody>- {files.map((f) => {- const href = hrefForFile?.(f.file_path);- const ownPct =- f.primary_owner_commit_pct != null- ? `${Math.round(f.primary_owner_commit_pct * 100)}%`- : "—";- const touched = formatRelativeTimeOrNull(f.last_commit_at) ?? "—";- return (- <tr- key={f.file_path}- className="border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] max-sm:block"- >- <td className="py-2.5 pr-3 align-top max-sm:block max-sm:pr-0">- {href ? (- <A href={href} className="group no-underline">- <PathText path={f.file_path} />- </A>- ) : (- <PathText path={f.file_path} />- )}- {isSoleCarried(f) && (- <span- title="High-churn file this person alone maintains"- className="ml-1.5 inline-block h-[5px] w-[5px] shrink-0 rounded-full bg-[var(--color-warning)] align-middle"- />- )}- {/* The four figures as one line, below `sm` only. Reads as a- sentence rather than as a table row that lost its header. */}- <span className="mt-1 hidden text-[11.5px] tabular-nums text-[var(--color-text-tertiary)] max-sm:block">- {f.commit_count_90d.toLocaleString()} commits in 90d · churn{" "}- {Math.round(f.churn_percentile)} · {ownPct} of its commits ·- touched {touched}- </span>- </td>- <td className={numCls}>{f.commit_count_90d.toLocaleString()}</td>- <td className={`${numCls} text-[var(--color-text-tertiary)]`}>- {Math.round(f.churn_percentile)}- </td>- <td className={`${numCls} text-[var(--color-text-tertiary)]`}>{ownPct}</td>- <td className={`${numCls} text-[var(--color-text-tertiary)]`}>{touched}</td>- </tr>- );- })}- </tbody>- </table>+ <OverviewSection title={labels.commitMixTitle} collapsible defaultOpen={false}>+ <OwnerCommitMix categories={owner.commit_categories} labels={labels} />+ </OverviewSection></div>);}-/* -------------------------------------------------------------------------- */--/**- * Who else works in the same files.- *- * A list of ten was the wrong shape for this data. Overlap on a real repo is- * one partner and then a cliff — 15.8%, then 1.6%, 1.2%, 1.0%, 0.8% — so rows- * two through ten are people who once touched the same file, presented at the- * same weight as the person who actually shares the work. The lead partner is- * the answer to the question the section exists for (who reviews this), and- * the tail is honestly reported as a count rather than padded out into rows.- */-function WorkingRelationships({- coAuthors,- total,- hrefForCoAuthor,+function OwnerCreditSection({+ credit,LinkComponent,+ labels,}: {- coAuthors: OwnerCoAuthor[];- total: number;- hrefForCoAuthor?: ((coAuthor: OwnerCoAuthor) => string) | undefined;+ credit: OwnerCredit;LinkComponent?: React.ElementType | undefined;+ labels: OwnershipLabels;}) {- const A = LinkComponent ?? "a";- const [lead, second] = [...coAuthors].sort(- (a, b) => b.co_change_strength - a.co_change_strength,- );-- return (- <OverviewSection- title="Who else works here"- description="Contributors editing the same files. Overlap is the share of this person's files the other has also committed to, so it reads as how much of their work is genuinely shared."- >- {!lead ? (- <EmptyState- className="p-6"- title="Nobody else has touched these files"- description="Co-authorship appears once a second contributor commits to a file this person owns."- />- ) : (- <div className="flex flex-col gap-3">- <LeadPartner- coAuthor={lead}- href={hrefForCoAuthor?.(lead)}- LinkComponent={A}- />- <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">- {total <= 1 ? (- <>No other contributor shares a file with this person.</>- ) : second ? (- <>- The next closest of {(total - 1).toLocaleString()} other- contributors overlaps on{" "}- {(second.co_change_strength * 100).toFixed(1)}%, so there is one- natural reviewer here rather than a shortlist.- </>- ) : (- <>- {(total - 1).toLocaleString()} other contributors share at least- one file.- </>- )}- </p>- </div>- )}- </OverviewSection>- );-}--function LeadPartner({- coAuthor,- href,- LinkComponent,-}: {- coAuthor: OwnerCoAuthor;- href: string | undefined;- LinkComponent: React.ElementType;-}) {- const A = LinkComponent;- const body = (- <>- <OwnerAvatar name={coAuthor.name} email={coAuthor.email} size="md" />- <span className="min-w-0">- {/* No truncation: the name is the primary column here and there is room- for it. */}- <span className="block font-medium text-[var(--color-text-primary)] transition-colors group-hover:text-[var(--color-accent-primary)] [text-wrap:pretty]">- {coAuthor.name || coAuthor.email || "unknown"}- </span>- <span className="block text-xs tabular-nums text-[var(--color-text-tertiary)]">- {coAuthor.shared_files.toLocaleString()} shared{" "}- {coAuthor.shared_files === 1 ? "file" : "files"} ·{" "}- {(coAuthor.co_change_strength * 100).toFixed(1)}% of this person's- work overlaps theirs- </span>- </span>- </>- );-- return href ? (- <A- href={href}- className="group flex w-fit items-center gap-3 no-underline"- >- {body}- </A>- ) : (- <span className="flex items-center gap-3">{body}</span>- );-}--/* -------------------------------------------------------------------------- */--/**- * Commit mix, as one share bar.- *- * The colour map this replaced keyed on `feat`, `docs`, `test`, `chore` and- * `perf`. The endpoint returns `feature`, `fix`, `refactor` and `dependency`,- * so four of the five colours were unreachable and the largest category fell- * through to the default — a palette that had never once rendered as designed.- * Each category keeps its fixed colour (commitCategoryColor), the same as on- * every other chart of commit types.- *- * Zero-count categories are dropped rather than rendered as an empty track:- * the endpoint returns the full key set, so a contributor who has never- * refactored was getting a labelled bar with nothing in it.- */-function CommitMix({ categories }: { categories: Record<string, number> }) {- const entries = Object.entries(categories ?? {})- .filter(([, n]) => n > 0)- .sort((a, b) => b[1] - a[1]);- const total = entries.reduce((sum, [, n]) => sum + n, 0);-+ if (credit.filesImproved === 0 && credit.findingsResolved === 0) return null;return (<OverviewSection- title="What they commit"- description={- total > 0- ? `${total.toLocaleString()} commits classified from the subject line, across every file this person has touched.`- : "Commits are classified from the subject line during indexing."- }+ title={labels.creditTitle}+ {...(credit.href+ ? {+ action: (+ <SectionLink href={credit.href} LinkComponent={LinkComponent}>+ {labels.creditLink}+ </SectionLink>+ ),+ }+ : {})}>- {entries.length === 0 ? (- <EmptyState- className="p-6"- title="No classified commits yet"- description="Commit classification runs during indexing and fills this in on the next sync."- />- ) : (- <ProportionBar- className="max-w-[420px]"- label="Commits by type"- segments={entries.map(([category, n]) => ({- key: category,- label: category.charAt(0).toUpperCase() + category.slice(1),- value: n,- detail: `${n.toLocaleString()} · ${pct(n, total)}%`,- color: commitCategoryColor(category),- }))}- />- )}+ <p className="text-[15px] leading-relaxed text-[var(--color-text-secondary)]">+ {labels.creditSentence(credit.windowDays, credit.filesImproved, credit.findingsResolved)}+ </p></OverviewSection>);}diff --git a/packages/ui/src/owners/owner-relationships.tsx b/packages/ui/src/owners/owner-relationships.tsxnew file mode 100644index 000000000..abace7ecc--- /dev/null+++ b/packages/ui/src/owners/owner-relationships.tsx@@ -0,0 +1,95 @@+import * as React from "react";+import type { OwnerCoAuthor } from "@repowise-dev/types/owners";+import { OverviewSection } from "../overview/section";+import { EmptyState } from "../shared/empty-state";+import type { OwnershipLabels } from "./labels";+import { OwnerAvatar } from "./owner-avatar";++/**+ * Who else works in the same files.+ *+ * Overlap on a real repo is one partner and then a cliff — 15.8%, then 1.6%,+ * 1.2%, 1.0% — so a list of ten presents people who once touched the same+ * file at the weight of the person who actually shares the work. The lead+ * partner answers the question the section exists for (who reviews this, who+ * picks it up), and the tail is reported as a count.+ */+export function OwnerRelationships({+ coAuthors,+ total,+ hrefForCoAuthor,+ LinkComponent,+ labels,+}: {+ coAuthors: OwnerCoAuthor[];+ total: number;+ hrefForCoAuthor?: ((coAuthor: OwnerCoAuthor) => string) | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels: OwnershipLabels;+}) {+ const A = LinkComponent ?? "a";+ const [lead, second] = [...coAuthors].sort(+ (a, b) => b.co_change_strength - a.co_change_strength,+ );++ return (+ <OverviewSection+ title={labels.relationshipsTitle}+ description={labels.relationshipsDescription}+ >+ {!lead ? (+ <EmptyState+ className="p-6"+ title={labels.relationshipsEmptyTitle}+ description={labels.relationshipsEmptyDescription}+ />+ ) : (+ <div className="flex flex-col gap-3">+ <LeadPartner coAuthor={lead} href={hrefForCoAuthor?.(lead)} LinkComponent={A} labels={labels} />+ <p className="max-w-[62ch] text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">+ {total <= 1+ ? labels.relationshipsAlone+ : second+ ? labels.relationshipsNext(total - 1, (second.co_change_strength * 100).toFixed(1))+ : labels.relationshipsOthers(total - 1)}+ </p>+ </div>+ )}+ </OverviewSection>+ );+}++function LeadPartner({+ coAuthor,+ href,+ LinkComponent,+ labels,+}: {+ coAuthor: OwnerCoAuthor;+ href: string | undefined;+ LinkComponent: React.ElementType;+ labels: OwnershipLabels;+}) {+ const A = LinkComponent;+ const body = (+ <>+ <OwnerAvatar name={coAuthor.name} email={coAuthor.email} size="md" />+ <span className="min-w-0">+ <span className="block font-medium text-[var(--color-text-primary)] transition-colors group-hover:text-[var(--color-accent-primary)] [text-wrap:pretty]">+ {coAuthor.name || coAuthor.email || labels.unknownName}+ </span>+ <span className="block text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {labels.partnerLine(coAuthor.shared_files, (coAuthor.co_change_strength * 100).toFixed(1))}+ </span>+ </span>+ </>+ );++ return href ? (+ <A href={href} className="group flex w-fit items-center gap-3 no-underline">+ {body}+ </A>+ ) : (+ <span className="flex items-center gap-3">{body}</span>+ );+}diff --git a/packages/ui/src/owners/owner-table.tsx b/packages/ui/src/owners/owner-table.tsxindex e5142c431..95d3f724a 100644--- a/packages/ui/src/owners/owner-table.tsx+++ b/packages/ui/src/owners/owner-table.tsx@@ -1,6 +1,7 @@import * as React from "react";-import type { OwnerListEntry } from "@repowise-dev/types/owners";+import type { IdentityKind, OwnerListEntry } from "@repowise-dev/types/owners";import { formatRelativeTimeOrNull } from "../lib/format";+import { ownershipLabels, type OwnershipLabels } from "./labels";import { OwnerAvatar } from "./owner-avatar";export type OwnerSortKey =@@ -20,14 +21,21 @@ interface Column {// Sole-owned files are `bus_factor_risk_files` under a name a person would// use. "Bus factor" is jargon that names the metaphor rather than the fact.-const COLUMNS: Column[] = [- { key: "files_owned", label: "Files owned", hint: "Files where this person wrote most of the surviving lines", numeric: true },- { key: "hotspots_owned", label: "Hotspots", hint: "Owned files that are also high-churn", numeric: true },- { key: "bus_factor_risk_files", label: "Sole owner", hint: "Owned files nobody else has touched", numeric: true },- { key: "dead_code_lines_owned", label: "Dead lines", hint: "Unreachable lines still attributed here", numeric: true },- { key: "commit_count_90d", label: "Commits 90d", numeric: true },- { key: null, label: "Last touched", numeric: false },-];+function columns(l: OwnershipLabels): Column[] {+ return [+ { key: "files_owned", label: l.colFilesOwned, hint: l.colFilesOwnedHint, numeric: true },+ { key: "hotspots_owned", label: l.colHotspots, hint: l.colHotspotsHint, numeric: true },+ { key: "bus_factor_risk_files", label: l.colSoleOwner, hint: l.colSoleOwnerHint, numeric: true },+ { key: "dead_code_lines_owned", label: l.colDeadLines, hint: l.colDeadLinesHint, numeric: true },+ { key: "commit_count_90d", label: l.colCommits90d, numeric: true },+ { key: null, label: l.colLastTouched, numeric: false },+ ];+}++/** Automation is named; people, the default, carry no label. */+function kindLabel(kind: IdentityKind, l: OwnershipLabels): string {+ return { human: l.kindPerson, bot: l.kindBot, agent: l.kindAgent }[kind];+}export interface OwnerTableProps {owners: OwnerListEntry[];@@ -38,6 +46,7 @@ export interface OwnerTableProps {hrefFor?: ((owner: OwnerListEntry) => string) | undefined;onSelect?: ((owner: OwnerListEntry) => void) | undefined;LinkComponent?: React.ElementType | undefined;+ labels?: Partial<OwnershipLabels> | undefined;}/**@@ -64,8 +73,10 @@ export function OwnerTable({hrefFor,onSelect,LinkComponent,+ labels: overrides,}: OwnerTableProps) {const A = LinkComponent ?? "a";+ const labels = ownershipLabels(overrides);return (<div className="-mx-[var(--page-pad)] overflow-x-auto px-[var(--page-pad)] sm:mx-0 sm:px-0">@@ -76,9 +87,9 @@ export function OwnerTable({scope="col"className="border-b border-[var(--color-border-default)] pb-2 pr-3 text-left font-mono text-[10px] font-normal uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Contributor+ {labels.colContributor}</th>- {COLUMNS.map((c) => {+ {columns(labels).map((c) => {const active = c.key != null && c.key === sort;const head = (<span title={c.hint} className={c.hint ? "cursor-help" : undefined}>@@ -145,6 +156,11 @@ export function OwnerTable({{displayName}</span>)}+ {o.kind !== "human" && (+ <span className="mt-0.5 block font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {kindLabel(o.kind, labels)}+ </span>+ )}{o.email && o.email !== o.name && (<span className="mt-0.5 block font-mono text-[11.5px] text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">{o.email}@@ -163,13 +179,13 @@ export function OwnerTable({// committing: that is knowledge with no second reader and// nobody left to ask.marker={o.bus_factor_risk_files > 0 && o.commit_count_90d === 0}- markerTitle="Sole-owned files held by someone inactive for 90 days"+ markerTitle={labels.soleInactiveTitle}/><Num value={o.dead_code_lines_owned} /><Numvalue={o.commit_count_90d}atLeast={o.commit_count_90d_at_least}- atLeastTitle="At least this many: the indexed commits stop inside the 90 days"+ atLeastTitle={labels.atLeastTitle}/><td className="whitespace-nowrap py-2.5 pl-3 align-top text-[var(--color-text-tertiary)]">{formatRelativeTimeOrNull(o.last_commit_at) ?? "—"}diff --git a/packages/ui/src/owners/ownership-distribution-bar.tsx b/packages/ui/src/owners/ownership-distribution-bar.tsxdeleted file mode 100644index 12f3c1625..000000000--- a/packages/ui/src/owners/ownership-distribution-bar.tsx+++ /dev/null@@ -1,53 +0,0 @@-import * as React from "react";-import type { OwnerListEntry } from "@repowise-dev/types/owners";-import { ProportionBar, SHARE_STEPS } from "../shared/proportion-bar";--interface OwnershipDistributionBarProps {- owners: OwnerListEntry[];- /** Repo-wide contributor count (may exceed the loaded `owners`). */- totalContributors: number;- onSelect?: (owner: OwnerListEntry) => void;- /** Router link for the drill-in; defaults to a plain anchor. */- hrefFor?: (owner: OwnerListEntry) => string;- LinkComponent?: React.ElementType | undefined;-}--/**- * How owned files spread across contributors, as one proportional bar.- *- * The point is the shape: a bar dominated by one or two segments is a- * concentration risk, an even spread is healthy. Legend entries drill into- * the owner profile.- *- * A server component. It takes `hrefFor` as well as `onSelect`, so a- * server-rendered page links and only a page that genuinely needs the- * callback pays for hydration.- */-export function OwnershipDistributionBar({- owners,- totalContributors,- onSelect,- hrefFor,- LinkComponent,-}: OwnershipDistributionBarProps) {- // The fold names every contributor past the shown ones, not only the- // loaded page of them.- const others = Math.max(0, totalContributors - SHARE_STEPS.length);- return (- <ProportionBar- label="Owned files by contributor"- segments={owners.map((o) => ({- key: o.key,- label: o.name || o.email || "unknown",- value: o.files_owned,- ...(hrefFor- ? { href: hrefFor(o) }- : onSelect- ? { onSelect: () => onSelect(o) }- : {}),- }))}- othersLabel={(n) => `${Math.max(n, others).toLocaleString()} others`}- LinkComponent={LinkComponent}- />- );-}diff --git a/packages/ui/src/owners/ownership-lede.tsx b/packages/ui/src/owners/ownership-lede.tsxnew file mode 100644index 000000000..fa3d927aa--- /dev/null+++ b/packages/ui/src/owners/ownership-lede.tsx@@ -0,0 +1,153 @@+"use client";++import * as React from "react";+import type { OwnersSummary } from "@repowise-dev/types/owners";+import { AiPromptButton } from "../health/ai-prompt-button";+import { useAiPromptAction } from "../health/ai-prompt-action";+import { ReadsColumn, type ReadItem } from "../overview/reads-column";+import { PageLede } from "../shared/page-lede";+import { WELL_SHARED_MIN, type KnowledgeCoverage } from "./knowledge-coverage";+import { ownershipLabels, type OwnershipLabels } from "./labels";+import { spreadPromptRequest } from "./prompt-requests";++export type OwnershipTab = "risks" | "loss" | "offboarding";++export interface OwnershipLedeProps {+ coverage: KnowledgeCoverage;+ summary: OwnersSummary;+ /** Link to an Ownership tab, e.g. `?tab=risks`, with an off-boarding scenario. */+ hrefForTab: (tab: OwnershipTab, leave?: string[]) => string;+ repoName?: string | undefined;+ LinkComponent?: React.ElementType | undefined;+ labels?: Partial<OwnershipLabels> | undefined;+}++/** Whole percent, capped below 100 so a share short of everything never reads "100%". */+const pct = (share: number) => `${share >= 1 ? 100 : Math.min(99, Math.round(share * 100))}%`;++/** The reads beside the lede, each present only when it has something to point at. */+function ownershipReads(+ summary: OwnersSummary,+ hrefForTab: OwnershipLedeProps["hrefForTab"],+ labels: OwnershipLabels,+): ReadItem[] {+ const reads: ReadItem[] = [];+ if (summary.single_owner_hotspots > 0) {+ reads.push({+ key: "hotspots",+ label: labels.readHotspots,+ value: summary.single_owner_hotspots.toLocaleString(),+ unit: labels.readHotspotsUnit(summary.single_owner_files),+ why: labels.readHotspotsWhy,+ href: hrefForTab("risks"),+ });+ }+ if (summary.quiet_owners_total > 0) {+ reads.push({+ key: "quiet",+ label: labels.readQuiet,+ value: summary.quiet_owners_total.toLocaleString(),+ unit: labels.readQuietUnit(summary.quiet_owners_total),+ why: labels.readQuietWhy(summary.activity_window_days),+ href: hrefForTab("loss"),+ });+ }+ const tf = summary.truck_factor;+ if (tf != null) {+ // The truck factor is the fewest top owners covering half the owned files,+ // so within the concentration list those are the people; the read links to+ // their scenario without naming anyone.+ const owners = summary.concentration.owners;+ const keys = tf <= owners.length ? owners.slice(0, tf).map((o) => o.key) : [];+ reads.push({+ key: "truck",+ label: labels.readTruck,+ value: tf.toLocaleString(),+ why: labels.readTruckWhy,+ href: hrefForTab("offboarding", keys),+ });+ }+ return reads;+}++/** The coverage figure and its sentence; `share` is known here. */+function CoverageFigure({+ coverage,+ share,+ days,+ labels,+ onPrompt,+}: {+ coverage: KnowledgeCoverage;+ share: number;+ days: number;+ labels: OwnershipLabels;+ onPrompt: () => void;+}) {+ const byLines = coverage.basis === "nloc";+ const good = share >= WELL_SHARED_MIN;+ const single = coverage.singleHolderFiles;+ return (+ <PageLede+ label={labels.coverageLabel}+ labelHint={labels.coverageHint(byLines, days)}+ value={pct(share)}+ unit={labels.coverageUnit(byLines)}+ {...(good ? { valueColor: "var(--color-success)", band: { label: labels.wellShared, color: "var(--color-success)" } } : {})}+ >+ <p>+ {labels.coverageSentence(pct(share), byLines, days)}+ {single > 0 && ` ${labels.singleHolderSentence(single, coverage.files)}`}+ </p>+ {single > 0 && <AiPromptButton className="mt-3" onClick={onPrompt} label={labels.agentPrompt} />}+ </PageLede>+ );+}++/**+ * The Ownership page's one figure: how much of the code that is changing has+ * a second person who knows it. Good news reads calm green; a low share reads+ * plain, never as an alarm. The primary action hands the single-person+ * changing files to the reader's agent for a plan to spread what they know.+ */+export function OwnershipLede({+ coverage,+ summary,+ hrefForTab,+ repoName,+ LinkComponent,+ labels: overrides,+}: OwnershipLedeProps) {+ const labels = React.useMemo(() => ownershipLabels(overrides), [overrides]);+ const { openPrompt, promptModal } = useAiPromptAction();+ const reads = ownershipReads(summary, hrefForTab, labels);+ const days = summary.activity_window_days;++ return (+ <section className="grid grid-cols-1 items-start gap-6 lg:grid-cols-[minmax(0,1fr)_300px] lg:gap-10">+ {coverage.share == null ? (+ <p className="max-w-[62ch] text-[15px] leading-relaxed text-[var(--color-text-secondary)]">+ {labels.noChanges(days)}+ </p>+ ) : (+ <CoverageFigure+ coverage={coverage}+ share={coverage.share}+ days={days}+ labels={labels}+ onPrompt={() =>+ openPrompt(+ spreadPromptRequest(coverage.singleHolderAreas, labels, {+ // The prompt itself stays English: it is written for the agent.+ spreadReason: `each one changed in the last ${days} days`,+ repoName,+ }),+ )+ }+ />+ )}+ {reads.length > 0 && <ReadsColumn items={reads} LinkComponent={LinkComponent} />}+ {promptModal}+ </section>+ );+}diff --git a/packages/ui/src/owners/people-picker.tsx b/packages/ui/src/owners/people-picker.tsxnew file mode 100644index 000000000..49262e567--- /dev/null+++ b/packages/ui/src/owners/people-picker.tsx@@ -0,0 +1,233 @@+"use client";++import * as React from "react";+import { Search, X } from "lucide-react";+import { Input } from "../ui/input";+import { OwnerAvatar } from "./owner-avatar";+import type { KnowledgePerson } from "./knowledge-files";++export interface PeoplePickerProps {+ people: readonly KnowledgePerson[];+ selected: readonly string[];+ onChange: (keys: string[]) => void;+ /** Accessible name and placeholder. */+ label?: string;+ placeholder?: string;+ /** Accessible name of a chip's remove button. */+ removeLabel?: (name: string) => string;+ /** Accessible name of the chip list. */+ selectedLabel?: string;+}++/** Matches listed before the reader narrows the search. */+const MAX_OPTIONS = 8;++/** People not yet picked whose name or email contains the query. */+export function matchPeople(+ people: readonly KnowledgePerson[],+ selected: readonly string[],+ query: string,+ limit = MAX_OPTIONS,+): KnowledgePerson[] {+ const chosen = new Set(selected);+ const needle = query.trim().toLowerCase();+ const hit = (p: KnowledgePerson) =>+ !needle || p.name.toLowerCase().includes(needle) || (p.email ?? "").toLowerCase().includes(needle);+ return people.filter((p) => !chosen.has(p.key) && hit(p)).slice(0, limit);+}++/**+ * Searchable multi-select of people, with avatars. A combobox over a plain+ * list: type to filter by name or email, arrows to move, Enter to add,+ * Backspace on an empty field to drop the last pick.+ */+export function PeoplePicker({+ people,+ selected,+ onChange,+ label = "Pick people",+ placeholder = "Search by name or email…",+ removeLabel = (name) => `Remove ${name}`,+ selectedLabel = "Selected people",+}: PeoplePickerProps) {+ const [query, setQuery] = React.useState("");+ const [open, setOpen] = React.useState(false);+ const [active, setActive] = React.useState(0);+ const listId = React.useId();+ const byKey = React.useMemo(() => new Map(people.map((p) => [p.key, p])), [people]);+ const options = matchPeople(people, selected, query);+ const showList = open && options.length > 0;++ const add = (key: string) => {+ onChange([...selected, key]);+ setQuery("");+ setActive(0);+ };+ const remove = (key: string) => onChange(selected.filter((k) => k !== key));+ const onKeyDown = comboboxKeyHandler({+ count: options.length,+ setActive,+ setOpen,+ onEnter: () => (open && options[active] ? add(options[active]!.key) : false),+ onBackspaceEmpty: () => (query === "" && selected.length > 0 ? remove(selected.at(-1)!) : false),+ });++ return (+ <div className="flex flex-col gap-2">+ <SelectedPeople+ keys={selected}+ byKey={byKey}+ onRemove={remove}+ removeLabel={removeLabel}+ label={selectedLabel}+ />+ <div className="relative max-w-sm">+ <Search className="pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-[var(--color-text-tertiary)]" />+ <Input+ role="combobox"+ aria-label={label}+ aria-expanded={showList}+ aria-controls={listId}+ aria-autocomplete="list"+ {...(showList ? { "aria-activedescendant": `${listId}-${active}` } : {})}+ value={query}+ placeholder={placeholder}+ className="pl-8"+ onChange={(e) => {+ setQuery(e.target.value);+ setOpen(true);+ setActive(0);+ }}+ onFocus={() => setOpen(true)}+ // Options cancel mousedown, so a click on one never blurs the field first.+ onBlur={() => setOpen(false)}+ onKeyDown={onKeyDown}+ />+ {showList && (+ <PeopleOptions id={listId} options={options} active={active} onHover={setActive} onPick={add} />+ )}+ </div>+ </div>+ );+}++/** Keys that move or pick, whose browser default (caret move, form submit) must not run. */+const CONSUMED_KEYS = new Set(["ArrowDown", "ArrowUp", "Enter"]);++/** Arrow, Enter, Escape and Backspace handling for a combobox over `count` options. */+function comboboxKeyHandler({+ count,+ setActive,+ setOpen,+ onEnter,+ onBackspaceEmpty,+}: {+ count: number;+ setActive: React.Dispatch<React.SetStateAction<number>>;+ setOpen: (open: boolean) => void;+ /** Returns false when there was nothing to pick. */+ onEnter: () => void | false;+ onBackspaceEmpty: () => void | false;+}) {+ return (e: React.KeyboardEvent<HTMLInputElement>) => {+ const keys: Record<string, () => void | false> = {+ ArrowDown: () => {+ setOpen(true);+ setActive((i) => Math.min(i + 1, Math.max(count - 1, 0)));+ },+ ArrowUp: () => setActive((i) => Math.max(i - 1, 0)),+ Enter: onEnter,+ Escape: () => setOpen(false),+ Backspace: onBackspaceEmpty,+ };+ const handled = keys[e.key]?.() !== false;+ if (handled && CONSUMED_KEYS.has(e.key)) e.preventDefault();+ };+}++function SelectedPeople({+ keys,+ byKey,+ onRemove,+ removeLabel,+ label,+}: {+ keys: readonly string[];+ byKey: ReadonlyMap<string, KnowledgePerson>;+ onRemove: (key: string) => void;+ removeLabel: (name: string) => string;+ label: string;+}) {+ if (keys.length === 0) return null;+ return (+ <ul aria-label={label} className="flex flex-wrap gap-1.5">+ {keys.map((key) => {+ const p = byKey.get(key) ?? { key, name: key, email: null };+ return (+ <li+ key={key}+ className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] py-0.5 pl-0.5 pr-1 text-xs text-[var(--color-text-primary)]"+ >+ <OwnerAvatar name={p.name} email={p.email} size="sm" />+ {p.name}+ <button+ type="button"+ onClick={() => onRemove(key)}+ aria-label={removeLabel(p.name)}+ className="rounded-full p-0.5 text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <X className="h-3 w-3" />+ </button>+ </li>+ );+ })}+ </ul>+ );+}++function PeopleOptions({+ id,+ options,+ active,+ onHover,+ onPick,+}: {+ id: string;+ options: readonly KnowledgePerson[];+ active: number;+ onHover: (index: number) => void;+ onPick: (key: string) => void;+}) {+ return (+ <ul+ id={id}+ role="listbox"+ className="absolute z-20 mt-1 max-h-72 w-full overflow-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-overlay)] py-1 shadow-lg"+ >+ {options.map((p, i) => (+ <li+ key={p.key}+ id={`${id}-${i}`}+ role="option"+ aria-selected={i === active}+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => onPick(p.key)}+ onMouseEnter={() => onHover(i)}+ className={`flex cursor-pointer items-center gap-2 px-2.5 py-1.5 text-sm ${+ i === active ? "bg-[var(--color-bg-elevated)]" : ""+ }`}+ >+ <OwnerAvatar name={p.name} email={p.email} size="sm" />+ <span className="min-w-0">+ <span className="block text-[var(--color-text-primary)]">{p.name}</span>+ {p.email && p.email !== p.name && (+ <span className="block truncate text-xs text-[var(--color-text-tertiary)]" title={p.email}>+ {p.email}+ </span>+ )}+ </span>+ </li>+ ))}+ </ul>+ );+}diff --git a/packages/ui/src/owners/prompt-requests.ts b/packages/ui/src/owners/prompt-requests.tsnew file mode 100644index 000000000..833423823--- /dev/null+++ b/packages/ui/src/owners/prompt-requests.ts@@ -0,0 +1,66 @@+/**+ * The two prompt requests the Ownership views hand to the shared prompt+ * modal: a plan to spread knowledge one person holds, and a handover plan for+ * people leaving. The modal chrome is labelled; the prompt stays English.+ */++import type { AiPromptRequest } from "../health/ai-prompt-action";+import { buildHandoverPrompt, offboardingPromptAreas, riskPromptAreas } from "./handover-prompt";+import { joinNames } from "./knowledge-files";+import type { KnowledgeRiskArea } from "./knowledge-risks";+import type { OwnershipLabels } from "./labels";+import type { OffboardingArea, OffboardingResult } from "./offboarding";++const rootOrDir = (areas: readonly { dir: string }[], labels: OwnershipLabels) =>+ areas.length === 1 ? areas[0]!.dir || labels.repositoryRoot : null;++/** A plan for a second person to learn single-holder files, by area. */+export function spreadPromptRequest(+ areas: readonly KnowledgeRiskArea[],+ labels: OwnershipLabels,+ options: { spreadReason?: string; repoName?: string | undefined } = {},+): AiPromptRequest {+ const people = Array.from(new Set(areas.flatMap((a) => a.files.map((f) => f.holder.name))));+ const promptAreas = riskPromptAreas(areas);+ const files = areas.reduce((s, a) => s + a.fileCount, 0);+ return {+ title: labels.spreadTitle,+ description: labels.spreadDescription(files),+ filePath: rootOrDir(areas, labels),+ getPrompt: (flavor) =>+ buildHandoverPrompt({+ purpose: "spread",+ people,+ areas: promptAreas,+ flavor,+ ...(options.spreadReason ? { spreadReason: options.spreadReason } : {}),+ ...(options.repoName ? { repoName: options.repoName } : {}),+ }),+ };+}++/** A handover plan for some areas of an off-boarding result. */+export function handoverPromptRequest(+ result: OffboardingResult,+ areas: readonly OffboardingArea[],+ labels: OwnershipLabels,+ repoName?: string,+): AiPromptRequest {+ const people = result.leaving.map((p) => p.name);+ const promptAreas = offboardingPromptAreas(areas);+ const files = promptAreas.reduce((s, a) => s + a.files.length, 0);+ return {+ title: labels.handoverTitle,+ description: labels.handoverDescription(files, joinNames(people)),+ filePath: rootOrDir(areas, labels),+ getPrompt: (flavor) =>+ buildHandoverPrompt({+ purpose: "handover",+ people,+ areas: promptAreas,+ flavor,+ threshold: result.threshold,+ ...(repoName ? { repoName } : {}),+ }),+ };+}diff --git a/packages/ui/src/shared/path-text.tsx b/packages/ui/src/shared/path-text.tsxnew file mode 100644index 000000000..4b2ebd267--- /dev/null+++ b/packages/ui/src/shared/path-text.tsx@@ -0,0 +1,33 @@+import * as React from "react";+import { cn } from "../lib/cn";++/**+ * A repository path with a break opportunity after each separator.+ *+ * Without it a 72-character path in a narrow column breaks mid-identifier and+ * wraps to ten lines; with it, it breaks between directories and wraps to two.+ * `<wbr>` rather than a zero-width space so the path is still clean when it is+ * copied out of the page. Turns accent under a `group` link on hover.+ */+export function PathText({ path, className }: { path: string; className?: string }) {+ const segments = path.split("/");+ return (+ <span+ className={cn(+ "font-mono text-xs text-[var(--color-text-primary)] transition-colors group-hover:text-[var(--color-accent-primary)] [overflow-wrap:anywhere]",+ className,+ )}+ >+ {segments.map((seg, i) => (+ <React.Fragment key={i}>+ {i > 0 && (+ <>+ /<wbr />+ </>+ )}+ {seg}+ </React.Fragment>+ ))}+ </span>+ );+}diff --git a/packages/web/messages/en.json b/packages/web/messages/en.jsonindex 1d27288c8..59fd47d71 100644--- a/packages/web/messages/en.json+++ b/packages/web/messages/en.json@@ -142,7 +142,7 @@"refactoring": "Refactoring","files": "Files","commits": "Commits",- "contributors": "Contributors",+ "contributors": "Ownership","decisions": "Decisions","stats": "Stats","usageAndSavings": "Usage & savings",@@ -176,7 +176,7 @@"decisions": "Decisions","commits": "Commits","changes": "Changes",- "owners": "Contributors",+ "owners": "Ownership","modules": "Modules","wiki": "Wiki","health": "Code Health",@@ -579,17 +579,178 @@"reviewDescription": "Split by what each record's acceptance amounts to, not by a status word. Every record is in exactly one lane and the counts add up: what governs, what nobody has reviewed, what has drifted from the code it names, what names nothing at all, and what has been retired."},"contributors": {- "title": "Contributors",- "description": "Who knows what, mined from full git history. Ownership follows whoever wrote the surviving lines, not whoever committed last.",+ "title": "Ownership",+ "description": "Who knows which code, mined from full git history. Ownership follows whoever wrote the surviving lines, not whoever committed last.","profileTitle": "Contributor","profileEmptyTitle": "No profile for this contributor","profileEmptyDescription": "Nobody by this name or address appears in the indexed git history. They may have committed under a different address, or the history may not have been synced yet.",- "profileBack": "All contributors",- "loadFailedTitle": "Couldn't load contributors",- "loadFailed": "The contributor list could not be loaded. Check that the API is reachable and try again.",+ "profileBack": "Ownership",+ "loadFailedTitle": "Couldn't load ownership",+ "loadFailed": "The people list could not be loaded. Check that the API is reachable and try again.","tenureSince": "Committing here since {date}","tenureLastTouched": "last touched {time}",- "unknownName": "unknown"+ "unknownName": "unknown",+ "tabsLabel": "Ownership views",+ "tabs": {+ "overview": "Overview",+ "risks": "Knowledge risks",+ "loss": "Knowledge loss",+ "offboarding": "Off-boarding"+ },+ "offboardingSuggestion": "the truck factor ({names})",+ "openInOffboarding": "Open in off-boarding",+ "matrixLoadFailed": "The per-file author shares could not be loaded. Check that the API is reachable and try again.",+ "ui": {+ "agentPrompt": "Copy prompt for your agent",+ "promptForGroup": "{count, plural, one {Copy prompt for this one} other {Copy prompt for these #}}",+ "repositoryRoot": "(repository root)",+ "hotspot": "Hotspot",+ "files": "{count, plural, one {# file} other {# files}}",+ "showAllFiles": "Show all {count, number} files",+ "showAllDirectories": "Show all {count, number} directories",+ "noOtherAuthor": "no other author",+ "coverageLabel": "Knowledge coverage",+ "coverageHint": "Share {basis, select, lines {of the code} other {of the files}} changed in the last {days} days in files two or more people hold (bus factor 2 or more), {basis, select, lines {weighted by lines of code} other {by file count}}. Files with no indexed history are left out.",+ "coverageUnit": "{basis, select, lines {of the code} other {of the files}} changed lately",+ "wellShared": "Well shared",+ "coverageSentence": "{pct} {basis, select, lines {of the code} other {of the files}} changed in the last {days} days{basis, select, lines {, by lines,} other {}} has two or more people who know it.",+ "singleHolderSentence": "{single, number} of the {files, plural, one {# changing file} other {# changing files}} {single, plural, one {has} other {have}} one main author; your agent can plan how a second person learns them.",+ "noChanges": "No code with history changed in the last {days} days, so there is no moving code to measure knowledge coverage on.",+ "spreadTitle": "Spread the knowledge",+ "spreadDescription": "A plan for a second person to learn {count, plural, one {# file} other {# files}} one person holds.",+ "readHotspots": "Single-author hotspots",+ "readHotspotsUnit": "of {count, plural, one {# single-author file} other {# single-author files}}",+ "readHotspotsWhy": "Busy files only one person has written. The cheapest place to get a second reader.",+ "readQuiet": "Quiet owners of changing code",+ "readQuietUnit": "{count, plural, one {person} other {people}}",+ "readQuietWhy": "No commit in {days} days, yet files they own changed in that time.",+ "readTruck": "Fewest people holding half the owned files",+ "readTruckWhy": "The truck factor. Open the off-boarding view to see what depends on them.",+ "everyone": "Everyone",+ "everyoneDescription": "A dot marks sole-owned files held by someone who has stopped committing, so a clean column means nothing to chase.",+ "people": "{all, select, yes {{count, plural, one {# contributor} other {# contributors}}} other {{count, plural, one {# person} other {# people}}}}",+ "searchPlaceholder": "Filter by name or email…",+ "searchLabel": "Filter people by name or email",+ "showAutomation": "Show {count, plural, one {# bot and agent identity} other {# bot and agent identities}}",+ "noMatch": "Nobody matches this search",+ "clearSearch": "Clear search",+ "noPeople": "No people yet",+ "noPeopleDescription": "People land with the first git index.",+ "showAllPeople": "Show all {all, select, yes {{count, plural, one {# contributor} other {# contributors}}} other {{count, plural, one {# person} other {# people}}}}",+ "loading": "Loading…",+ "risksIntro": "{files, plural, one {# file has} other {# files have}} one author and matter right now: {hotspots, plural, one {# is a hotspot} other {# are hotspots}} and {lowHealth, plural, one {# is} other {# are}} in weak health, across {dirs, plural, one {# directory} other {# directories}}. Hand them to your agent for a plan to get a second person reading each one.",+ "risksCleanTitle": "Every hotspot and weak file has a second author, across {count, number} files",+ "risksCleanDescription": "Knowledge here is shared: no busy or weak file depends on a single person’s history.",+ "risksOneHolder": "{name} wrote nearly all of it",+ "risksManyHolders": "{holders, number} people each hold their own files",+ "risksManyHoldersTop": "{holders, number} people each hold their own files, {name} the most ({files, number})",+ "risksSevere": "{count, plural, one {# is} other {# are}} both a hotspot and in weak health",+ "risksListLabel": "Directories with knowledge held by one person",+ "lossIntro": "{total, plural, one {# person has} other {# people have}} not committed in {days} days but still own files that changed in that time. Each row shows which of the files that changed lately would have no majority author without them, and who is best placed to pick each directory up.",+ "lossShowing": "Showing the {shown, number} with the most changing code.",+ "lossCleanTitle": "Everyone who owns changing code has committed in the last {days} days",+ "lossCleanDescription": "Across {people, plural, one {# person} other {# people}} and {files, plural, one {# owned file} other {# owned files}}, no file that changed lately belongs to someone who has stopped committing.",+ "lossCarriedTitle": "Others already carry the code that is still changing",+ "lossCarriedDescription": "Every file that changed in the last {days} days keeps a majority of its commits with people who are still here, even without all {quiet, plural, one {# quiet owner} other {# quiet owners}}.",+ "lossLastCommit": "Last commit {when}.",+ "lossChangingOne": "The one file they own changed lately.",+ "lossChanging": "{changing, number} of the {owned, number} files they own changed lately.",+ "lossAtRisk": "Without them, {files, plural, one {# file that changed lately has} other {# files that changed lately have}} no majority author left.",+ "lossAtRiskSevere": "Without them, {files, plural, one {# file that changed lately has} other {# files that changed lately have}} no majority author left, {severe, number} of them hotspots or in weak health.",+ "lossNoneAtRisk": "The people who stay hold the majority of every changing file they worked on.",+ "lossDirectories": "{open, select, yes {Hide} other {Show}} {count, plural, one {# directory} other {# directories}}",+ "lossListLabel": "Quiet owners of changing code",+ "leavingLabel": "If these people left",+ "leavingPicker": "People leaving",+ "thresholdLabel": "At risk below {pct}% kept",+ "thresholdHelp": "A file is at risk when the people who stay made less than this share of its commits.",+ "tryLabel": "Try:",+ "pickPrompt": "Pick one or more people to see which files would lose most of the knowledge behind them, and who is best placed to take each directory over. Nothing is saved; the scenario lives in the page address, so you can share it.",+ "pickerPlaceholder": "Search by name or email…",+ "removePerson": "Remove {name}",+ "selectedPeople": "Selected people",+ "unknownPeople": "None of the selected people appear in the indexed history. They may have committed under a different address; search for them by name.",+ "nothingDependsTitle": "Nothing depends on {names} alone",+ "nothingDependsDescription": "The people who stay hold at least {threshold} of the commits on all {files, plural, one {# file} other {# files}} {names} worked on.",+ "noShareTitle": "{count, plural, one {{names} holds} other {{names} hold}} no share of the indexed code",+ "noShareDescription": "No code file lists them among its top five authors.",+ "resultSentence": "Without {names}, {files, plural, one {# file} other {# files}} would be left with authors holding under {threshold} of the commits: {codeShare} of the code. {kept, number} more carry some of their history but keep at least {threshold} with the people who stay.",+ "resultSentenceSevere": "Without {names}, {files, plural, one {# file} other {# files}} would be left with authors holding under {threshold} of the commits: {codeShare} of the code, {severe, number} of them hotspots or in weak health. {kept, number} more carry some of their history but keep at least {threshold} with the people who stay.",+ "statAtRisk": "Files at risk",+ "statHotspots": "Hotspots among them",+ "statHotspotsHint": "At-risk files in the repository’s high-churn band",+ "statShare": "Share of code",+ "statShareHint": "Lines of code in at-risk files, of {nloc, number} across {files, plural, one {# file} other {# files}}",+ "statDirectories": "Directories",+ "heir": "{name} could take over: the strongest remaining author on {files, number} of {of, number}",+ "noHeir": "Nobody who stays is among these files’ main authors",+ "heirSevere": "{count, plural, one {# is a hotspot or in} other {# are hotspots or in}} weak health",+ "handoverTitle": "Plan the handover",+ "handoverDescription": "A handover plan for {files, plural, one {# file} other {# files}} that depend on {names}.",+ "offboardingListLabel": "Directories that would lose their majority author",+ "underOnePercent": "under 1%",+ "dependsTitle": "What depends on them",+ "dependsDescription": "Files where this person made most of the commits, so the people who stay would hold under half of the history, and who is best placed to take each directory over.",+ "ownershipLink": "Ownership",+ "filesCarryTitle": "Files they carry",+ "filesCarryHint": "{shown, number} of {touched, number} touched",+ "filesCarryDescription": "The files with the most commits attributed to this person. Churn is a percentile against every file in the repo. A dot marks a high-churn file they alone maintain and wrote at least 90% of the commits for: {sole, number} of these {shown, number}.",+ "filesCarryDescriptionNone": "The files with the most commits attributed to this person. Churn is a percentile against every file in the repo. A dot marks a high-churn file they alone maintain and wrote at least 90% of the commits for, and none of these qualify.",+ "commitMixTitle": "What they commit",+ "commitMixDescription": "{total, plural, one {# commit} other {# commits}} classified from the subject line, across every file this person has touched.",+ "commitMixEmptyTitle": "No classified commits yet",+ "commitMixEmptyDescription": "Commit classification runs during indexing and fills this in on the next sync.",+ "commitMixBarLabel": "Commits by type",+ "creditTitle": "What they improved",+ "creditLink": "See the commits",+ "creditSentence": "In the last {days} days their commits made {files, plural, one {# file} other {# files}} healthier and resolved {findings, plural, one {# finding} other {# findings}}.",+ "activityLabel": "Activity",+ "activeLine": "Active: {floor, select, yes {at least } other {}}{commits, plural, one {# commit} other {# commits}} in the last 90 days",+ "quietLine": "Quiet: no commit in the last 90 days",+ "emailLabel": "Email",+ "aliasesLabel": "Also commits as",+ "footprintTitle": "Where they work",+ "footprintDescription": "Files they are the main owner of, by top-level directory. Share is the fraction of each directory’s files where this person wrote most of the surviving lines.",+ "footprintEmptyTitle": "No directory attribution yet",+ "footprintEmptyDescription": "Ownership by directory appears after the next git sync.",+ "footprintBarLabel": "Owned files by directory",+ "footprintDetail": "{files, plural, one {# file} other {# files}} · {pct}% theirs",+ "relationshipsTitle": "Who else works here",+ "relationshipsDescription": "People editing the same files. Overlap is the share of this person’s files the other has also committed to, so it reads as how much of their work is genuinely shared.",+ "relationshipsEmptyTitle": "Nobody else has touched these files",+ "relationshipsEmptyDescription": "Co-authorship appears once a second person commits to a file this person owns.",+ "relationshipsAlone": "Nobody else shares a file with this person.",+ "relationshipsNext": "The next closest of {others, plural, one {# other person} other {# other people}} overlaps on {pct}%, so there is one natural reviewer here rather than a shortlist.",+ "relationshipsOthers": "{others, plural, one {# other person shares} other {# other people share}} at least one file.",+ "partnerLine": "{files, plural, one {# shared file} other {# shared files}} · {pct}% of this person’s work overlaps theirs",+ "unknownName": "unknown",+ "fileTableEmptyTitle": "No file attribution yet",+ "fileTableEmptyDescription": "File-level ownership appears after the next git sync.",+ "colFile": "File",+ "colCommits90d": "Commits 90d",+ "colChurn": "Churn",+ "colChurnHint": "Percentile rank of this file’s change frequency against every file in the repo",+ "colTheirCommits": "Their commits",+ "colTheirCommitsHint": "Share of this file’s commits written by this person",+ "colTouched": "Touched",+ "soleCarriedTitle": "High-churn file this person alone maintains",+ "fileMeta": "{commits, plural, one {# commit} other {# commits}} in 90d · churn {churn} · {ownPct} of its commits · touched {touched}",+ "colContributor": "Contributor",+ "colFilesOwned": "Files owned",+ "colFilesOwnedHint": "Files where this person wrote most of the surviving lines",+ "colHotspots": "Hotspots",+ "colHotspotsHint": "Owned files that are also high-churn",+ "colSoleOwner": "Sole owner",+ "colSoleOwnerHint": "Owned files nobody else has touched",+ "colDeadLines": "Dead lines",+ "colDeadLinesHint": "Unreachable lines still attributed here",+ "colLastTouched": "Last touched",+ "kindPerson": "Person",+ "kindBot": "Bot",+ "kindAgent": "Coding agent",+ "soleInactiveTitle": "Sole-owned files held by someone inactive for 90 days",+ "atLeastTitle": "At least this many: the indexed commits stop inside the 90 days"+ }},"costs": {"spendEmptyTitle": "No model calls recorded yet",diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.jsonindex 5615464e4..1688a1b74 100644--- a/packages/web/messages/zh-CN.json+++ b/packages/web/messages/zh-CN.json@@ -142,7 +142,7 @@"refactoring": "重构","files": "文件","commits": "提交",- "contributors": "贡献者",+ "contributors": "代码所有权","decisions": "决策","stats": "统计","usageAndSavings": "用量与节省",@@ -176,7 +176,7 @@"decisions": "决策","commits": "提交","changes": "变更",- "owners": "贡献者",+ "owners": "代码所有权","modules": "模块","wiki": "维基","health": "代码健康",@@ -579,17 +579,178 @@"reviewDescription": "按每条记录的「被接受」实际意味着什么来划分,而不是按状态词划分。每条记录只落在一个分区里,计数可以相加:有约束力的、无人评审过的、与所指向代码已脱节的、什么都指不到的,以及已退役的。"},"contributors": {- "title": "贡献者",- "description": "谁懂哪部分代码,从完整 git 历史中挖掘得出。归属跟随仍然存活的那些行的作者,而不是最后提交的人。",+ "title": "代码所有权",+ "description": "谁熟悉哪部分代码,从完整 git 历史中挖掘得出。所有权跟随仍然存活的那些行的作者,而不是最后提交的人。","profileTitle": "贡献者","profileEmptyTitle": "该贡献者没有可展示的资料","profileEmptyDescription": "已索引的 git 历史中没有这个名字或地址。对方可能用了别的地址提交,或者历史尚未同步。",- "profileBack": "全部贡献者",- "loadFailedTitle": "无法加载贡献者",- "loadFailed": "无法加载贡献者列表。请确认接口可访问后重试。",+ "profileBack": "代码所有权",+ "loadFailedTitle": "无法加载代码所有权",+ "loadFailed": "无法加载人员列表。请确认接口可访问后重试。","tenureSince": "自 {date} 起在此提交","tenureLastTouched": "最近提交于 {time}",- "unknownName": "未知"+ "unknownName": "未知",+ "tabsLabel": "代码所有权视图",+ "tabs": {+ "overview": "概览",+ "risks": "知识风险",+ "loss": "知识流失",+ "offboarding": "离职模拟"+ },+ "offboardingSuggestion": "卡车因子对应的成员({names})",+ "openInOffboarding": "在离职模拟中打开",+ "matrixLoadFailed": "无法加载每个文件的作者占比。请确认 API 可以访问,然后重试。",+ "ui": {+ "agentPrompt": "复制给智能体的提示词",+ "promptForGroup": "{count, plural, one {为这一项复制提示词} other {为这 # 项复制提示词}}",+ "repositoryRoot": "(仓库根目录)",+ "hotspot": "热点",+ "files": "{count, plural, other {# 个文件}}",+ "showAllFiles": "显示全部 {count, number} 个文件",+ "showAllDirectories": "显示全部 {count, number} 个目录",+ "noOtherAuthor": "无其他作者",+ "coverageLabel": "知识覆盖率",+ "coverageHint": "过去 {days} 天内变更的{basis, select, lines {代码} other {文件}}中,由两人或以上掌握(总线因子 2 或以上)的文件所占比例,{basis, select, lines {按代码行数加权} other {按文件数计算}}。没有索引历史的文件不计入。",+ "coverageUnit": "近期变更的{basis, select, lines {代码} other {文件}}",+ "wellShared": "分布良好",+ "coverageSentence": "过去 {days} 天内变更的{basis, select, lines {代码(按行数计)} other {文件}}中,有 {pct} 由两人或以上熟悉。",+ "singleHolderSentence": "{files, number} 个变更文件中有 {single, number} 个只有一位主要作者;你的智能体可以规划如何让第二个人熟悉它们。",+ "noChanges": "过去 {days} 天内没有带历史的代码发生变更,因此没有可衡量知识覆盖率的活跃代码。",+ "spreadTitle": "扩散知识",+ "spreadDescription": "让第二个人熟悉由一人掌握的 {count, number} 个文件的计划。",+ "readHotspots": "单一作者热点",+ "readHotspotsUnit": "共 {count, number} 个单一作者文件",+ "readHotspotsWhy": "只有一个人写过的繁忙文件。最容易找到第二位阅读者的地方。",+ "readQuiet": "变更代码的沉寂所有者",+ "readQuietUnit": "人",+ "readQuietWhy": "{days} 天内没有提交,但他们拥有的文件在此期间发生了变更。",+ "readTruck": "掌握一半已归属文件的最少人数",+ "readTruckWhy": "即卡车因子。打开离职模拟查看有哪些代码依赖他们。",+ "everyone": "所有人",+ "everyoneDescription": "圆点标记由已停止提交的人独自拥有的文件,因此这一列为空就表示没有需要跟进的事项。",+ "people": "{all, select, yes {{count, number} 位贡献者} other {{count, number} 人}}",+ "searchPlaceholder": "按姓名或邮箱筛选…",+ "searchLabel": "按姓名或邮箱筛选人员",+ "showAutomation": "显示 {count, number} 个机器人和智能体身份",+ "noMatch": "没有人符合此搜索",+ "clearSearch": "清除搜索",+ "noPeople": "暂无人员",+ "noPeopleDescription": "首次建立 git 索引后会出现人员。",+ "showAllPeople": "显示全部 {all, select, yes {{count, number} 位贡献者} other {{count, number} 人}}",+ "loading": "加载中…",+ "risksIntro": "{files, number} 个文件只有一位作者,且当下很重要:其中 {hotspots, number} 个是热点,{lowHealth, number} 个健康度偏弱,分布在 {dirs, number} 个目录中。交给你的智能体,规划让第二个人逐一熟悉它们。",+ "risksCleanTitle": "在 {count, number} 个文件中,每个热点和偏弱文件都有第二位作者",+ "risksCleanDescription": "这里的知识是共享的:没有繁忙或偏弱的文件依赖单个人的历史。",+ "risksOneHolder": "几乎全部由 {name} 编写",+ "risksManyHolders": "{holders, number} 人各自掌握自己的文件",+ "risksManyHoldersTop": "{holders, number} 人各自掌握自己的文件,其中 {name} 最多({files, number} 个)",+ "risksSevere": "其中 {count, number} 个既是热点又健康度偏弱",+ "risksListLabel": "知识由一人掌握的目录",+ "lossIntro": "{total, number} 人在 {days} 天内没有提交,但仍拥有在此期间变更过的文件。每一行显示:没有他们时,近期变更的文件中哪些将失去多数作者,以及谁最适合接手各个目录。",+ "lossShowing": "仅显示变更代码最多的 {shown, number} 人。",+ "lossCleanTitle": "所有拥有变更代码的人都在过去 {days} 天内有过提交",+ "lossCleanDescription": "在 {people, number} 人和 {files, number} 个已归属文件中,近期变更的文件都不属于已停止提交的人。",+ "lossCarriedTitle": "仍在变更的代码已有其他人承担",+ "lossCarriedDescription": "过去 {days} 天内变更的每个文件,即使没有全部 {quiet, number} 位沉寂所有者,其多数提交仍由在职的人完成。",+ "lossLastCommit": "最近提交于 {when}。",+ "lossChangingOne": "他们拥有的唯一一个文件近期有变更。",+ "lossChanging": "他们拥有的 {owned, number} 个文件中有 {changing, number} 个近期有变更。",+ "lossAtRisk": "没有他们时,{files, number} 个近期变更的文件将失去多数作者。",+ "lossAtRiskSevere": "没有他们时,{files, number} 个近期变更的文件将失去多数作者,其中 {severe, number} 个是热点或健康度偏弱。",+ "lossNoneAtRisk": "留下的人掌握了他们参与过的每个变更文件的多数提交。",+ "lossDirectories": "{open, select, yes {隐藏} other {显示}} {count, number} 个目录",+ "lossListLabel": "变更代码的沉寂所有者",+ "leavingLabel": "如果这些人离开",+ "leavingPicker": "离开的人员",+ "thresholdLabel": "保留低于 {pct}% 即为有风险",+ "thresholdHelp": "当留下的人在某文件中的提交占比低于此值时,该文件即为有风险。",+ "tryLabel": "试试:",+ "pickPrompt": "选择一人或多人,查看哪些文件会失去背后的大部分知识,以及谁最适合接手各个目录。不会保存任何内容;场景保存在页面地址中,便于分享。",+ "pickerPlaceholder": "按姓名或邮箱搜索…",+ "removePerson": "移除 {name}",+ "selectedPeople": "已选人员",+ "unknownPeople": "所选人员均未出现在已索引的历史中。他们可能使用了其他地址提交;请按姓名搜索。",+ "nothingDependsTitle": "没有代码只依赖 {names}",+ "nothingDependsDescription": "在 {names} 参与过的全部 {files, number} 个文件中,留下的人至少掌握 {threshold} 的提交。",+ "noShareTitle": "{names} 在已索引代码中没有占比",+ "noShareDescription": "没有任何代码文件将他们列为前五位作者。",+ "resultSentence": "没有 {names} 时,{files, number} 个文件的剩余作者将只掌握不到 {threshold} 的提交:占代码的 {codeShare}。另有 {kept, number} 个文件包含他们的部分历史,但留下的人仍掌握至少 {threshold}。",+ "resultSentenceSevere": "没有 {names} 时,{files, number} 个文件的剩余作者将只掌握不到 {threshold} 的提交:占代码的 {codeShare},其中 {severe, number} 个是热点或健康度偏弱。另有 {kept, number} 个文件包含他们的部分历史,但留下的人仍掌握至少 {threshold}。",+ "statAtRisk": "有风险的文件",+ "statHotspots": "其中的热点",+ "statHotspotsHint": "处于仓库高变更区间的有风险文件",+ "statShare": "代码占比",+ "statShareHint": "有风险文件的代码行数,总计 {nloc, number} 行,分布于 {files, number} 个文件",+ "statDirectories": "目录",+ "heir": "{name} 可以接手:在 {of, number} 个文件中,有 {files, number} 个由其作为最主要的留任作者",+ "noHeir": "留下的人中没有这些文件的主要作者",+ "heirSevere": "其中 {count, number} 个是热点或健康度偏弱",+ "handoverTitle": "规划交接",+ "handoverDescription": "针对依赖 {names} 的 {files, number} 个文件的交接计划。",+ "offboardingListLabel": "将失去多数作者的目录",+ "underOnePercent": "不到 1%",+ "dependsTitle": "依赖于他们的代码",+ "dependsDescription": "此人完成了大部分提交的文件:留下的人将只掌握不到一半的历史;以及谁最适合接手各个目录。",+ "ownershipLink": "代码所有权",+ "filesCarryTitle": "他们承担的文件",+ "filesCarryHint": "共接触 {touched, number} 个,显示 {shown, number} 个",+ "filesCarryDescription": "归属于此人的提交最多的文件。变更度是相对仓库中所有文件的百分位。圆点标记他们独自维护且完成了至少 90% 提交的高变更文件:其中 {shown, number} 个里有 {sole, number} 个。",+ "filesCarryDescriptionNone": "归属于此人的提交最多的文件。变更度是相对仓库中所有文件的百分位。圆点标记他们独自维护且完成了至少 90% 提交的高变更文件,这些文件中没有符合条件的。",+ "commitMixTitle": "他们提交的内容",+ "commitMixDescription": "根据提交标题分类的 {total, number} 次提交,覆盖此人接触过的所有文件。",+ "commitMixEmptyTitle": "暂无已分类的提交",+ "commitMixEmptyDescription": "提交分类在建立索引时运行,下次同步后会显示在这里。",+ "commitMixBarLabel": "按类型划分的提交",+ "creditTitle": "他们改善的内容",+ "creditLink": "查看这些提交",+ "creditSentence": "在过去 {days} 天里,他们的提交让 {files, number} 个文件更健康,并解决了 {findings, number} 个问题。",+ "activityLabel": "活跃度",+ "activeLine": "活跃:过去 90 天内{floor, select, yes {至少} other {}} {commits, number} 次提交",+ "quietLine": "沉寂:过去 90 天内没有提交",+ "emailLabel": "邮箱",+ "aliasesLabel": "其他提交身份",+ "footprintTitle": "他们的工作范围",+ "footprintDescription": "他们作为主要所有者的文件,按顶层目录划分。占比是每个目录中由此人编写了大部分存活代码行的文件比例。",+ "footprintEmptyTitle": "暂无目录归属",+ "footprintEmptyDescription": "下次 git 同步后会显示按目录的所有权。",+ "footprintBarLabel": "按目录划分的拥有文件",+ "footprintDetail": "{files, number} 个文件 · {pct}% 归其所有",+ "relationshipsTitle": "还有谁在这里工作",+ "relationshipsDescription": "编辑相同文件的人。重叠度是此人的文件中对方也提交过的比例,体现他们的工作有多少是真正共享的。",+ "relationshipsEmptyTitle": "没有其他人改动过这些文件",+ "relationshipsEmptyDescription": "当第二个人向此人拥有的文件提交后,会显示共同作者。",+ "relationshipsAlone": "没有其他人与此人共享文件。",+ "relationshipsNext": "其余 {others, number} 人中,下一位的重叠度为 {pct}%,因此这里只有一位自然的评审人,而不是一份候选名单。",+ "relationshipsOthers": "另有 {others, number} 人至少共享一个文件。",+ "partnerLine": "{files, number} 个共享文件 · 此人 {pct}% 的工作与其重叠",+ "unknownName": "未知",+ "fileTableEmptyTitle": "暂无文件归属",+ "fileTableEmptyDescription": "下次 git 同步后会显示文件级所有权。",+ "colFile": "文件",+ "colCommits90d": "90 天提交",+ "colChurn": "变更度",+ "colChurnHint": "该文件变更频率相对仓库中所有文件的百分位排名",+ "colTheirCommits": "其提交占比",+ "colTheirCommitsHint": "该文件的提交中由此人完成的比例",+ "colTouched": "最近改动",+ "soleCarriedTitle": "此人独自维护的高变更文件",+ "fileMeta": "90 天内 {commits, number} 次提交 · 变更度 {churn} · 占其提交的 {ownPct} · 最近改动 {touched}",+ "colContributor": "贡献者",+ "colFilesOwned": "拥有文件",+ "colFilesOwnedHint": "由此人编写了大部分存活代码行的文件",+ "colHotspots": "热点",+ "colHotspotsHint": "同时也是高变更文件的拥有文件",+ "colSoleOwner": "独有",+ "colSoleOwnerHint": "没有其他人改动过的拥有文件",+ "colDeadLines": "死代码行",+ "colDeadLinesHint": "仍归属于此人的不可达代码行",+ "colLastTouched": "最近改动",+ "kindPerson": "人员",+ "kindBot": "机器人",+ "kindAgent": "编程智能体",+ "soleInactiveTitle": "由 90 天未活跃者独自拥有的文件",+ "atLeastTitle": "至少这么多:已索引的提交在 90 天窗口内中断"+ }},"costs": {"spendEmptyTitle": "尚无模型调用记录",diff --git a/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx b/packages/web/src/app/repos/[id]/owners/[owner]/page.tsxindex 2ba97c27e..e3998cf0b 100644--- a/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx+++ b/packages/web/src/app/repos/[id]/owners/[owner]/page.tsx@@ -10,6 +10,8 @@ import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import { formatDate, formatRelativeTimeOrNull } from "@repowise-dev/ui/lib/format";import { ApiClientError } from "@/lib/api/client";import { getOwnerProfile } from "@/lib/api/owners";+import { WhatDependsOnThem } from "@/components/owners/what-depends-on-them";+import { buildOwnershipLabels } from "@/components/owners/ownership-labels";export async function generateMetadata(): Promise<Metadata> {const t = await getTranslations("views.contributors");@@ -32,6 +34,7 @@ export default async function OwnerProfilePage({}) {const { id, owner } = await params;const t = await getTranslations("views.contributors");+ const labels = buildOwnershipLabels(await getTranslations("views.contributors.ui"), t);const base = `/repos/${id}`;const ownerKey = decodeURIComponent(owner);@@ -82,6 +85,8 @@ export default async function OwnerProfilePage({<OwnerProfileViewowner={profile}base={base}+ dependsOn={<WhatDependsOnThem repoId={id} ownerKey={profile.key} />}+ labels={labels}hrefForFile={(path) => fileEntityPath(base, path)}hrefForModule={(mod) => `${base}/modules/${encodeURIComponent(mod)}`}hrefForCoAuthor={(c) =>diff --git a/packages/web/src/app/repos/[id]/owners/page.tsx b/packages/web/src/app/repos/[id]/owners/page.tsxindex 6e6ac419a..d922b64f7 100644--- a/packages/web/src/app/repos/[id]/owners/page.tsx+++ b/packages/web/src/app/repos/[id]/owners/page.tsx@@ -1,114 +1,53 @@"use client";-import { useMemo, useState } from "react";-import Link from "next/link";-import { useParams, useRouter } from "next/navigation";+/**+ * Ownership — `/repos/[id]/owners` (the route keeps its original name).+ *+ * Knowledge and handover, as four tabs behind `?tab=`: the overview (truck+ * factor lede, two reads, the full table collapsed), knowledge risks,+ * knowledge loss, and the off-boarding what-if (`?leave=a,b&threshold=50`).+ */++import { useParams } from "next/navigation";import { useTranslations } from "next-intl";import useSWR from "swr";-import useSWRInfinite from "swr/infinite";import { Users } from "lucide-react";-import {- OwnerDirectory,- type OwnerDirectoryFilters,-} from "@repowise-dev/ui/owners/owner-directory";-import { ApiError } from "@repowise-dev/ui/shared/api-error";import { PageShell } from "@repowise-dev/ui/shared/page-shell";-import { useDebounce } from "@/lib/hooks/use-debounce";-import { listAllOwners, listOwnersPage } from "@/lib/api/owners";-import type { OwnerListEntry, Paginated } from "@/lib/api/types";+import { ViewTabs } from "@repowise-dev/ui/shared/view-tabs";+import { ContributorsPanel } from "@/components/owners/contributors-panels";+import { CONTRIBUTOR_TABS, useContributorsUrl } from "@/components/owners/use-contributors-url";+import { getOwnersSummary } from "@/lib/api/owners";-const LIMIT = 30;-/** When contributor count is at or below this, prefetch everyone for an- * accurate ownership distribution bar via fetchAllPaginated. */-const DISTRIBUTION_PREFETCH_CAP = 120;--export default function OwnersDirectoryPage() {+export default function ContributorsPage() {const t = useTranslations("views.contributors");- const tCommon = useTranslations("common");const { id } = useParams<{ id: string }>();- const router = useRouter();- const [filters, setFilters] = useState<OwnerDirectoryFilters>({- q: "",- sort: "files_owned",+ const { tab, scenario, setTab, setScenario } = useContributorsUrl();+ const summary = useSWR(`owners-summary:${id}`, () => getOwnersSummary(id), {+ revalidateOnFocus: false,});- const debouncedQ = useDebounce(filters.q, 250);-- const key = useMemo(- () => JSON.stringify({ q: debouncedQ, sort: filters.sort }),- [debouncedQ, filters.sort],- );-- const { data, error, mutate, size, setSize, isLoading, isValidating } = useSWRInfinite<- Paginated<OwnerListEntry>- >(- (pageIndex, previous) => {- if (previous && !previous.has_more) return null;- return `owners:${id}:${key}:${pageIndex}`;- },- (k) => {- const pageIndex = parseInt(k.split(":").pop()!, 10);- return listOwnersPage({- repoId: id,- q: debouncedQ || undefined,- sort: filters.sort,- limit: LIMIT,- offset: pageIndex * LIMIT,- });- },- { revalidateOnFocus: false, revalidateFirstPage: false },- );-- const items = useMemo(() => (data ? data.flatMap((p) => p.items) : []), [data]);- const total = data && data.length > 0 ? data[0].total : 0;- const hasMore = data ? data[data.length - 1].has_more : false;-- const shouldPrefetchDistribution =- debouncedQ === "" && total > 0 && total <= DISTRIBUTION_PREFETCH_CAP;- const { data: distributionOwners } = useSWR(- shouldPrefetchDistribution ? `owners-all:${id}:${filters.sort}` : null,- () =>- listAllOwners({- repoId: id,- sort: filters.sort,- maxItems: DISTRIBUTION_PREFETCH_CAP,- pageSize: DISTRIBUTION_PREFETCH_CAP,- }),- { revalidateOnFocus: false },- );+ const quiet = summary.data?.quiet_owners_total;return (- <PageShell- icon={<Users />}- title={t("title")}- description={t("description")}- >- <OwnerDirectory- owners={items}- distributionOwners={distributionOwners}- isLoading={isLoading}- isValidating={isValidating}- total={total}- hasMore={hasMore}- filters={filters}- onFiltersChange={setFilters}- onLoadMore={() => setSize(size + 1)}- base={`/repos/${id}`}- hrefFor={(o) => `/repos/${id}/owners/${encodeURIComponent(o.key)}`}- LinkComponent={Link}- error={- error ? (- <ApiError- title={t("loadFailedTitle")}- message={t("loadFailed")}- retryLabel={tCommon("retry")}- onRetry={() => void mutate()}- />- ) : undefined- }- onSelect={(o) =>- router.push(`/repos/${id}/owners/${encodeURIComponent(o.key)}`)- }- />+ <PageShell icon={<Users />} title={t("title")} description={t("description")}>+ <ViewTabs+ aria-label={t("tabsLabel")}+ tabs={CONTRIBUTOR_TABS.map((tabId) => ({+ id: tabId,+ label: t(`tabs.${tabId}`),+ // Cheap and meaningful before the click: the summary already counts it.+ ...(tabId === "loss" && quiet !== undefined ? { badge: quiet } : {}),+ }))}+ value={tab}+ onValueChange={setTab}+ >+ <ContributorsPanel+ tab={tab}+ repoId={id}+ summary={summary}+ scenario={scenario}+ onScenarioChange={setScenario}+ />+ </ViewTabs></PageShell>);}diff --git a/packages/web/src/components/layout/nav-items.test.ts b/packages/web/src/components/layout/nav-items.test.tsindex d10eb8a7e..6693217cc 100644--- a/packages/web/src/components/layout/nav-items.test.ts+++ b/packages/web/src/components/layout/nav-items.test.ts@@ -11,7 +11,7 @@ describe("repoNavGroups", () => {["start", ["Overview", "Chat"]],["understand", ["Docs", "Architecture", "Knowledge Graph", "Files"]],["quality", ["Code Health", "Refactoring", "Tests", "Security"]],- ["people", ["Contributors", "Commits", "Decisions"]],+ ["people", ["Ownership", "Commits", "Decisions"]],["settings", ["Stats", "Usage & savings", "Settings"]],]);});diff --git a/packages/web/src/components/layout/nav-items.ts b/packages/web/src/components/layout/nav-items.tsindex 1ae02308a..b2cacace6 100644--- a/packages/web/src/components/layout/nav-items.ts+++ b/packages/web/src/components/layout/nav-items.ts@@ -110,7 +110,7 @@ export function repoNavGroups(repoId: string): NavGroup[] {label: "People & History",labelKey: "groupPeopleAndHistory",items: [- { label: "Contributors", labelKey: "contributors", href: `${base}/owners`, icon: Users },+ { label: "Ownership", labelKey: "contributors", href: `${base}/owners`, icon: Users },{ label: "Commits", labelKey: "commits", href: `${base}/commits`, icon: GitCommitHorizontal },{ label: "Decisions", labelKey: "decisions", href: `${base}/decisions`, icon: Lightbulb },],diff --git a/packages/web/src/components/layout/repo-breadcrumb-label.ts b/packages/web/src/components/layout/repo-breadcrumb-label.tsindex 0b013995a..0927b6a18 100644--- a/packages/web/src/components/layout/repo-breadcrumb-label.ts+++ b/packages/web/src/components/layout/repo-breadcrumb-label.ts@@ -19,7 +19,7 @@ const SEGMENT_LABELS: Record<string, string> = {decisions: "Decisions",commits: "Commits",changes: "Changes",- owners: "Contributors",+ owners: "Ownership",modules: "Modules",wiki: "Wiki",health: "Code Health",diff --git a/packages/web/src/components/owners/all-contributors.tsx b/packages/web/src/components/owners/all-contributors.tsxnew file mode 100644index 000000000..e745dbfde--- /dev/null+++ b/packages/web/src/components/owners/all-contributors.tsx@@ -0,0 +1,128 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import { useTranslations } from "next-intl";+import useSWRInfinite from "swr/infinite";+import {+ OwnerDirectory,+ type OwnerDirectoryFilters,+} from "@repowise-dev/ui/owners/owner-directory";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { useDebounce } from "@/lib/hooks/use-debounce";+import { listOwnersPage } from "@/lib/api/owners";+import type { OwnerListEntry, Paginated } from "@/lib/api/types";+import { useOwnershipLabels } from "./ownership-labels";+import {+ directoryFiltersFromParams,+ directoryFiltersKey,+ externalDirectoryFilters,+ writeDirectoryFilters,+} from "./use-contributors-url";++/** Rows shown before "Show all", then the page size the rest loads in. */+const FIRST_PAGE = 10;+const REST_PAGE = 50;++const pageRange = (pageIndex: number) =>+ pageIndex === 0+ ? { offset: 0, limit: FIRST_PAGE }+ : { offset: FIRST_PAGE + (pageIndex - 1) * REST_PAGE, limit: REST_PAGE };++/** The Overview's "Everyone" table: people only unless the reader asks for automation. */+export function AllContributors({ repoId, automationCount }: { repoId: string; automationCount: number }) {+ const t = useTranslations("views.contributors");+ const tCommon = useTranslations("common");+ const router = useRouter();+ const searchParams = useSearchParams();+ const labels = useOwnershipLabels();+ const [filters, setFilters] = useState<OwnerDirectoryFilters>(() =>+ directoryFiltersFromParams(searchParams),+ );+ const debouncedQ = useDebounce(filters.q, 250);+ // The table's search, sort and toggle live in the URL, so a filtered view is a+ // link. The URL seeds the state; the table writes it on every debounced+ // change, and the first write only normalises a hand-edited query.+ // Writes not yet seen back, oldest first: a slow replace can land after the+ // next debounced write, and its echo must not revert the search box.+ const written = useRef<string[]>([]);+ useEffect(() => {+ const shown = { ...filters, q: debouncedQ };+ const next = writeDirectoryFilters(searchParams, shown);+ if (next === searchParams.toString()) return;+ written.current.push(directoryFiltersKey(shown));+ router.replace(next ? `?${next}` : "?", { scroll: false });+ // Only the debounced filters drive a write; reading searchParams must not loop.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [debouncedQ, filters.sort, filters.includeAutomation]);+ // A URL the table did not write (a link followed while it stays mounted) wins.+ useEffect(() => {+ const adopt = externalDirectoryFilters(searchParams, written.current, { ...filters, q: debouncedQ });+ if (adopt) {+ written.current = [];+ setFilters(adopt);+ return;+ }+ const echo = written.current.indexOf(directoryFiltersKey(directoryFiltersFromParams(searchParams)));+ if (echo >= 0) written.current.splice(0, echo + 1);+ // Only a URL change is read here; the write above follows the filters.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [searchParams]);+ const key = useMemo(+ () => JSON.stringify({ q: debouncedQ, sort: filters.sort, all: filters.includeAutomation }),+ [debouncedQ, filters.sort, filters.includeAutomation],+ );++ const { data, error, mutate, size, setSize, isLoading, isValidating } = useSWRInfinite<+ Paginated<OwnerListEntry>+ >(+ (pageIndex, previous) => {+ if (previous && !previous.has_more) return null;+ return `owners:${repoId}:${key}:${pageIndex}`;+ },+ (k) => {+ const pageIndex = parseInt(k.split(":").pop()!, 10);+ return listOwnersPage({+ repoId,+ q: debouncedQ || undefined,+ sort: filters.sort,+ ...(filters.includeAutomation ? {} : { kind: "human" as const }),+ ...pageRange(pageIndex),+ });+ },+ { revalidateOnFocus: false, revalidateFirstPage: false },+ );++ const items = useMemo(() => (data ? data.flatMap((p) => p.items) : []), [data]);+ const total = data?.[0]?.total ?? 0;+ const hrefFor = (o: OwnerListEntry) => `/repos/${repoId}/owners/${encodeURIComponent(o.key)}`;++ return (+ <OwnerDirectory+ owners={items}+ isLoading={isLoading}+ isValidating={isValidating}+ total={total}+ hasMore={data ? data[data.length - 1]!.has_more : false}+ filters={filters}+ onFiltersChange={setFilters}+ onShowAll={() => void setSize(Math.max(size, 1 + Math.ceil(Math.max(0, total - FIRST_PAGE) / REST_PAGE)))}+ automationCount={automationCount}+ hrefFor={hrefFor}+ LinkComponent={Link}+ labels={labels}+ error={+ error ? (+ <ApiError+ title={t("loadFailedTitle")}+ message={t("loadFailed")}+ retryLabel={tCommon("retry")}+ onRetry={() => void mutate()}+ />+ ) : undefined+ }+ onSelect={(o) => router.push(hrefFor(o))}+ />+ );+}diff --git a/packages/web/src/components/owners/contributors-panels.tsx b/packages/web/src/components/owners/contributors-panels.tsxnew file mode 100644index 000000000..7112746b1--- /dev/null+++ b/packages/web/src/components/owners/contributors-panels.tsx@@ -0,0 +1,119 @@+"use client";++import { useMemo, type ReactNode } from "react";+import dynamic from "next/dynamic";+import Link from "next/link";+import { useTranslations } from "next-intl";+import type { SWRResponse } from "swr";+import type { KnowledgeMatrix, OwnersSummary } from "@repowise-dev/types/owners";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+import { OwnershipLede } from "@repowise-dev/ui/owners/ownership-lede";+import { knowledgeCoverage } from "@repowise-dev/ui/owners/knowledge-coverage";+import type { OffboardingScenario } from "@repowise-dev/ui/owners/offboarding-view";+import { AllContributors } from "./all-contributors";+import { useOwnershipLabels } from "./ownership-labels";+import { useKnowledgeMatrix } from "./use-knowledge-matrix";+import { contributorsHref, type ContributorTab } from "./use-contributors-url";++const TabFallback = () => <Skeleton className="h-[50vh] w-full rounded-lg" />;+const KnowledgeRisksView = dynamic(+ () => import("@repowise-dev/ui/owners/knowledge-risks-view").then((m) => m.KnowledgeRisksView),+ { ssr: false, loading: TabFallback },+);+const KnowledgeLossView = dynamic(+ () => import("@repowise-dev/ui/owners/knowledge-loss-view").then((m) => m.KnowledgeLossView),+ { ssr: false, loading: TabFallback },+);+const OffboardingView = dynamic(+ () => import("@repowise-dev/ui/owners/offboarding-view").then((m) => m.OffboardingView),+ { ssr: false, loading: TabFallback },+);++interface PanelProps {+ tab: ContributorTab;+ repoId: string;+ summary: SWRResponse<OwnersSummary>;+ scenario: OffboardingScenario;+ onScenarioChange: (next: OffboardingScenario) => void;+}++/**+ * The active Ownership tab. Every tab reads the summary and the knowledge+ * matrix (one fetch each, shared with the person page); the three matrix+ * views are split out of the landing chunk.+ */+export function ContributorsPanel({ tab, repoId, summary, scenario, onScenarioChange }: PanelProps) {+ const t = useTranslations("views.contributors");+ const tCommon = useTranslations("common");+ const base = `/repos/${repoId}`;+ const matrix = useKnowledgeMatrix(repoId);+ const s = summary.data;+ const labels = useOwnershipLabels();+ const coverage = useMemo(() => (matrix.data ? knowledgeCoverage(matrix.data) : null), [matrix.data]);++ const loadError = (onRetry: () => void, message: string) => (+ <ApiError title={t("loadFailedTitle")} message={message} retryLabel={tCommon("retry")} onRetry={onRetry} />+ );+ const ready = (render: (m: KnowledgeMatrix, s: OwnersSummary) => ReactNode, fallback = <TabFallback />) => {+ if (summary.error) return loadError(() => void summary.mutate(), t("loadFailed"));+ if (matrix.error) return loadError(() => void matrix.mutate(), t("matrixLoadFailed"));+ return matrix.data && s ? render(matrix.data, s) : fallback;+ };++ // The people behind the truck factor, as the one-click starting scenario.+ const suggestions = useMemo(() => {+ if (!s?.truck_factor || s.truck_factor > s.concentration.owners.length) return [];+ const owners = s.concentration.owners.slice(0, s.truck_factor);+ const names = owners.map((o) => o.name).join(", ");+ return [{ label: t("offboardingSuggestion", { names }), keys: owners.map((o) => o.key) }];+ }, [s, t]);++ const panels: Record<ContributorTab, () => ReactNode> = {+ overview: () => (+ <>+ {ready(+ (_, sum) =>+ coverage && (+ <OwnershipLede+ coverage={coverage}+ summary={sum}+ hrefForTab={(next, leave) => contributorsHref(base, next, leave)}+ LinkComponent={Link}+ labels={labels}+ />+ ),+ <Skeleton className="h-40 w-full rounded-lg" />,+ )}+ <AllContributors repoId={repoId} automationCount={s?.automation_identities ?? 0} />+ </>+ ),+ risks: () => ready((m) => <KnowledgeRisksView matrix={m} base={base} LinkComponent={Link} labels={labels} />),+ loss: () =>+ ready((m, sum) => (+ <KnowledgeLossView+ matrix={m}+ summary={sum}+ base={base}+ hrefForPerson={(key) => `${base}/owners/${encodeURIComponent(key)}`}+ hrefForScenario={(key) => contributorsHref(base, "offboarding", [key])}+ LinkComponent={Link}+ labels={labels}+ />+ )),+ offboarding: () =>+ ready((m) => (+ <OffboardingView+ matrix={m}+ scenario={scenario}+ onScenarioChange={onScenarioChange}+ suggestions={suggestions}+ base={base}+ LinkComponent={Link}+ labels={labels}+ />+ )),+ };++ return <div className="flex flex-col gap-6 pt-4 sm:gap-8">{panels[tab]()}</div>;+}diff --git a/packages/web/src/components/owners/ownership-labels.test.tsx b/packages/web/src/components/owners/ownership-labels.test.tsxnew file mode 100644index 000000000..987b7242d--- /dev/null+++ b/packages/web/src/components/owners/ownership-labels.test.tsx@@ -0,0 +1,57 @@+// @vitest-environment jsdom++import { renderHook } from "@testing-library/react";+import { NextIntlClientProvider } from "next-intl";+import type { ReactNode } from "react";+import { describe, expect, it } from "vitest";+import type { OwnershipLabels } from "@repowise-dev/ui/owners/labels";+import { DEFAULT_OWNERSHIP_LABELS } from "@repowise-dev/ui/owners/labels";+import enMessages from "../../../messages/en.json";+import zhMessages from "../../../messages/zh-CN.json";+import { useOwnershipLabels } from "./ownership-labels";++/** Every label rendered with sample arguments: strings as they are, functions called. */+function renderAll(labels: OwnershipLabels): Record<string, string> {+ const sample: Record<string, unknown[]> = {+ resultSentence: [{ names: "Ana", files: 3, threshold: "50%", codeShare: "9%", severe: 1, kept: 2 }],+ };+ return Object.fromEntries(+ Object.entries(labels).map(([key, value]) => {+ if (typeof value === "string") return [key, value];+ const args = sample[key] ?? Array.from({ length: value.length }, (_, i) => (i === 0 ? 2 : i % 2 ? 3 : "Ana"));+ return [key, String((value as (...a: unknown[]) => unknown)(...args))];+ }),+ );+}++function labelsFor(locale: string, messages: Record<string, unknown>): OwnershipLabels {+ const wrapper = ({ children }: { children: ReactNode }) => (+ <NextIntlClientProvider locale={locale} messages={messages}>+ {children}+ </NextIntlClientProvider>+ );+ return renderHook(() => useOwnershipLabels(), { wrapper }).result.current;+}++describe("useOwnershipLabels", () => {+ it("fills every label the ui defines", () => {+ const labels = labelsFor("en", enMessages);+ expect(Object.keys(labels).sort()).toEqual(Object.keys(DEFAULT_OWNERSHIP_LABELS).sort());+ });++ it("formats every English message without leftover placeholders", () => {+ for (const [key, text] of Object.entries(renderAll(labelsFor("en", enMessages)))) {+ expect(text, key).not.toMatch(/[{}]|views\.contributors/);+ }+ });++ it("formats every zh-CN message in Chinese", () => {+ const zh = renderAll(labelsFor("zh-CN", zhMessages));+ for (const [key, text] of Object.entries(zh)) {+ expect(text, key).not.toMatch(/[{}]|views\.contributors/);+ }+ expect(zh.everyone).toBe("所有人");+ expect(zh.coverageLabel).toBe("知识覆盖率");+ expect(zh.showAllPeople).not.toMatch(/Show all/);+ });+});diff --git a/packages/web/src/components/owners/ownership-labels.ts b/packages/web/src/components/owners/ownership-labels.tsnew file mode 100644index 000000000..cf69d1618--- /dev/null+++ b/packages/web/src/components/owners/ownership-labels.ts@@ -0,0 +1,188 @@+import { useMemo } from "react";+import { useTranslations, type TranslationValues } from "next-intl";+import type { OwnershipLabels } from "@repowise-dev/ui/owners/labels";++// No "use client": the person page builds these on the server with+// getTranslations, the client views through useOwnershipLabels.++/** A translator scoped to a namespace, from useTranslations or getTranslations. */+export type OwnershipTranslator = (key: string, values?: TranslationValues) => string;++const basis = (byLines: boolean) => (byLines ? "lines" : "files");+const yes = (flag: boolean) => (flag ? "yes" : "no");++/**+ * The Ownership views' copy from the catalog. `t` is scoped to+ * `views.contributors.ui`, `tPage` to `views.contributors`.+ */+export function buildOwnershipLabels(t: OwnershipTranslator, tPage: OwnershipTranslator): OwnershipLabels {+ return {+ agentPrompt: t("agentPrompt"),+ promptForGroup: (count) => t("promptForGroup", { count }),+ repositoryRoot: t("repositoryRoot"),+ hotspot: t("hotspot"),+ files: (count) => t("files", { count }),+ showAllFiles: (count) => t("showAllFiles", { count }),+ showAllDirectories: (count) => t("showAllDirectories", { count }),+ noOtherAuthor: t("noOtherAuthor"),+ openInOffboarding: tPage("openInOffboarding"),++ coverageLabel: t("coverageLabel"),+ coverageHint: (byLines, days) => t("coverageHint", { basis: basis(byLines), days }),+ coverageUnit: (byLines) => t("coverageUnit", { basis: basis(byLines) }),+ wellShared: t("wellShared"),+ coverageSentence: (pct, byLines, days) => t("coverageSentence", { pct, basis: basis(byLines), days }),+ singleHolderSentence: (single, files) => t("singleHolderSentence", { single, files }),+ noChanges: (days) => t("noChanges", { days }),+ spreadTitle: t("spreadTitle"),+ spreadDescription: (count) => t("spreadDescription", { count }),+ readHotspots: t("readHotspots"),+ readHotspotsUnit: (count) => t("readHotspotsUnit", { count }),+ readHotspotsWhy: t("readHotspotsWhy"),+ readQuiet: t("readQuiet"),+ readQuietUnit: (count) => t("readQuietUnit", { count }),+ readQuietWhy: (days) => t("readQuietWhy", { days }),+ readTruck: t("readTruck"),+ readTruckWhy: t("readTruckWhy"),++ everyone: t("everyone"),+ everyoneDescription: t("everyoneDescription"),+ people: (count, all) => t("people", { count, all: yes(all) }),+ searchPlaceholder: t("searchPlaceholder"),+ searchLabel: t("searchLabel"),+ showAutomation: (count) => t("showAutomation", { count }),+ noMatch: t("noMatch"),+ clearSearch: t("clearSearch"),+ noPeople: t("noPeople"),+ noPeopleDescription: t("noPeopleDescription"),+ showAllPeople: (count, all) => t("showAllPeople", { count, all: yes(all) }),+ loading: t("loading"),++ risksIntro: (files, hotspots, lowHealth, dirs) => t("risksIntro", { files, hotspots, lowHealth, dirs }),+ risksCleanTitle: (count) => t("risksCleanTitle", { count }),+ risksCleanDescription: t("risksCleanDescription"),+ risksOneHolder: (name) => t("risksOneHolder", { name }),+ risksManyHolders: (holders, name, files) =>+ name ? t("risksManyHoldersTop", { holders, name, files }) : t("risksManyHolders", { holders }),+ risksSevere: (count) => t("risksSevere", { count }),+ risksListLabel: t("risksListLabel"),++ lossIntro: (total, days, shown) =>+ total > shown ? `${t("lossIntro", { total, days })} ${t("lossShowing", { shown })}` : t("lossIntro", { total, days }),+ lossCleanTitle: (days) => t("lossCleanTitle", { days }),+ lossCleanDescription: (people, files) => t("lossCleanDescription", { people, files }),+ lossCarriedTitle: t("lossCarriedTitle"),+ lossCarriedDescription: (days, quiet) => t("lossCarriedDescription", { days, quiet }),+ lossLastCommit: (when) => t("lossLastCommit", { when }),+ lossChanging: (changing, owned) =>+ owned === 1 ? t("lossChangingOne") : t("lossChanging", { changing, owned }),+ lossAtRisk: (files, severe) =>+ severe > 0 ? t("lossAtRiskSevere", { files, severe }) : t("lossAtRisk", { files }),+ lossNoneAtRisk: t("lossNoneAtRisk"),+ lossDirectories: (open, count) => t("lossDirectories", { open: yes(open), count }),+ lossListLabel: t("lossListLabel"),++ leavingLabel: t("leavingLabel"),+ leavingPicker: t("leavingPicker"),+ thresholdLabel: (pct) => t("thresholdLabel", { pct }),+ thresholdHelp: t("thresholdHelp"),+ tryLabel: t("tryLabel"),+ pickPrompt: t("pickPrompt"),+ pickerPlaceholder: t("pickerPlaceholder"),+ removePerson: (name) => t("removePerson", { name }),+ selectedPeople: t("selectedPeople"),+ unknownPeople: t("unknownPeople"),+ nothingDependsTitle: (names) => t("nothingDependsTitle", { names }),+ nothingDependsDescription: (threshold, files, names) =>+ t("nothingDependsDescription", { threshold, files, names }),+ noShareTitle: (names, count) => t("noShareTitle", { names, count }),+ noShareDescription: t("noShareDescription"),+ resultSentence: ({ names, files, threshold, codeShare, severe, kept }) =>+ severe > 0+ ? t("resultSentenceSevere", { names, files, threshold, codeShare, severe, kept })+ : t("resultSentence", { names, files, threshold, codeShare, kept }),+ statAtRisk: t("statAtRisk"),+ statHotspots: t("statHotspots"),+ statHotspotsHint: t("statHotspotsHint"),+ statShare: t("statShare"),+ statShareHint: (nloc, files) => t("statShareHint", { nloc, files }),+ statDirectories: t("statDirectories"),+ heir: (name, files, of) => t("heir", { name, files, of }),+ noHeir: t("noHeir"),+ heirSevere: (count) => t("heirSevere", { count }),+ handoverTitle: t("handoverTitle"),+ handoverDescription: (files, names) => t("handoverDescription", { files, names }),+ offboardingListLabel: t("offboardingListLabel"),+ underOnePercent: t("underOnePercent"),++ dependsTitle: t("dependsTitle"),+ dependsDescription: t("dependsDescription"),+ ownershipLink: t("ownershipLink"),+ filesCarryTitle: t("filesCarryTitle"),+ filesCarryHint: (shown, touched) => t("filesCarryHint", { shown, touched }),+ filesCarryDescription: (sole, shown) =>+ sole > 0 ? t("filesCarryDescription", { sole, shown }) : t("filesCarryDescriptionNone"),+ commitMixTitle: t("commitMixTitle"),+ commitMixDescription: (total) => t("commitMixDescription", { total }),+ commitMixEmptyTitle: t("commitMixEmptyTitle"),+ commitMixEmptyDescription: t("commitMixEmptyDescription"),+ commitMixBarLabel: t("commitMixBarLabel"),+ creditTitle: t("creditTitle"),+ creditLink: t("creditLink"),+ creditSentence: (days, files, findings) => t("creditSentence", { days, files, findings }),+ activityLabel: t("activityLabel"),+ activeLine: (commits, floor) => t("activeLine", { commits, floor: yes(floor) }),+ quietLine: t("quietLine"),+ emailLabel: t("emailLabel"),+ aliasesLabel: t("aliasesLabel"),+ footprintTitle: t("footprintTitle"),+ footprintDescription: t("footprintDescription"),+ footprintEmptyTitle: t("footprintEmptyTitle"),+ footprintEmptyDescription: t("footprintEmptyDescription"),+ footprintBarLabel: t("footprintBarLabel"),+ footprintDetail: (files, pct) => t("footprintDetail", { files, pct }),+ relationshipsTitle: t("relationshipsTitle"),+ relationshipsDescription: t("relationshipsDescription"),+ relationshipsEmptyTitle: t("relationshipsEmptyTitle"),+ relationshipsEmptyDescription: t("relationshipsEmptyDescription"),+ relationshipsAlone: t("relationshipsAlone"),+ relationshipsNext: (others, pct) => t("relationshipsNext", { others, pct }),+ relationshipsOthers: (others) => t("relationshipsOthers", { others }),+ partnerLine: (files, pct) => t("partnerLine", { files, pct }),+ unknownName: t("unknownName"),+ fileTableEmptyTitle: t("fileTableEmptyTitle"),+ fileTableEmptyDescription: t("fileTableEmptyDescription"),+ colFile: t("colFile"),+ colCommits90d: t("colCommits90d"),+ colChurn: t("colChurn"),+ colChurnHint: t("colChurnHint"),+ colTheirCommits: t("colTheirCommits"),+ colTheirCommitsHint: t("colTheirCommitsHint"),+ colTouched: t("colTouched"),+ soleCarriedTitle: t("soleCarriedTitle"),+ fileMeta: (commits, churn, ownPct, touched) => t("fileMeta", { commits, churn, ownPct, touched }),++ colContributor: t("colContributor"),+ colFilesOwned: t("colFilesOwned"),+ colFilesOwnedHint: t("colFilesOwnedHint"),+ colHotspots: t("colHotspots"),+ colHotspotsHint: t("colHotspotsHint"),+ colSoleOwner: t("colSoleOwner"),+ colSoleOwnerHint: t("colSoleOwnerHint"),+ colDeadLines: t("colDeadLines"),+ colDeadLinesHint: t("colDeadLinesHint"),+ colLastTouched: t("colLastTouched"),+ kindPerson: t("kindPerson"),+ kindBot: t("kindBot"),+ kindAgent: t("kindAgent"),+ soleInactiveTitle: t("soleInactiveTitle"),+ atLeastTitle: t("atLeastTitle"),+ };+}++/** The same copy in a client component, memoised on the translators. */+export function useOwnershipLabels(): OwnershipLabels {+ const t = useTranslations("views.contributors.ui");+ const tPage = useTranslations("views.contributors");+ return useMemo(() => buildOwnershipLabels(t, tPage), [t, tPage]);+}diff --git a/packages/web/src/components/owners/use-contributors-url.test.ts b/packages/web/src/components/owners/use-contributors-url.test.tsnew file mode 100644index 000000000..a03e4e7da--- /dev/null+++ b/packages/web/src/components/owners/use-contributors-url.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";++import { directoryFiltersKey, externalDirectoryFilters } from "./use-contributors-url";++const shown = { q: "ada", sort: "files_owned" as const, includeAutomation: false };++describe("externalDirectoryFilters", () => {+ it("ignores the table's own write and a URL that already says what it shows", () => {+ const own = directoryFiltersKey(shown);+ expect(externalDirectoryFilters(new URLSearchParams(`tab=overview&${own}`), [own], shown)).toBeNull();+ expect(externalDirectoryFilters(new URLSearchParams("q=ada"), [], shown)).toBeNull();+ // A late echo of an earlier write, while a newer one is pending.+ expect(externalDirectoryFilters(new URLSearchParams("q=a"), ["q=a", own], shown)).toBeNull();+ });++ it("adopts a URL the table did not write", () => {+ const own = directoryFiltersKey(shown);+ expect(externalDirectoryFilters(new URLSearchParams(""), [own], shown)).toEqual({+ q: "",+ sort: "files_owned",+ includeAutomation: false,+ });+ expect(externalDirectoryFilters(new URLSearchParams("automation=1"), [own], shown)).toMatchObject({+ includeAutomation: true,+ });+ });+});diff --git a/packages/web/src/components/owners/use-contributors-url.ts b/packages/web/src/components/owners/use-contributors-url.tsnew file mode 100644index 000000000..c380c8608--- /dev/null+++ b/packages/web/src/components/owners/use-contributors-url.ts@@ -0,0 +1,134 @@+"use client";++import { useCallback, useMemo } from "react";+import { useRouter, useSearchParams } from "next/navigation";+import {+ formatLeaveParam,+ formatThresholdParam,+ parseLeaveParam,+ parseThresholdParam,+} from "@repowise-dev/ui/owners/offboarding";+import type { OffboardingScenario } from "@repowise-dev/ui/owners/offboarding-view";+import type { OwnerDirectoryFilters, OwnerSortKey } from "@repowise-dev/ui/owners/owner-directory";++const SORT_KEYS: readonly OwnerSortKey[] = [+ "files_owned",+ "hotspots_owned",+ "commit_count_90d",+ "dead_code_lines_owned",+ "bus_factor_risk_files",+];+const DEFAULT_SORT: OwnerSortKey = "files_owned";++/** The Everyone table's filters from `?q=&sort=&automation=1`. */+export function directoryFiltersFromParams(sp: URLSearchParams): OwnerDirectoryFilters {+ const sort = sp.get("sort") as OwnerSortKey | null;+ return {+ q: sp.get("q") ?? "",+ sort: sort && SORT_KEYS.includes(sort) ? sort : DEFAULT_SORT,+ includeAutomation: sp.get("automation") === "1",+ };+}++/** `sp` with the table's filters written in, defaults left out; returns the query string. */+export function writeDirectoryFilters(sp: URLSearchParams, f: OwnerDirectoryFilters): string {+ const next = new URLSearchParams(sp.toString());+ const set = (key: string, value: string | null) => (value ? next.set(key, value) : next.delete(key));+ set("q", f.q.trim() || null);+ set("sort", f.sort === DEFAULT_SORT ? null : f.sort);+ set("automation", f.includeAutomation ? "1" : null);+ return next.toString();+}++/** The table's filters as their query string alone; equal strings mean the same view. */+export function directoryFiltersKey(f: OwnerDirectoryFilters): string {+ return writeDirectoryFilters(new URLSearchParams(), f);+}++/**+ * Filters to adopt from a URL the table did not write itself (a link followed+ * while it stays mounted), or null when the URL is an echo of one of its+ * pending writes (*written*, oldest first) or already says what it shows.+ */+export function externalDirectoryFilters(+ sp: URLSearchParams,+ written: readonly string[],+ shown: OwnerDirectoryFilters,+): OwnerDirectoryFilters | null {+ const incoming = directoryFiltersFromParams(sp);+ const key = directoryFiltersKey(incoming);+ return written.includes(key) || key === directoryFiltersKey(shown) ? null : incoming;+}++export const CONTRIBUTOR_TABS = ["overview", "risks", "loss", "offboarding"] as const;+export type ContributorTab = (typeof CONTRIBUTOR_TABS)[number];++/** Params that belong to one tab and must not ride along to another. */+const SCENARIO_PARAMS = ["leave", "threshold"];+const DIRECTORY_PARAMS = ["q", "sort", "automation"];+const DEFAULT_THRESHOLD_PARAM = formatThresholdParam(parseThresholdParam(null));++function parseTab(raw: string | null): ContributorTab {+ return (CONTRIBUTOR_TABS as readonly string[]).includes(raw ?? "") ? (raw as ContributorTab) : "overview";+}++/** An Ownership page URL: a tab and, for off-boarding, who is leaving. */+export function contributorsHref(base: string, tab: ContributorTab, leave?: string[]): string {+ const sp = new URLSearchParams();+ if (tab !== "overview") sp.set("tab", tab);+ if (leave?.length) sp.set("leave", formatLeaveParam(leave));+ const qs = sp.toString();+ return qs ? `${base}/owners?${qs}` : `${base}/owners`;+}++/**+ * The Ownership page's URL state: `?tab=` and the off-boarding scenario+ * (`?leave=a,b&threshold=50`). The scenario is parsed off the raw strings so+ * its array keeps one identity between renders and the simulation memo holds.+ */+export function useContributorsUrl() {+ const router = useRouter();+ const searchParams = useSearchParams();+ const tab = parseTab(searchParams.get("tab"));+ const rawLeave = searchParams.get("leave");+ const rawThreshold = searchParams.get("threshold");+ const scenario = useMemo<OffboardingScenario>(+ () => ({ leaving: parseLeaveParam(rawLeave), threshold: parseThresholdParam(rawThreshold) }),+ [rawLeave, rawThreshold],+ );++ const replaceParams = useCallback(+ (edit: (sp: URLSearchParams) => void) => {+ const sp = new URLSearchParams(searchParams.toString());+ edit(sp);+ const qs = sp.toString();+ router.replace(qs ? `?${qs}` : "?", { scroll: false });+ },+ [router, searchParams],+ );++ const setTab = useCallback(+ (next: string) =>+ replaceParams((sp) => {+ if (next === "overview") sp.delete("tab");+ else sp.set("tab", next);+ if (next !== "offboarding") for (const p of SCENARIO_PARAMS) sp.delete(p);+ if (next !== "overview") for (const p of DIRECTORY_PARAMS) sp.delete(p);+ }),+ [replaceParams],+ );++ const setScenario = useCallback(+ (next: OffboardingScenario) =>+ replaceParams((sp) => {+ if (next.leaving.length) sp.set("leave", formatLeaveParam(next.leaving));+ else sp.delete("leave");+ const threshold = formatThresholdParam(next.threshold);+ if (threshold === DEFAULT_THRESHOLD_PARAM) sp.delete("threshold");+ else sp.set("threshold", threshold);+ }),+ [replaceParams],+ );++ return { tab, scenario, setTab, setScenario };+}diff --git a/packages/web/src/components/owners/use-knowledge-matrix.ts b/packages/web/src/components/owners/use-knowledge-matrix.tsnew file mode 100644index 000000000..44764a4b6--- /dev/null+++ b/packages/web/src/components/owners/use-knowledge-matrix.ts@@ -0,0 +1,11 @@+"use client";++import useSWR from "swr";+import { getKnowledgeMatrix } from "@/lib/api/owners";++/** The one key every surface reads the knowledge matrix under, so it is fetched once. */+export function useKnowledgeMatrix(repoId: string, enabled = true) {+ return useSWR(enabled ? `knowledge-matrix:${repoId}` : null, () => getKnowledgeMatrix(repoId), {+ revalidateOnFocus: false,+ });+}diff --git a/packages/web/src/components/owners/what-depends-on-them.tsx b/packages/web/src/components/owners/what-depends-on-them.tsxnew file mode 100644index 000000000..9ae063976--- /dev/null+++ b/packages/web/src/components/owners/what-depends-on-them.tsx@@ -0,0 +1,62 @@+"use client";++import { useMemo } from "react";+import Link from "next/link";+import { useTranslations } from "next-intl";+import { simulateOffboarding } from "@repowise-dev/ui/owners/offboarding";+import { OffboardingResultView } from "@repowise-dev/ui/owners/offboarding-result";+import { ApiError } from "@repowise-dev/ui/shared/api-error";+import { Skeleton } from "@repowise-dev/ui/ui/skeleton";+import { useKnowledgeMatrix } from "./use-knowledge-matrix";+import { useOwnershipLabels } from "./ownership-labels";+import { contributorsHref } from "./use-contributors-url";++/**+ * "What depends on them" on a person page: the single-person off-boarding.+ *+ * Computed in the browser from the knowledge matrix rather than on the server.+ * For the person behind the truck factor the result covers thousands of files,+ * megabytes once serialised into the page, while the matrix is one gzipped+ * fetch under 100 KB that the Ownership tabs share under the same key.+ */+export function WhatDependsOnThem({ repoId, ownerKey }: { repoId: string; ownerKey: string }) {+ const t = useTranslations("views.contributors");+ const tCommon = useTranslations("common");+ const base = `/repos/${repoId}`;+ const matrix = useKnowledgeMatrix(repoId);+ const labels = useOwnershipLabels();+ const result = useMemo(+ () => (matrix.data ? simulateOffboarding(matrix.data, [ownerKey]) : null),+ [matrix.data, ownerKey],+ );++ if (matrix.error) {+ return (+ <ApiError+ title={t("loadFailedTitle")}+ message={t("matrixLoadFailed")}+ retryLabel={tCommon("retry")}+ onRetry={() => void matrix.mutate()}+ />+ );+ }+ if (!result) return <Skeleton className="h-48 w-full rounded-lg" />;++ return (+ <OffboardingResultView+ result={result}+ base={base}+ LinkComponent={Link}+ initialAreas={5}+ labels={labels}+ secondaryAction={+ <Link+ href={contributorsHref(base, "offboarding", [ownerKey])}+ className="text-xs text-[var(--color-accent-primary)] hover:underline"+ >+ {t("openInOffboarding")}+ </Link>+ }+ />+ );+}diff --git a/tests/unit/analysis/test_owner_knowledge_rollups.py b/tests/unit/analysis/test_owner_knowledge_rollups.pyindex ca38b450c..01b38a324 100644--- a/tests/unit/analysis/test_owner_knowledge_rollups.py+++ b/tests/unit/analysis/test_owner_knowledge_rollups.py@@ -240,10 +240,14 @@ def test_knowledge_matrix_rows_are_positional_and_indexed() -> None:for row in matrix["files"]}assert list(files) == sorted(r["file_path"] for r in ROWS)- assert files["core/a.py"] == (0, "a.py", 120, 6.2, True, 1, 0, [(0, 0.8), (1, 0.2)])+ assert files["core/a.py"][:8] == (0, "a.py", 120, 6.2, True, 1, 0, [(0, 0.8), (1, 0.2)])assert files["lib/x.py"][2:4] == (40, None)# A bot-owned file keeps its row, with no owner and no authors.- assert files["deps/lock.py"][6:] == (None, [])+ assert files["deps/lock.py"][6:8] == (None, [])+ # The last element says whether the file changed in the activity window.+ assert {path: row[8] for path, row in files.items()} == {+ r["file_path"]: (r.get("commit_count_90d") or 0) > 0 for r in ROWS+ }def test_an_email_only_owner_owns_files_on_every_surface() -> None:diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.pyindex 92f3f21e3..14aeb8849 100644--- a/tests/unit/server/test_owners.py+++ b/tests/unit/server/test_owners.py@@ -296,6 +296,35 @@ async def test_list_and_profile_carry_kind_and_merged_identities(client: AsyncClassert data["aliases"] == {"names": ["Alice"], "emails": ["[email protected]"]}+async def test_list_owners_filters_by_kind(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])+ bot = {"name": "dependabot[bot]", "email": "49699333+dependabot[bot]@users.noreply.github.com"}+ async with get_session(app.state.session_factory) as session:+ await crud.upsert_git_metadata(+ session,+ repository_id=repo["id"],+ file_path="requirements.txt",+ commit_count_total=4,+ primary_owner_name=bot["name"],+ primary_owner_email=bot["email"],+ top_authors_json=json.dumps([{**bot, "commit_count": 4}]),+ bus_factor=1,+ contributor_count=1,+ )++ url = f"/api/repos/{repo['id']}/owners"+ every = (await client.get(url)).json()+ people = (await client.get(url, params={"kind": "human"})).json()+ bots = (await client.get(url, params={"kind": "bot"})).json()+ assert {i["kind"] for i in every["items"]} == {"human", "bot"}+ assert {i["kind"] for i in people["items"]} == {"human"}+ assert people["total"] == every["total"] - bots["total"]+ assert [i["name"] for i in bots["items"]] == ["dependabot[bot]"]+ assert (await client.get(url, params={"kind": "robot"})).status_code == 422++@pytest.mark.asyncioasync def test_owners_summary(client: AsyncClient, app) -> None:repo = await create_test_repo(client)@@ -329,7 +358,9 @@ async def test_knowledge_matrix(client: AsyncClient, app) -> None:a, b = keys.index("[email protected]"), keys.index("[email protected]")main = next(f for f in data["files"] if f[1] == "main.py")# No health row: score null, nloc 0.- assert main == [0, "main.py", 0, None, True, 1, a, [[a, 0.7], [b, 0.3]]]+ assert main == [0, "main.py", 0, None, True, 1, a, [[a, 0.7], [b, 0.3]], True]+ utils = next(f for f in data["files"] if f[1] == "utils.py")+ assert utils[8] is True # two commits in the window@pytest.mark.asyncio