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): people-only ownership summary and knowledge matrix (#4136)
Raghav Chamadiyaf9d5c96df2e5
diff --git a/docs/layers/OWNERSHIP.md b/docs/layers/OWNERSHIP.mdindex a263db1e5..2c097f3d7 100644--- a/docs/layers/OWNERSHIP.md+++ b/docs/layers/OWNERSHIP.md@@ -78,6 +78,16 @@ the most files in it. A module is a **silo** when one person owns more than 80%of its files. Per file, the dashboard and REST API mark a silo when the primaryowner holds more than 80% of the file's commits.+### Repository summary and knowledge matrix++`/api/repos/<id>/owners/summary` returns the truck factor, single-owner files,+silo modules, the share of owned files held by the top three people, active+contributors, and quiet owners (no commit in 90 days, still owning files that+changed in that window). `/api/repos/<id>/owners/knowledge-matrix` returns every+code file's top five people with their share of its commits, for off-boarding+what-ifs. Both count people only: bots and coding agents own nothing and hold no+share, and each contributor carries a `kind` (`human`, `bot`, `agent`).+### DetectorsThree code-health detectors turn these fields into findings. They run with thediff --git a/packages/api-client/src/owners.ts b/packages/api-client/src/owners.tsindex 06fbb8780..09f689cd7 100644--- a/packages/api-client/src/owners.ts+++ b/packages/api-client/src/owners.ts@@ -1,3 +1,4 @@+import type { KnowledgeMatrix, OwnersSummary } from "@repowise-dev/types/owners";import { apiGet } from "./client";import { fetchAllPaginated } from "./pagination";import type {@@ -51,3 +52,13 @@ export async function getOwnerProfile(`/api/repos/${repoId}/owners/${encodeURIComponent(ownerKey)}`,);}++/** Truck factor, silos, concentration and activity; people only, built once per index. */+export async function getOwnersSummary(repoId: string): Promise<OwnersSummary> {+ return apiGet<OwnersSummary>(`/api/repos/${repoId}/owners/summary`);+}++/** Every code file's top authors and risk facts, for client-side off-boarding. */+export async function getKnowledgeMatrix(repoId: string): Promise<KnowledgeMatrix> {+ return apiGet<KnowledgeMatrix>(`/api/repos/${repoId}/owners/knowledge-matrix`);+}diff --git a/packages/api-client/src/types/ownership.ts b/packages/api-client/src/types/ownership.tsindex 0e0d4ff61..498761322 100644--- a/packages/api-client/src/types/ownership.ts+++ b/packages/api-client/src/types/ownership.ts@@ -1,3 +1,5 @@+import type { IdentityKind, OwnerAliases } from "@repowise-dev/types/owners";+// ---------------------------------------------------------------------------// Owner / contributor profile// ---------------------------------------------------------------------------@@ -6,6 +8,7 @@ export interface OwnerListEntry {key: string;name: string;email: string | null;+ kind: IdentityKind;files_owned: number;hotspots_owned: number;silo_modules: number;@@ -44,6 +47,8 @@ export interface OwnerProfileResponse {key: string;name: string;email: string | null;+ kind: IdentityKind;+ aliases: OwnerAliases;files_owned: number;hotspots_owned: number;silo_modules: number;diff --git a/packages/core/src/repowise/core/analysis/knowledge_matrix.py b/packages/core/src/repowise/core/analysis/knowledge_matrix.pynew file mode 100644index 000000000..a08031f32--- /dev/null+++ b/packages/core/src/repowise/core/analysis/knowledge_matrix.py@@ -0,0 +1,135 @@+"""Per-file knowledge rows, compact enough to ship whole to the browser.++The Contributors page simulates off-boarding client side ("if these people+left, which files lose most of the knowledge behind them"), so it needs every+file at once, not a page. Rows are positional tuples and name people and+directories by index into two dictionaries, which keeps a 6k-file repository+well under half a megabyte gzipped.++People only: automation (bots and coding agents) is left out of every share,+on both sides of the fraction, the same rule the truck factor and the+concentration figure follow. A file only automation touched has no authors.+``bus_factor`` is the indexer's own figure, as every other surface shows it.++Sync, no I/O. Rows may be dicts, dataclasses or ORM rows.+"""++from __future__ import annotations++import posixpath+from collections import Counter+from collections.abc import Iterable, Mapping+from typing import Any++from repowise.core.analysis.health.rows import field as row_field+from repowise.core.analysis.health.rows import json_field+from repowise.core.analysis.owners import OwnerAccumulator, is_active+from repowise.core.analysis.ownership_concentration import person_owner+from repowise.core.author_identity import IdentityResolver++#: Authors kept per file, strongest first.+TOP_AUTHORS = 5+++def file_author_shares(+ row: Any, resolve: IdentityResolver, top: int = TOP_AUTHORS+) -> list[tuple[str, float]]:+ """``(identity key, share of the file's human commits)``, strongest first.++ Entries of one person under two names or emails merge before ranking.+ Shares are of every human commit the row records (its top 50 authors),+ so the kept *top* may sum to under 1.+ """+ commits: Counter[str] = Counter()+ for a in json_field(row, "top_authors_json", []):+ key = resolve(a.get("name"), a.get("email") or None)+ count = int(a.get("commit_count") or 0)+ if key and count > 0 and not resolve.is_bot(key):+ commits[key] += count+ total = commits.total()+ ranked = sorted(commits.items(), key=lambda kv: (-kv[1], kv[0]))[:top]+ return [(key, n / total) for key, n in ranked]+++class _Index:+ """Values to dense positions, in first-seen order."""++ def __init__(self) -> None:+ self.items: list[str] = []+ self._pos: dict[str, int] = {}++ def __call__(self, value: str) -> int:+ pos = self._pos.get(value)+ if pos is None:+ pos = self._pos[value] = len(self.items)+ self.items.append(value)+ return pos+++def _author_entry(+ key: str, accs: Mapping[str, OwnerAccumulator], resolve: IdentityResolver+) -> dict[str, Any]:+ acc = accs.get(key)+ last = acc.last_commit_at if acc else None+ return {+ "key": key,+ "name": acc.name if acc else resolve.display_name(key),+ "email": acc.email if acc else None,+ "last_commit_at": last.isoformat() if last else None,+ "active": bool(acc and is_active(acc)),+ }+++def build_knowledge_matrix(+ git_rows: Iterable[Any],+ resolve: IdentityResolver,+ accs: Mapping[str, OwnerAccumulator],+ health: Mapping[str, tuple[float | None, int]],+) -> dict[str, Any]:+ """The matrix payload; see ``KnowledgeMatrixResponse`` for the fields.++ ``health`` maps a path to its ``(score, nloc)``; a file without a health+ row gets ``None`` and 0. Files come sorted by path; authors are indexed by+ how many files they appear on, most first, so the commonest indices are+ the shortest.+ """+ shaped = []+ seen: Counter[str] = Counter()+ for m in sorted(git_rows, key=lambda r: row_field(r, "file_path")):+ shares = file_author_shares(m, resolve)+ primary = person_owner(m, resolve)+ seen.update({key for key, _ in shares} | ({primary} if primary else set()))+ shaped.append((m, shares, primary))++ authors = sorted(seen, key=lambda k: (-seen[k], k))+ author_pos = {key: i for i, key in enumerate(authors)}+ dirs = _Index()+ files = []+ for m, shares, primary in shaped:+ path = row_field(m, "file_path")+ directory, name = posixpath.split(path)+ score, nloc = health.get(path, (None, 0))+ files.append(+ (+ dirs(directory),+ name,+ nloc or 0,+ round(score, 1) if score is not None else None,+ bool(row_field(m, "is_hotspot")),+ 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],+ )+ )+ return {+ "authors": [_author_entry(key, accs, resolve) for key in authors],+ "dirs": dirs.items,+ "files": files,+ }+++__all__ = [+ "TOP_AUTHORS",+ "build_knowledge_matrix",+ "file_author_shares",+]diff --git a/packages/core/src/repowise/core/analysis/owners.py b/packages/core/src/repowise/core/analysis/owners.pyindex b111b38e0..d75af8579 100644--- a/packages/core/src/repowise/core/analysis/owners.py+++ b/packages/core/src/repowise/core/analysis/owners.py@@ -27,6 +27,7 @@ from repowise.core.analysis.health.aggregation import module_labelfrom repowise.core.analysis.health.rows import field as row_fieldfrom repowise.core.analysis.health.rows import json_fieldfrom repowise.core.author_identity import (+ IdentityKind,IdentityResolver,build_identity_resolver,canonicalize_author_email,@@ -70,10 +71,16 @@ class OwnerAccumulator:key: strname: stremail: str | None = None+ kind: IdentityKind = "human"+ # Every display name and canonical email folded into this identity.+ alias_names: list[str] = field(default_factory=list)+ alias_emails: list[str] = field(default_factory=list)files_owned: int = 0 # files where this person is primary_ownerhotspots_owned: int = 0bus_factor_risk_files: int = 0+ # Owned files with a commit in the last 90 days (the git row's own count).+ owned_changing_files: int = 0# Distinct commits in the 90 days before HEAD; None when the commit rows# are missing or do not reach back across the whole window.commit_count_90d: int | None = None@@ -137,6 +144,7 @@ def aggregate_owners(dead_rows: Iterable[Any],commit_rows: Iterable[Any] | None = None,total_commits: int | None = None,+ resolve: IdentityResolver | None = None,) -> tuple[dict[str, OwnerAccumulator], dict[str, int]]:"""Walk every git row once, returning per-owner accumulators and files per module.@@ -146,13 +154,16 @@ def aggregate_owners(``author_email``, ``committed_at``), newest non-merge commits from HEAD;``total_commits`` the repo's non-merge total, which says whether a samplethat stops inside the window is nonetheless the whole history.+ ``resolve`` is :func:`people_resolver` over the same rows, passed by a+ caller that reuses it; built here when absent."""rows = list(git_rows)commits = list(commit_rows or [])accs: dict[str, OwnerAccumulator] = {}module_totals: dict[str, int] = defaultdict(int)- resolve = people_resolver(rows, commits)+ if resolve is None:+ resolve = people_resolver(rows, commits)def _ensure(name: str, email: str | None) -> OwnerAccumulator:k = resolve(name, email)@@ -160,7 +171,15 @@ def aggregate_owners(return OwnerAccumulator(key="", name=name or "(unknown)", email=email)acc = accs.get(k)if acc is None:- acc = OwnerAccumulator(key=k, name=resolve.display_name(k), email=email)+ names, emails = resolve.aliases(k)+ acc = OwnerAccumulator(+ key=k,+ name=resolve.display_name(k),+ email=email,+ kind=resolve.kind(k),+ alias_names=names,+ alias_emails=emails,+ )accs[k] = accif email and not acc.email:acc.email = email@@ -227,8 +246,11 @@ def aggregate_owners(if row_field(m, "is_hotspot"):primary.hotspots_owned += 1primary.module_hotspots[module] += 1- if (row_field(m, "bus_factor") or 0) <= 1:+ # Exactly 1: a bus factor of 0 means no indexed history, not risk.+ if (row_field(m, "bus_factor") or 0) == 1:primary.bus_factor_risk_files += 1+ if (row_field(m, "commit_count_90d") or 0) > 0:+ primary.owned_changing_files += 1# Co-author tally: each pair of distinct touchers shares this file.for i, a in enumerate(touchers):@@ -312,6 +334,19 @@ def _apply_commit_activity(acc.last_commit_at = last[key]+def is_active(acc: OwnerAccumulator) -> bool:+ """Committed in the 90 days before HEAD (a floor count counts)."""+ return bool(acc.commit_count_90d or acc.commit_count_90d_at_least)+++def is_quiet(acc: OwnerAccumulator) -> bool:+ """Known to have made no commit in the 90 days before HEAD.++ ``False`` when the commit rows do not cover the window: unknown is not quiet.+ """+ return acc.commit_count_90d == 0++def silo_modules(acc: OwnerAccumulator, module_totals: dict[str, int]) -> int:"""Count modules where this owner is >80% of file ownership."""@@ -337,6 +372,8 @@ __all__ = ["OwnerAccumulator","aggregate_owners","as_utc",+ "is_active",+ "is_quiet","module_share","owner_key","people_resolver",diff --git a/packages/core/src/repowise/core/analysis/owners_summary.py b/packages/core/src/repowise/core/analysis/owners_summary.pynew file mode 100644index 000000000..4dea6495c--- /dev/null+++ b/packages/core/src/repowise/core/analysis/owners_summary.py@@ -0,0 +1,127 @@+"""The repository-level knowledge-risk summary behind the Contributors page.++One server-side reading, so the page never derives these figures from a+partial page of owners: the truck factor, single-owner files, silo modules,+how concentrated ownership is, who is active, and who has gone quiet while+still owning files that change. People only: automation owns nothing and is+counted separately.++Sync, no I/O, no clock. Reads the owner fold's accumulators and the same git+rows and identity resolver the fold was built from.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from typing import Any++from repowise.core.analysis.owners import (+ ACTIVITY_WINDOW_DAYS,+ OwnerAccumulator,+ is_active,+ is_quiet,+)+from repowise.core.analysis.ownership_concentration import (+ OwnedFiles,+ module_silos,+ owned_files,+ top_owners,+ truck_factor,+)+from repowise.core.author_identity import IdentityResolver++#: Owners counted in the concentration figure.+CONCENTRATION_TOP_N = 3+#: Longest quiet-owner list returned; ``quiet_owners_total`` carries the rest.+QUIET_OWNERS_CAP = 25+++def _iso(acc: OwnerAccumulator | None) -> str | None:+ at = acc.last_commit_at if acc else None+ return at.isoformat() if at else None+++Accs = Mapping[str, OwnerAccumulator]+++def _person(accs: Accs, key: str, resolve: IdentityResolver) -> dict:+ acc = accs.get(key)+ return {"key": key, "name": acc.name if acc else resolve.display_name(key)}+++def _concentration(owned: OwnedFiles, accs: Accs, resolve: IdentityResolver) -> dict[str, Any]:+ total = owned.owned_total+ top = top_owners(owned, CONCENTRATION_TOP_N)+ return {+ "top_n": CONCENTRATION_TOP_N,+ "share": (sum(n for _, n in top) / total) if total else None,+ "owners": [+ {**_person(accs, key, resolve), "files_owned": n, "share": n / total}+ for key, n in top+ ],+ }+++def _silos(owned: OwnedFiles, accs: Accs, resolve: IdentityResolver) -> list[dict[str, Any]]:+ return [+ {+ "module": s.module,+ "owner": _person(accs, s.owner, resolve),+ "owned_files": s.owned,+ "file_count": s.file_count,+ "share": s.share,+ }+ for s in module_silos(owned)+ ]+++def _activity(people: list[OwnerAccumulator]) -> dict[str, Any]:+ """Who is active, and who has gone quiet while owning files that still change."""+ quiet = sorted(+ (a for a in people if is_quiet(a) and a.owned_changing_files > 0),+ key=lambda a: (-a.owned_changing_files, -a.files_owned, a.key),+ )+ return {+ "activity_window_days": ACTIVITY_WINDOW_DAYS,+ # A floor when the indexed commits stop inside the window.+ "active_contributors": sum(1 for a in people if is_active(a)),+ "activity_complete": any(a.commit_count_90d is not None for a in people),+ "quiet_owners": [+ {+ "key": a.key,+ "name": a.name,+ "last_commit_at": _iso(a),+ "files_owned": a.files_owned,+ "changing_files_owned": a.owned_changing_files,+ }+ for a in quiet[:QUIET_OWNERS_CAP]+ ],+ "quiet_owners_total": len(quiet),+ }+++def build_owner_summary(+ git_rows: Iterable[Any],+ resolve: IdentityResolver,+ accs: Accs,+) -> dict[str, Any]:+ """The summary payload; see ``OwnersSummaryResponse`` for the fields."""+ owned = owned_files(git_rows, resolve)+ identities = [a for a in accs.values() if a.key]+ people = [a for a in identities if a.kind == "human"]+ return {+ "truck_factor": truck_factor(owned),+ "people": len(people),+ "automation_identities": len(identities) - len(people),+ "owners": len(owned.by_owner),+ "tracked_files": sum(owned.module_totals.values()),+ "owned_files": owned.owned_total,+ "single_owner_files": owned.single_owner_files,+ "single_owner_hotspots": owned.single_owner_hotspots,+ "concentration": _concentration(owned, accs, resolve),+ "silo_modules": _silos(owned, accs, resolve),+ **_activity(people),+ }+++__all__ = ["CONCENTRATION_TOP_N", "QUIET_OWNERS_CAP", "build_owner_summary"]diff --git a/packages/core/src/repowise/core/analysis/ownership_concentration.py b/packages/core/src/repowise/core/analysis/ownership_concentration.pynew file mode 100644index 000000000..2df48b51a--- /dev/null+++ b/packages/core/src/repowise/core/analysis/ownership_concentration.py@@ -0,0 +1,133 @@+"""How concentrated a repository's file ownership is among people.++One reading of "who owns what", shared by the Stats page+(:func:`repowise.core.stats_highlights.build_people`) and the owners summary so+both publish the same truck factor, silos and single-owner count. Owners are+people: each file's primary owner goes through the caller's identity resolver+and automation (bots and coding agents) owns nothing here.++Sync, no I/O. Rows may be dicts, dataclasses or ORM rows.+"""++from __future__ import annotations++from collections import Counter+from collections.abc import Iterable+from dataclasses import dataclass, field+from typing import Any++from repowise.core.analysis.health.aggregation import module_label+from repowise.core.analysis.health.rows import field as row_field+from repowise.core.author_identity import IdentityResolver++#: A module is a silo when one person owns more than this share of its files.+SILO_SHARE = 0.8+++@dataclass+class OwnedFiles:+ """Primary-owned files per person, overall and per top-level module."""++ by_owner: Counter[str] = field(default_factory=Counter)+ by_module: dict[str, Counter[str]] = field(default_factory=dict)+ # Every file per module, owned by a person or not.+ module_totals: Counter[str] = field(default_factory=Counter)+ # Person-owned files whose bus factor is exactly 1 (0 means no history,+ # not risk), and those of them git flags as hotspots.+ single_owner_files: int = 0+ single_owner_hotspots: int = 0++ @property+ def owned_total(self) -> int:+ return sum(self.by_owner.values())+++@dataclass(frozen=True)+class ModuleSilo:+ module: str+ owner: str+ owned: int+ file_count: int++ @property+ def share(self) -> float:+ return self.owned / self.file_count+++def person_owner(row: Any, resolve: IdentityResolver) -> str | None:+ """The row's primary owner as a person's key; ``None`` for automation or nobody.++ Keyed as the owner fold keys it, so an email-only owner counts too.+ """+ name = row_field(row, "primary_owner_name")+ email = row_field(row, "primary_owner_email")+ if not (name or email):+ return None+ key = resolve(name, email)+ return key if key and not resolve.is_bot(key) else None+++def owned_files(rows: Iterable[Any], resolve: IdentityResolver) -> OwnedFiles:+ """Fold git rows into per-person primary ownership."""+ out = OwnedFiles()+ for m in rows:+ owner = person_owner(m, resolve)+ module = module_label(row_field(m, "file_path"))+ out.module_totals[module] += 1+ if not owner:+ continue+ out.by_owner[owner] += 1+ out.by_module.setdefault(module, Counter())[owner] += 1+ if (row_field(m, "bus_factor") or 0) == 1:+ out.single_owner_files += 1+ out.single_owner_hotspots += bool(row_field(m, "is_hotspot"))+ return out+++def truck_factor(owned: OwnedFiles) -> int | None:+ """Fewest people who together own more than half the owned files.++ ``None`` when no person owns a file.+ """+ total = owned.owned_total+ if not total:+ return None+ cumulative = count = 0+ for files in sorted(owned.by_owner.values(), reverse=True):+ cumulative += files+ count += 1+ if cumulative * 2 > total:+ break+ return count+++def module_silos(owned: OwnedFiles) -> list[ModuleSilo]:+ """Modules where one person owns more than :data:`SILO_SHARE` of the files.++ Largest modules first, then by name.+ """+ silos = []+ for module, owners in owned.by_module.items():+ owner, files = min(owners.items(), key=lambda kv: (-kv[1], kv[0]))+ total = owned.module_totals[module]+ if files / total > SILO_SHARE:+ silos.append(ModuleSilo(module, owner, files, total))+ silos.sort(key=lambda s: (-s.file_count, s.module))+ return silos+++def top_owners(owned: OwnedFiles, n: int) -> list[tuple[str, int]]:+ """The *n* people owning the most files, ties broken by key."""+ return sorted(owned.by_owner.items(), key=lambda kv: (-kv[1], kv[0]))[:n]+++__all__ = [+ "SILO_SHARE",+ "ModuleSilo",+ "OwnedFiles",+ "module_silos",+ "owned_files",+ "person_owner",+ "top_owners",+ "truck_factor",+]diff --git a/packages/core/src/repowise/core/author_identity.py b/packages/core/src/repowise/core/author_identity.pyindex f2b535519..9b539a264 100644--- a/packages/core/src/repowise/core/author_identity.py+++ b/packages/core/src/repowise/core/author_identity.py@@ -164,6 +164,8 @@ class IdentityResolver:# Automation identities only; every other key is a person.self._kinds = kindsself._agents = agents+ # key -> its member emails, built on the first ``aliases`` call.+ self._members: dict[str, list[str]] | None = Nonedef __call__(self, name: str | None, email: str | None) -> str:node = _node(name, email)@@ -192,6 +194,19 @@ class IdentityResolver:"""Every human identity the resolver was built from."""return set(self._names) - set(self._kinds)+ def aliases(self, key: str) -> tuple[list[str], list[str]]:+ """``(names, emails)`` folded into the identity *key*, each sorted.++ The names are every display name it was seen under; the emails every+ canonical address that resolves to it, its own key included.+ """+ if self._members is None:+ self._members = defaultdict(list)+ for node, k in self._key_of.items():+ if not node.startswith("name:"):+ self._members[k].append(node)+ return sorted(self._names.get(key, ())), sorted(self._members.get(key, ()))+def build_identity_resolver(pairs: Iterable[tuple[str | None, str | None]],diff --git a/packages/core/src/repowise/core/components/rollup.py b/packages/core/src/repowise/core/components/rollup.pyindex 87c2f9e85..07e04ea4d 100644--- a/packages/core/src/repowise/core/components/rollup.py+++ b/packages/core/src/repowise/core/components/rollup.py@@ -3,7 +3,7 @@Sync, no I/O. Every figure carries ``basis`` (``measured``, ``inferred`` or``unavailable``) and a ``method`` saying what it rests on. The arithmetic isthe existing one: health is :func:`module_rollups` over the component's files,-the bus factor is the repository truck factor (:func:`build_people`) taken+the bus factor is the repository truck factor (:func:`truck_factor`) takenover the component's files. Health and dead code leave out files in languages:data:`LANGUAGE_GATES` holds back on that layer, the same registry the``ungated`` SQL filter reads, and say how many. No figure names a person.@@ -18,7 +18,7 @@ from repowise.core.analysis.finding_registry import gate_forfrom repowise.core.analysis.health.aggregation import module_rollupsfrom repowise.core.analysis.health.rows import fieldfrom repowise.core.analysis.owners import people_resolver-from repowise.core.stats_highlights import build_people+from repowise.core.analysis.ownership_concentration import owned_files, truck_factor_TOP_HOTSPOTS = 5#: Below this many owned files a truck factor is an anecdote, not a measure.@@ -107,22 +107,17 @@ def _hotspots(paths: list[str], git_rows: Mapping[str, Mapping[str, Any]]) -> didef _bus_factor(paths: list[str], git_rows: Mapping[str, Mapping[str, Any]]) -> dict[str, Any]:rows = [git_rows[p] for p in paths if p in git_rows]- people = build_people(rows)- if people["truck_factor"] is None:+ owned_rows = owned_files(rows, people_resolver(rows))+ value = truck_factor(owned_rows)+ if value is None:return _unavailable("no file in this component has a known primary owner")- # Owned the way build_people counts it: a primary owner who is not a bot.- resolve = people_resolver(rows)- owned = 0- for m in rows:- name = m.get("primary_owner_name")- if name and not resolve.is_bot(resolve(name, m.get("primary_owner_email"))):- owned += 1+ owned = owned_rows.owned_totalout: dict[str, Any] = {- "value": people["truck_factor"],+ "value": value,"owned_files": owned,"file_count": len(paths),"coverage": round(owned / len(paths), 2) if paths else 0.0,- "single_owner_files": people["single_owner_files"],+ "single_owner_files": owned_rows.single_owner_files,"basis": "measured","method": "fewest primary owners who together own over half the owned files",}diff --git a/packages/core/src/repowise/core/stats_highlights.py b/packages/core/src/repowise/core/stats_highlights.pyindex 3e1bc3955..349cd0d51 100644--- a/packages/core/src/repowise/core/stats_highlights.py+++ b/packages/core/src/repowise/core/stats_highlights.py@@ -550,55 +550,25 @@ def build_people(git_metadata: Iterable[Row], commits: Iterable[Row] = ()) -> diOwners are people, not display names: each file's primary owner goesthrough :func:`people_resolver`, so one person under two names or emails- is one owner, and automation owns nothing here.+ is one owner, and automation owns nothing here. The counting itself lives+ in :mod:`repowise.core.analysis.ownership_concentration`, shared with the+ owners summary."""- from repowise.core.analysis.health.aggregation import module_labelfrom repowise.core.analysis.owners import people_resolver-- rows = list(git_metadata)- resolve = people_resolver(rows, commits)- owners: Counter[str] = Counter()- single_owner_files = 0- module_owner_files: dict[str, Counter[str]] = {}- module_file_totals: Counter[str] = Counter()-- for m in rows:- name = m.get("primary_owner_name")- owner = resolve(name, m.get("primary_owner_email")) if name else None- if owner and resolve.is_bot(owner):- owner = None- if _int(m.get("bus_factor")) == 1:- single_owner_files += 1- module = module_label(m.get("file_path"))- module_file_totals[module] += 1- if owner:- owners[owner] += 1- module_owner_files.setdefault(module, Counter())[owner] += 1-- silo_count = sum(- 1- for module, mowners in module_owner_files.items()- if max(mowners.values()) / module_file_totals[module] > 0.8+ from repowise.core.analysis.ownership_concentration import (+ module_silos,+ owned_files,+ truck_factor,)- # Fewest primary owners who together hold more than half the owned files.- owned_total = sum(owners.values())- truck_factor: int | None = None- if owned_total:- cumulative = 0- truck_factor = 0- for count in sorted(owners.values(), reverse=True):- cumulative += count- truck_factor += 1- if cumulative * 2 > owned_total:- break-+ rows = list(git_metadata)+ owned = owned_files(rows, people_resolver(rows, commits))return {- "owner_count": len(owners),- "tracked_files": sum(module_file_totals.values()),- "single_owner_files": single_owner_files,- "silo_count": silo_count,- "truck_factor": truck_factor,+ "owner_count": len(owned.by_owner),+ "tracked_files": sum(owned.module_totals.values()),+ "single_owner_files": owned.single_owner_files,+ "silo_count": len(module_silos(owned)),+ "truck_factor": truck_factor(owned),}diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.pyindex 1061919fc..63b179a90 100644--- a/packages/server/src/repowise/server/routers/owners.py+++ b/packages/server/src/repowise/server/routers/owners.py@@ -14,17 +14,22 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import (+ KnowledgeMatrixResponse,+ OwnerAliases,OwnerCoAuthor,OwnerFileEntry,OwnerListEntry,OwnerModuleRollup,OwnerProfileResponse,+ OwnersSummaryResponse,Paginated,)from repowise.server.services.owner_profile import (_OwnerAccumulator,aggregate_owners,+ knowledge_matrix,module_share,+ owner_summary,silo_modules,)@@ -45,6 +50,7 @@ def _to_list_entry(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> Ownkey=acc.key,name=acc.name,email=acc.email,+ kind=acc.kind,files_owned=acc.files_owned,hotspots_owned=acc.hotspots_owned,silo_modules=silo_modules(acc, module_totals),@@ -80,7 +86,7 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerPacc.files_touched,key=lambda fp: (acc.files_touched[fp],- (acc.file_meta[fp].churn_percentile or 0.0),+ (acc.file_meta[fp]["churn_percentile"] or 0.0),),reverse=True,)[:50]@@ -90,11 +96,11 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerPOwnerFileEntry(file_path=fp,commit_count_90d=acc.files_touched[fp],- churn_percentile=(m.churn_percentile or 0.0) * 100.0,- bus_factor=m.bus_factor or 0,- is_hotspot=bool(m.is_hotspot),- last_commit_at=m.last_commit_at,- primary_owner_commit_pct=m.primary_owner_commit_pct,+ churn_percentile=(m["churn_percentile"] or 0.0) * 100.0,+ bus_factor=m["bus_factor"] or 0,+ is_hotspot=bool(m["is_hotspot"]),+ last_commit_at=m["last_commit_at"],+ primary_owner_commit_pct=m["primary_owner_commit_pct"],))@@ -115,6 +121,8 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerPkey=acc.key,name=acc.name,email=acc.email,+ kind=acc.kind,+ aliases=OwnerAliases(names=acc.alias_names, emails=acc.alias_emails),files_owned=acc.files_owned,hotspots_owned=acc.hotspots_owned,silo_modules=silo_modules(acc, module_totals),@@ -186,6 +194,24 @@ async def list_owners()[email protected]("/{repo_id}/owners/summary", response_model=OwnersSummaryResponse)+async def get_owners_summary(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Truck factor, single-owner files, silos, concentration and activity, people only."""+ return await owner_summary(session, repo_id)++[email protected]("/{repo_id}/owners/knowledge-matrix", response_model=KnowledgeMatrixResponse)+async def get_knowledge_matrix(+ repo_id: str,+ session: AsyncSession = Depends(get_db_session),+) -> dict:+ """Every code file's top authors and risk facts, for client-side off-boarding."""+ return await knowledge_matrix(session, repo_id)++@router.get("/{repo_id}/owners/{owner_key:path}",response_model=OwnerProfileResponse,diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 132b2b874..c688ed850 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -210,14 +210,17 @@ if TYPE_CHECKING:KnowledgeMapResponse,KnowledgeMapSilo,KnowledgeMapTarget,+ KnowledgeMatrixResponse,ModuleHealthDetail,ModuleHealthOwner,ModuleHealthSummary,+ OwnerAliases,OwnerCoAuthor,OwnerFileEntry,OwnerListEntry,OwnerModuleRollup,OwnerProfileResponse,+ OwnersSummaryResponse,ReviewerSuggestion,ReviewerSuggestionsResponse,)@@ -523,14 +526,17 @@ _EXPORTS: dict[str, tuple[str, ...]] = {"KnowledgeMapResponse","KnowledgeMapSilo","KnowledgeMapTarget",+ "KnowledgeMatrixResponse","ModuleHealthDetail","ModuleHealthOwner","ModuleHealthSummary",+ "OwnerAliases","OwnerCoAuthor","OwnerFileEntry","OwnerListEntry","OwnerModuleRollup","OwnerProfileResponse",+ "OwnersSummaryResponse","ReviewerSuggestion","ReviewerSuggestionsResponse",),@@ -804,6 +810,7 @@ __all__ = ["KnowledgeMapResponse","KnowledgeMapSilo","KnowledgeMapTarget",+ "KnowledgeMatrixResponse","McpToolInfo","McpToolSurfaceResponse","ModuleEdgeResponse",@@ -815,11 +822,13 @@ __all__ = ["NeighboringCommunity","NodeSearchResult","OkResponse",+ "OwnerAliases","OwnerCoAuthor","OwnerFileEntry","OwnerListEntry","OwnerModuleRollup","OwnerProfileResponse",+ "OwnersSummaryResponse","OwnershipEntry","PageResponse","PageSummaryResponse",diff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.pyindex dd1e32cbd..e741ea602 100644--- a/packages/server/src/repowise/server/schemas/ownership.py+++ b/packages/server/src/repowise/server/schemas/ownership.py@@ -3,9 +3,13 @@from __future__ import annotationsfrom datetime import datetime+from typing import Literalfrom pydantic import BaseModel+#: Who an identity is: a person, other automation, or a coding agent.+IdentityKindField = Literal["human", "bot", "agent"]+class KnowledgeMapOwner(BaseModel):email: str@@ -38,6 +42,7 @@ class OwnerListEntry(BaseModel):key: str # stable identifier for the URL (email if known, else name)name: stremail: str | None+ kind: IdentityKindFieldfiles_owned: inthotspots_owned: intsilo_modules: int # modules where this owner is >80%@@ -49,7 +54,7 @@ class OwnerListEntry(BaseModel):# A floor of that count when the indexed commits stop inside the window.commit_count_90d_at_least: int | None = Nonelast_commit_at: datetime | None- bus_factor_risk_files: int # files they own where bus_factor <= 1+ bus_factor_risk_files: int # files they own whose bus_factor is exactly 1class OwnerModuleRollup(BaseModel):@@ -76,10 +81,19 @@ class OwnerCoAuthor(BaseModel):co_change_strength: float # 0-1 fraction+class OwnerAliases(BaseModel):+ """Every display name and canonical email folded into one person."""++ names: list[str]+ emails: list[str]++class OwnerProfileResponse(BaseModel):key: strname: stremail: str | None+ kind: IdentityKindField+ aliases: OwnerAliases# Headline metricsfiles_owned: int@@ -112,6 +126,82 @@ class OwnerProfileResponse(BaseModel):commit_categories: dict+class OwnerRef(BaseModel):+ key: str+ name: str+++class ConcentrationOwner(OwnerRef):+ files_owned: int+ share: float # of all person-owned files (0-1)+++class OwnershipConcentration(BaseModel):+ top_n: int+ # Share of person-owned files the top_n people own; None when nobody owns one.+ share: float | None+ owners: list[ConcentrationOwner]+++class SiloModule(BaseModel):+ module: str+ owner: OwnerRef+ owned_files: int+ file_count: int+ share: float # owned_files / file_count, above 0.8+++class QuietOwner(OwnerRef):+ last_commit_at: datetime | None+ files_owned: int+ changing_files_owned: int # owned files with a commit in the last 90 days+++class OwnersSummaryResponse(BaseModel):+ """Repository knowledge risk, people only (automation owns nothing)."""++ truck_factor: int | None+ people: int+ automation_identities: int+ owners: int+ tracked_files: int+ owned_files: int+ single_owner_files: int # bus factor exactly 1+ single_owner_hotspots: int+ concentration: OwnershipConcentration+ silo_modules: list[SiloModule]+ activity_window_days: int+ # People with a commit in the window; a floor when activity_complete is false.+ active_contributors: int+ activity_complete: bool+ # People with no commit in the window who still own files that changed in it.+ quiet_owners: list[QuietOwner]+ quiet_owners_total: int+++class KnowledgeMatrixAuthor(BaseModel):+ key: str # the owner key used by /owners/{key}+ name: str+ email: str | None+ last_commit_at: str | None+ active: bool # committed in the 90 days before HEAD+++#: One file: (dir index, file name, nloc, health score, is_hotspot, bus_factor,+#: primary owner author index, [(author index, share of human commits)]).+KnowledgeMatrixFile = tuple[+ int, str, int, float | None, bool, int, int | None, list[tuple[int, float]]+]+++class KnowledgeMatrixResponse(BaseModel):+ """Every code file's top-5 human authors, positional and indexed for size."""++ authors: list[KnowledgeMatrixAuthor]+ dirs: list[str] # "" is the repository root+ files: list[KnowledgeMatrixFile]++class ModuleHealthOwner(BaseModel):name: stremail: str | Nonediff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.pyindex 9f3f4cbdb..8fbba8712 100644--- a/packages/server/src/repowise/server/services/owner_profile.py+++ b/packages/server/src/repowise/server/services/owner_profile.py@@ -3,46 +3,90 @@Fetches ``GitMetadata``, ``DeadCodeFinding`` and ``GitCommit`` rows and folds them with:func:`repowise.core.analysis.owners.aggregate_owners`. The exposed ``key`` isURL-safe only at the router layer; the fold deals with the canonical form.++The fold reads every git row of the repository, so it and everything derived+from it (the summary, the knowledge matrix) are built once per index state+through :func:`per_index` and shared read-only across requests."""from __future__ import annotations+from dataclasses import dataclass+from typing import Any+from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis import owners as _foldfrom repowise.core.analysis.finding_registry import excluded_types+from repowise.core.analysis.health.rows import json_field+from repowise.core.analysis.knowledge_matrix import build_knowledge_matrixfrom repowise.core.analysis.owners import (OwnerAccumulator,module_share,owner_key,+ people_resolver,silo_modules,)+from repowise.core.analysis.owners_summary import build_owner_summary+from repowise.core.author_identity import IdentityResolverfrom repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.crud.analysis.shown import ungatedfrom repowise.core.persistence.models import (DeadCodeFinding,GitCommit,GitMetadata,+ HealthFileMetric,Repository,)+from repowise.server.mcp_server._graph_files import per_index_OwnerAccumulator = OwnerAccumulator+# What the fold, the profile shaper and the matrix read from a git row.+_GIT_COLUMNS = (+ GitMetadata.file_path,+ GitMetadata.primary_owner_name,+ GitMetadata.primary_owner_email,+ GitMetadata.primary_owner_commit_pct,+ GitMetadata.top_authors_json,+ GitMetadata.commit_categories_json,+ GitMetadata.commit_count_90d,+ GitMetadata.lines_added_90d,+ GitMetadata.lines_deleted_90d,+ GitMetadata.first_commit_at,+ GitMetadata.last_commit_at,+ GitMetadata.is_hotspot,+ GitMetadata.bus_factor,+ GitMetadata.churn_percentile,+)+_JSON_COLUMNS = {"top_authors_json": [], "commit_categories_json": {}}-async def aggregate_owners(- session: AsyncSession, repo_id: str-) -> tuple[dict[str, OwnerAccumulator], dict[str, int]]:- """Per-owner accumulators and files per module for *repo_id*.- Git rows stay ORM entities: ``file_meta`` hands them back to the router.- """+@dataclass(frozen=True)+class OwnerData:+ """One repository's owner fold and the inputs it was built from. Read-only."""- git_rows = (- (await session.execute(select(GitMetadata).where(code_file_rows(repo_id))))- .scalars()- .all()- )+ git_rows: list[dict[str, Any]]+ resolve: IdentityResolver+ accs: dict[str, OwnerAccumulator]+ module_totals: dict[str, int]+++async def _git_rows(session: AsyncSession, repo_id: str) -> list[dict[str, Any]]:+ """Code-file git rows as plain dicts, JSON columns decoded once."""+ result = await session.execute(select(*_GIT_COLUMNS).where(code_file_rows(repo_id)))+ rows = []+ for mapping in result.mappings():+ row = dict(mapping)+ for name, default in _JSON_COLUMNS.items():+ row[name] = json_field(row, name, default)+ rows.append(row)+ return rows+++async def _load_owner_data(session: AsyncSession, repo_id: str) -> OwnerData:+ git_rows = await _git_rows(session, repo_id)dead_rows = (await session.execute(select(@@ -69,14 +113,64 @@ async def aggregate_owners(total_commits = await session.scalar(select(Repository.total_commit_count).where(Repository.id == repo_id))- return _fold.aggregate_owners(git_rows, dead_rows, commit_rows, total_commits)+ resolve = people_resolver(git_rows, commit_rows)+ accs, module_totals = _fold.aggregate_owners(+ git_rows, dead_rows, commit_rows, total_commits, resolve+ )+ return OwnerData(git_rows, resolve, accs, module_totals)+++async def owner_data(session: AsyncSession, repo_id: str) -> OwnerData:+ """The owner fold for *repo_id*, built once per index state."""+ return await per_index(+ session, repo_id, "owners.data", lambda: _load_owner_data(session, repo_id)+ )+++async def aggregate_owners(+ session: AsyncSession, repo_id: str+) -> tuple[dict[str, OwnerAccumulator], dict[str, int]]:+ """Per-owner accumulators and files per module for *repo_id*."""+ data = await owner_data(session, repo_id)+ return data.accs, data.module_totals+++async def owner_summary(session: AsyncSession, repo_id: str) -> dict[str, Any]:+ """The repository's knowledge-risk summary, built once per index state."""+ # Read first: ``per_index`` holds a lock that is not reentrant.+ data = await owner_data(session, repo_id)++ async def build() -> dict[str, Any]:+ return build_owner_summary(data.git_rows, data.resolve, data.accs)++ return await per_index(session, repo_id, "owners.summary", build)+++async def knowledge_matrix(session: AsyncSession, repo_id: str) -> dict[str, Any]:+ """Every file's knowledge row, built once per index state."""+ data = await owner_data(session, repo_id)++ async def build() -> dict[str, Any]:+ result = await session.execute(+ select(HealthFileMetric.file_path, HealthFileMetric.score, HealthFileMetric.nloc).where(+ HealthFileMetric.repository_id == repo_id+ )+ )+ health = {path: (score, nloc) for path, score, nloc in result}+ return build_knowledge_matrix(data.git_rows, data.resolve, data.accs, health)++ return await per_index(session, repo_id, "owners.knowledge_matrix", build)__all__ = ["OwnerAccumulator",+ "OwnerData","_OwnerAccumulator","aggregate_owners",+ "knowledge_matrix","module_share",+ "owner_data","owner_key",+ "owner_summary","silo_modules",]diff --git a/packages/types/__tests__/owners.test.ts b/packages/types/__tests__/owners.test.tsnew file mode 100644index 000000000..ec1cd6557--- /dev/null+++ b/packages/types/__tests__/owners.test.ts@@ -0,0 +1,15 @@+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, []];++ it("joins the row's directory and file name", () => {+ expect(knowledgeMatrixPath(["", "src/core"], row(1, "a.py"))).toBe("src/core/a.py");+ });++ it("leaves a root file bare", () => {+ expect(knowledgeMatrixPath(["", "src"], row(0, "setup.py"))).toBe("setup.py");+ });+});diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 46b7a0d4e..b2915f48e 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -988,6 +988,13 @@ export interface CommunitySummaryItem {top_file: string;}+export interface ConcentrationOwner {+ key: string;+ name: string;+ files_owned: number;+ share: number;+}+export interface ConversationDetailResponse {conversation: ConversationResponse;messages?: ChatMessageResponse[];@@ -2454,6 +2461,21 @@ export interface KnowledgeMapTarget {doc_words: number;}+export interface KnowledgeMatrixAuthor {+ key: string;+ name: string;+ email: string | null;+ last_commit_at: string | null;+ active: boolean;+}++/** Every code file's top-5 human authors, positional and indexed for size. */+export interface KnowledgeMatrixResponse {+ authors: KnowledgeMatrixAuthor[];+ dirs: string[];+ files: ([number, string, number, number | null, boolean, number, number | null, [number, number][]])[];+}+/** One tool in the configurable surface, with the flags a UI needs. */export interface McpToolInfo {name: string;@@ -2613,6 +2635,12 @@ export interface OkResponse {ok?: boolean;}+/** Every display name and canonical email folded into one person. */+export interface OwnerAliases {+ names: string[];+ emails: string[];+}+export interface OwnerCoAuthor {name: string;email: string | null;@@ -2635,6 +2663,7 @@ export interface OwnerListEntry {key: string;name: string;email: string | null;+ kind: "human" | "bot" | "agent";files_owned: number;hotspots_owned: number;silo_modules: number;@@ -2657,6 +2686,8 @@ export interface OwnerProfileResponse {key: string;name: string;email: string | null;+ kind: "human" | "bot" | "agent";+ aliases: OwnerAliases;files_owned: number;hotspots_owned: number;silo_modules: number;@@ -2677,6 +2708,36 @@ export interface OwnerProfileResponse {commit_categories: Record<string, unknown>;}+export interface OwnerRef {+ key: string;+ name: string;+}++/** Repository knowledge risk, people only (automation owns nothing). */+export interface OwnersSummaryResponse {+ truck_factor: number | null;+ people: number;+ automation_identities: number;+ owners: number;+ tracked_files: number;+ owned_files: number;+ single_owner_files: number;+ single_owner_hotspots: number;+ concentration: OwnershipConcentration;+ silo_modules: SiloModule[];+ activity_window_days: number;+ active_contributors: number;+ activity_complete: boolean;+ quiet_owners: QuietOwner[];+ quiet_owners_total: number;+}++export interface OwnershipConcentration {+ top_n: number;+ share: number | null;+ owners: ConcentrationOwner[];+}+export interface OwnershipEntry {module_path: string;primary_owner: string | null;@@ -3107,6 +3168,14 @@ export interface QueueCounts {gated?: number;}+export interface QuietOwner {+ key: string;+ name: string;+ last_commit_at: string | null;+ files_owned: number;+ changing_files_owned: number;+}+/** What the ``fix_first`` scope leaves out of a page's filtered set. */export interface RefactoringHiddenCounts {total?: number;@@ -3685,6 +3754,14 @@ export interface SetApiKeyRequest {repo_id?: string | null;}+export interface SiloModule {+ module: string;+ owner: OwnerRef;+ owned_files: number;+ file_count: number;+ share: number;+}+/** One change in reading order; ``signals`` holds each signal that fired. */export interface Suspect {id: string;diff --git a/packages/types/src/owners.ts b/packages/types/src/owners.tsindex 6f0a9090c..63cdca060 100644--- a/packages/types/src/owners.ts+++ b/packages/types/src/owners.ts@@ -4,10 +4,14 @@* `/api/repos/{id}/owners` and `/api/repos/{id}/owners/{key}`.*/+/** Who an identity is: a person, other automation, or a coding agent. */+export type IdentityKind = "human" | "bot" | "agent";+export interface OwnerListEntry {key: string;name: string;email: string | null;+ kind: IdentityKind;files_owned: number;hotspots_owned: number;silo_modules: number;@@ -18,6 +22,7 @@ export interface OwnerListEntry {/** A floor of that count when the indexed commits stop inside the window; null otherwise. */commit_count_90d_at_least?: number | null;last_commit_at: string | null;+ /** Owned files whose bus factor is exactly 1 (0 means no indexed history). */bus_factor_risk_files: number;}@@ -48,10 +53,18 @@ export interface OwnerCoAuthor {co_change_strength: number;}+/** Every display name and canonical email folded into one person. */+export interface OwnerAliases {+ names: string[];+ emails: string[];+}+export interface OwnerProfile {key: string;name: string;email: string | null;+ kind: IdentityKind;+ aliases: OwnerAliases;files_owned: number;hotspots_owned: number;silo_modules: number;@@ -63,6 +76,7 @@ export interface OwnerProfile {commit_count_90d_at_least?: number | null;last_commit_at: string | null;first_commit_at: string | null;+ /** Owned files whose bus factor is exactly 1 (0 means no indexed history). */bus_factor_risk_files: number;/** Estimated, not exact — see Pydantic doc. */lines_added_90d_est: number;@@ -76,3 +90,108 @@ export interface OwnerProfile {co_authors_total?: number;commit_categories: Record<string, number>;}++// ---------------------------------------------------------------------------+// /owners/summary: repository knowledge risk, people only+// ---------------------------------------------------------------------------++export interface OwnerRef {+ key: string;+ name: string;+}++export interface ConcentrationOwner extends OwnerRef {+ files_owned: number;+ /** Share of person-owned files (0-1). */+ share: number;+}++export interface OwnershipConcentration {+ top_n: number;+ /** Share of person-owned files the top_n people own; null when nobody owns one. */+ share: number | null;+ owners: ConcentrationOwner[];+}++export interface SiloModule {+ module: string;+ owner: OwnerRef;+ owned_files: number;+ file_count: number;+ /** owned_files / file_count, above 0.8. */+ share: number;+}++export interface QuietOwner extends OwnerRef {+ last_commit_at: string | null;+ files_owned: number;+ /** Owned files with a commit in the last 90 days. */+ changing_files_owned: number;+}++/** Automation (bots, coding agents) owns nothing in any of these figures. */+export interface OwnersSummary {+ truck_factor: number | null;+ people: number;+ automation_identities: number;+ owners: number;+ tracked_files: number;+ owned_files: number;+ /** Files whose bus factor is exactly 1. */+ single_owner_files: number;+ single_owner_hotspots: number;+ concentration: OwnershipConcentration;+ silo_modules: SiloModule[];+ activity_window_days: number;+ /** People with a commit in the window; a floor when activity_complete is false. */+ active_contributors: number;+ activity_complete: boolean;+ /** People with no commit in the window who still own files that changed in it. */+ quiet_owners: QuietOwner[];+ quiet_owners_total: number;+}++// ---------------------------------------------------------------------------+// /owners/knowledge-matrix: every code file, compact, for off-boarding+// ---------------------------------------------------------------------------++export interface KnowledgeMatrixAuthor {+ /** The owner key used by /owners/{key}. */+ key: string;+ name: string;+ email: string | null;+ last_commit_at: string | null;+ /** Committed in the 90 days before HEAD. */+ active: boolean;+}++/** [index into `authors`, share of the file's human commits (0-1)]. */+export type KnowledgeMatrixShare = [author: number, share: number];++export type KnowledgeMatrixFile = [+ dir: number,+ name: string,+ nloc: number,+ healthScore: number | null,+ isHotspot: boolean,+ busFactor: number,+ primaryOwner: number | null,+ authors: KnowledgeMatrixShare[],+];++/**+ * Bots and coding agents are left out of every share. Each file lists its top+ * 5 people; anyone outside them holds less than the fifth share.+ */+export interface KnowledgeMatrix {+ authors: KnowledgeMatrixAuthor[];+ /** Directory per index; "" is the repository root. */+ dirs: string[];+ files: KnowledgeMatrixFile[];+}++/** A matrix row's repository-relative path. */+export function knowledgeMatrixPath(dirs: readonly string[], file: KnowledgeMatrixFile): string {+ const dir = dirs[file[0]];+ return dir ? `${dir}/${file[1]}` : file[1];+}diff --git a/packages/ui/__tests__/owners/owner-table.test.tsx b/packages/ui/__tests__/owners/owner-table.test.tsxindex 30e16279b..ad3e0326e 100644--- a/packages/ui/__tests__/owners/owner-table.test.tsx+++ b/packages/ui/__tests__/owners/owner-table.test.tsx@@ -8,6 +8,7 @@ const owner = (name: string, over: Partial<OwnerListEntry>): OwnerListEntry => (key: name,name,email: null,+ kind: "human",files_owned: 3,hotspots_owned: 0,silo_modules: 0,diff --git a/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsx b/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsxindex fcd91d7bd..eb0d53631 100644--- a/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsx+++ b/packages/ui/__tests__/owners/ownership-distribution-bar.test.tsx@@ -8,6 +8,7 @@ const owner = (name: string, files: number): OwnerListEntry => ({key: name,name,email: null,+ kind: "human",files_owned: files,hotspots_owned: 0,silo_modules: 0,diff --git a/tests/unit/analysis/test_owner_knowledge_rollups.py b/tests/unit/analysis/test_owner_knowledge_rollups.pynew file mode 100644index 000000000..ca38b450c--- /dev/null+++ b/tests/unit/analysis/test_owner_knowledge_rollups.py@@ -0,0 +1,279 @@+"""The owners summary, the knowledge matrix and the concentration they share.++All three read people, never automation: a bot's commits and owned files+leave every share, on both sides of the fraction.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta++from repowise.core.analysis.knowledge_matrix import (+ build_knowledge_matrix,+ file_author_shares,+)+from repowise.core.analysis.owners import aggregate_owners, people_resolver+from repowise.core.analysis.owners_summary import build_owner_summary+from repowise.core.analysis.ownership_concentration import (+ module_silos,+ owned_files,+ person_owner,+ top_owners,+ truck_factor,+)+from repowise.core.stats_highlights import build_people++_HEAD = datetime(2026, 9, 1, tzinfo=UTC)+_BOT = ("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com")+_ADA = ("Ada Lovelace", "[email protected]")+_ADA_ALT = ("Ada Lovelace", "[email protected]")+_BOB = ("Bob Stone", "[email protected]")+_CY = ("Cy Young", "[email protected]")+++def _author(who: tuple[str, str], commits: int) -> dict:+ return {"name": who[0], "email": who[1], "commit_count": commits}+++def _row(+ path: str,+ owner: tuple[str, str],+ authors: list[dict],+ *,+ bus_factor: int = 1,+ hotspot: bool = False,+ changed_90d: int = 0,+) -> dict:+ return {+ "file_path": path,+ "primary_owner_name": owner[0],+ "primary_owner_email": owner[1],+ "top_authors_json": authors,+ "bus_factor": bus_factor,+ "is_hotspot": hotspot,+ "commit_count_90d": changed_90d,+ }+++def _commit(sha: str, who: tuple[str, str], days_before_head: int) -> dict:+ return {+ "sha": sha,+ "author_name": who[0],+ "author_email": who[1],+ "committed_at": _HEAD - timedelta(days=days_before_head),+ }+++# Ada owns the core (one file under her noreply address); Bob owns lib and+# has gone quiet while it still changes; Cy owns one file; the bot owns two.+ROWS = [+ _row("core/a.py", _ADA, [_author(_ADA, 8), _author(_BOT, 10), _author(_BOB, 2)], hotspot=True),+ _row("core/b.py", _ADA_ALT, [_author(_ADA_ALT, 3), _author(_ADA, 3)]),+ _row("core/c.py", _ADA, [_author(_ADA, 5), _author(_CY, 5)], bus_factor=2),+ _row("lib/x.py", _BOB, [_author(_BOB, 9), _author(_ADA, 1)], changed_90d=3),+ _row("lib/y.py", _BOB, [_author(_BOB, 4)], changed_90d=1, hotspot=True),+ _row("tools/t.py", _CY, [_author(_CY, 2)]),+ _row("deps/lock.py", _BOT, [_author(_BOT, 40)]),+ _row("deps/pin.py", _BOT, [_author(_BOT, 12)]),+]+COMMITS = [+ _commit("s1", _ADA, 1),+ _commit("s2", _ADA_ALT, 5),+ _commit("s3", _CY, 30),+ _commit("s4", _BOT, 2),+ _commit("s5", _BOB, 200),+]+++def _fold():+ resolve = people_resolver(ROWS, COMMITS)+ accs, _ = aggregate_owners(ROWS, [], COMMITS, total_commits=len(COMMITS), resolve=resolve)+ return resolve, accs+++# ---------------------------------------------------------------------------+# Concentration+# ---------------------------------------------------------------------------+++def test_owned_files_counts_people_and_leaves_automation_out() -> None:+ owned = owned_files(ROWS, people_resolver(ROWS, COMMITS))+ assert dict(owned.by_owner) == {"[email protected]": 3, "[email protected]": 2, "[email protected]": 1}+ assert owned.owned_total == 6+ assert owned.single_owner_files == 5+ assert sum(owned.module_totals.values()) == len(ROWS)+++def test_truck_factor_silos_and_top_owners() -> None:+ owned = owned_files(ROWS, people_resolver(ROWS, COMMITS))+ # Ada's 3 of 6 is not more than half; Ada and Bob are.+ assert truck_factor(owned) == 2+ assert [(s.module, s.owner, s.owned, s.file_count) for s in module_silos(owned)] == [+ ("core", "[email protected]", 3, 3),+ ("lib", "[email protected]", 2, 2),+ ("tools", "[email protected]", 1, 1),+ ]+ assert top_owners(owned, 2) == [("[email protected]", 3), ("[email protected]", 2)]+ assert truck_factor(owned_files([], people_resolver())) is None+++def test_build_people_reads_the_shared_concentration() -> None:+ people = build_people(ROWS, COMMITS)+ assert people == {+ "owner_count": 3,+ "tracked_files": 8,+ "single_owner_files": 5,+ "silo_count": 3,+ "truck_factor": 2,+ }+++# ---------------------------------------------------------------------------+# Identity on the owner fold+# ---------------------------------------------------------------------------+++def test_owner_fold_carries_kind_and_merged_identities() -> None:+ _resolve, accs = _fold()+ ada = accs["[email protected]"]+ assert ada.kind == "human"+ assert ada.alias_names == ["Ada Lovelace"]+ assert ada.alias_emails == ["[email protected]", "[email protected]"]+ bot = next(a for a in accs.values() if a.name.startswith("dependabot"))+ assert bot.kind == "bot"+ assert accs["[email protected]"].owned_changing_files == 2+++# ---------------------------------------------------------------------------+# Summary+# ---------------------------------------------------------------------------+++def test_summary_is_people_only() -> None:+ resolve, accs = _fold()+ summary = build_owner_summary(ROWS, resolve, accs)++ assert summary["truck_factor"] == build_people(ROWS, COMMITS)["truck_factor"] == 2+ assert (summary["people"], summary["automation_identities"]) == (3, 1)+ assert (summary["owned_files"], summary["tracked_files"]) == (6, 8)+ assert summary["single_owner_files"] == 5+ assert summary["single_owner_hotspots"] == 2++ concentration = summary["concentration"]+ # The bot's two files are in neither the numerator nor the denominator.+ assert concentration["share"] == 1.0+ assert [o["key"] for o in concentration["owners"]] == [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]+ assert concentration["owners"][0]["share"] == 0.5+ assert [s["module"] for s in summary["silo_modules"]] == ["core", "lib", "tools"]+ assert summary["silo_modules"][0]["owner"] == {"key": "[email protected]", "name": "Ada Lovelace"}+++def test_summary_activity_and_quiet_owners() -> None:+ resolve, accs = _fold()+ summary = build_owner_summary(ROWS, resolve, accs)+ assert summary["activity_complete"] is True+ # Ada and Cy committed in the window; the bot is not a person.+ assert summary["active_contributors"] == 2+ # Bob's last commit is 200 days old and he owns two files that still change.+ assert summary["quiet_owners_total"] == 1+ quiet = summary["quiet_owners"][0]+ assert (quiet["key"], quiet["changing_files_owned"], quiet["files_owned"]) == (+ "[email protected]",+ 2,+ 2,+ )+++def test_summary_without_commit_rows_names_nobody_quiet() -> None:+ resolve = people_resolver(ROWS)+ accs, _ = aggregate_owners(ROWS, [], resolve=resolve)+ summary = build_owner_summary(ROWS, resolve, accs)+ assert summary["activity_complete"] is False+ assert summary["active_contributors"] == 0+ assert summary["quiet_owners"] == []+++# ---------------------------------------------------------------------------+# Knowledge matrix+# ---------------------------------------------------------------------------+++def test_file_author_shares_merge_people_and_drop_automation() -> None:+ resolve = people_resolver(ROWS, COMMITS)+ # 10 of core/a.py's 20 commits are the bot's: Ada holds 8 of the 10 human ones.+ assert file_author_shares(ROWS[0], resolve) == [+ ("[email protected]", 0.8),+ ("[email protected]", 0.2),+ ]+ # Ada's two addresses are one author holding the whole file.+ assert file_author_shares(ROWS[1], resolve) == [("[email protected]", 1.0)]+ assert file_author_shares(ROWS[6], resolve) == []+ assert person_owner(ROWS[1], resolve) == "[email protected]"+ assert person_owner(ROWS[6], resolve) is None+++def test_file_author_shares_keep_the_top_n() -> None:+ people = [(f"Person {i}", f"p{i}@example.com") for i in range(7)]+ row = _row("x.py", people[0], [_author(p, 10 - i) for i, p in enumerate(people)])+ shares = file_author_shares(row, people_resolver([row]), top=5)+ assert [k for k, _ in shares] == [f"p{i}@example.com" for i in range(5)]+ assert round(sum(s for _, s in shares), 6) == round(40 / 49, 6)+++def test_knowledge_matrix_rows_are_positional_and_indexed() -> None:+ resolve, accs = _fold()+ matrix = build_knowledge_matrix(+ ROWS, resolve, accs, {"core/a.py": (6.234, 120), "lib/x.py": (None, 40)}+ )+ authors = [a["key"] for a in matrix["authors"]]+ # Indexed by how many files each person appears on, most first.+ assert matrix["authors"][0]["active"] is True+ assert matrix["authors"][1]["active"] is False++ files = {+ (matrix["dirs"][row[0]] + "/" if matrix["dirs"][row[0]] else "") + row[1]: row+ 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["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, [])+++def test_an_email_only_owner_owns_files_on_every_surface() -> None:+ rows = [_row("a.py", ("", "[email protected]"), [_author(("", "[email protected]"), 3)])]+ resolve = people_resolver(rows)+ accs, _ = aggregate_owners(rows, [], resolve=resolve)+ assert accs["[email protected]"].files_owned == 1+ assert dict(owned_files(rows, resolve).by_owner) == {"[email protected]": 1}+ assert person_owner(rows[0], resolve) == "[email protected]"+++def test_a_file_without_history_is_not_a_single_owner_risk() -> None:+ rows = [*ROWS, _row("core/new.py", _ADA, [], bus_factor=0)]+ resolve = people_resolver(rows, COMMITS)+ accs, _ = aggregate_owners(rows, [], COMMITS, len(COMMITS), resolve)+ ada = accs["[email protected]"]+ # a.py and b.py have bus factor 1; c.py has 2 and new.py has none indexed.+ assert (ada.files_owned, ada.bus_factor_risk_files) == (4, 2)+ assert build_owner_summary(rows, resolve, accs)["single_owner_files"] == 5+++def test_automation_and_unowned_files_are_not_single_owner_risks() -> None:+ rows = [+ *ROWS,+ _row("deps/hot.py", _BOT, [_author(_BOT, 30)], hotspot=True),+ _row("gen/out.py", ("", ""), [], hotspot=True),+ ]+ resolve = people_resolver(rows, COMMITS)+ accs, _ = aggregate_owners(rows, [], COMMITS, len(COMMITS), resolve)+ owned = owned_files(rows, resolve)+ assert (owned.single_owner_files, owned.single_owner_hotspots) == (5, 2)+ summary = build_owner_summary(rows, resolve, accs)+ assert (summary["single_owner_files"], summary["single_owner_hotspots"]) == (5, 2)diff --git a/tests/unit/server/golden/ownership_rollups.json b/tests/unit/server/golden/ownership_rollups.jsonindex 9ed01bb2d..e051d513d 100644--- a/tests/unit/server/golden/ownership_rollups.json+++ b/tests/unit/server/golden/ownership_rollups.json@@ -5,6 +5,7 @@"key": "[email protected]","name": "Alice","email": "[email protected]",+ "kind": "human","files_owned": 2,"hotspots_owned": 1,"silo_modules": 0,@@ -19,6 +20,7 @@"key": "[email protected]","name": "Bob Stone","email": "[email protected]",+ "kind": "human","files_owned": 2,"hotspots_owned": 1,"silo_modules": 0,@@ -33,6 +35,7 @@"key": "name:Carol","name": "Carol","email": null,+ "kind": "human","files_owned": 1,"hotspots_owned": 0,"silo_modules": 0,@@ -54,6 +57,7 @@"key": "[email protected]","name": "Alice","email": "[email protected]",+ "kind": "human","files_owned": 2,"hotspots_owned": 1,"silo_modules": 0,@@ -68,6 +72,7 @@"key": "[email protected]","name": "Bob Stone","email": "[email protected]",+ "kind": "human","files_owned": 2,"hotspots_owned": 1,"silo_modules": 0,@@ -82,6 +87,7 @@"key": "name:Carol","name": "Carol","email": null,+ "kind": "human","files_owned": 1,"hotspots_owned": 0,"silo_modules": 0,@@ -102,6 +108,15 @@"key": "[email protected]","name": "Alice","email": "[email protected]",+ "kind": "human",+ "aliases": {+ "names": [+ "Alice"+ ],+ "emails": [+ ]+ },"files_owned": 2,"hotspots_owned": 1,"silo_modules": 0,@@ -182,6 +197,16 @@"key": "[email protected]","name": "Bob Stone","email": "[email protected]",+ "kind": "human",+ "aliases": {+ "names": [+ "Bob Stone"+ ],+ "emails": [+ "[email protected]",+ ]+ },"files_owned": 2,"hotspots_owned": 1,"silo_modules": 0,@@ -262,6 +287,13 @@"key": "name:Carol","name": "Carol","email": null,+ "kind": "human",+ "aliases": {+ "names": [+ "Carol"+ ],+ "emails": []+ },"files_owned": 1,"hotspots_owned": 0,"silo_modules": 0,diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.pyindex 98fb2fd4a..92f3f21e3 100644--- a/tests/unit/server/test_owners.py+++ b/tests/unit/server/test_owners.py@@ -280,3 +280,76 @@ async def test_commits_90d_counts_the_owners_own_commits(client: AsyncClient, apassert by_name["Alice"]["commit_count_90d"] == 2assert by_name["Bob"]["commit_count_90d"] == 0assert by_name["Bob"]["last_commit_at"].startswith("2024-03-01")+++async def test_list_and_profile_carry_kind_and_merged_identities(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ items = (await client.get(f"/api/repos/{repo['id']}/owners")).json()["items"]+ assert {i["kind"] for i in items} == {"human"}++ key = quote("[email protected]", safe="")+ data = (await client.get(f"/api/repos/{repo['id']}/owners/{key}")).json()+ assert data["kind"] == "human"+ assert data["aliases"] == {"names": ["Alice"], "emails": ["[email protected]"]}+++async def test_owners_summary(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/owners/summary")+ assert resp.status_code == 200+ data = resp.json()+ # Alice and Bob own one file each: it takes both to pass half.+ assert data["truck_factor"] == 2+ assert (data["owned_files"], data["tracked_files"]) == (2, 2)+ assert (data["single_owner_files"], data["single_owner_hotspots"]) == (1, 1)+ assert data["concentration"]["share"] == 1.0+ # Two people split src evenly, so it is no silo.+ assert data["silo_modules"] == []+ assert data["activity_complete"] is False+ assert data["quiet_owners"] == []+++async def test_knowledge_matrix(client: AsyncClient, app) -> None:+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ resp = await client.get(f"/api/repos/{repo['id']}/owners/knowledge-matrix")+ assert resp.status_code == 200+ data = resp.json()+ assert data["dirs"] == ["src"]+ keys = [a["key"] for a in data["authors"]]+ assert sorted(keys) == ["[email protected]", "[email protected]"]+ 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]]]+++async def test_owner_fold_is_built_once_per_index_state(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ from repowise.server.services import owner_profile++ calls = []+ real = owner_profile._load_owner_data++ async def counting(session, repo_id):+ calls.append(repo_id)+ return await real(session, repo_id)++ monkeypatch.setattr(owner_profile, "_load_owner_data", counting)+ repo = await create_test_repo(client)+ await _seed(app.state.session_factory, repo["id"])++ base = f"/api/repos/{repo['id']}/owners"+ for url in (base, f"{base}/summary", f"{base}/knowledge-matrix", base):+ assert (await client.get(url)).status_code == 200+ assert calls == [repo["id"]]