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(components): compare declared owners with recent activity per component (#3781)
Raghav Chamadiya966702b7b2d7
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex eda64bfb9..080b4c064 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -168,7 +168,7 @@ A triage card for files, modules or symbols: summary, symbols with signatures an**Key return fields:** `targets` keyed by target, each with title, summary, symbols, `hotspot`, `fix_history` (files with counted bug fixes), `episodes`, decision titles, `file_preview` (for files with no symbols), `resolved_to` (a symbol miss falling back to its file); `dropped_targets` and `recovery` when the budget forced targets out; `_meta.complete` for whole files served.-A `component:<name>` target returns the component's declared context (owner, system, criticality, tags) and `facts` rolled up over its files: health, hotspots, bus factor, test reach and dead code, each with a `basis` (`measured`, `inferred` or `unavailable`). Components come from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or are derived from the index. `include` does not apply to component targets; health and dead code leave out files in gated languages and say how many.+A `component:<name>` target returns the component's declared context (owner, system, criticality, tags) and `facts` rolled up over its files: health, hotspots, bus factor, test reach and dead code, each with a `basis` (`measured`, `inferred` or `unavailable`). Components come from [`.repowise/components.yaml`](../reference/CONFIG.md#repowisecomponentsyaml) or are derived from the index. With `include=["ownership"]` a component card adds `ownership`: declared teams with their activity over the last 90 days, a count of individual owners, and findings (`critical_no_active_owner`, `declared_owner_inactive`, `critical_bus_factor_one`, `catalog_entry_no_code`). An owner with no identity in the indexed history is `unknown` and raises no finding, so `critical_no_active_owner` does not fire when every owner is unknown; individuals match only by exact git email or forge noreply login. No other `include` applies to component targets. Health and dead code leave out files in gated languages and say how many.A `change:<id>` target (`change:pr-123`, or a commit sha the change landed) returns the [Change Record](../reference/CLI_REFERENCE.md#repowise-changes): title, forge ref, `merged_at`, category, files and provenance with its coverage. On a file target, `changes` lists the newest Change Records that touched it, and `provenance` gives the file's commits by source (agent, human-attested, unknown) with coverage; the agent share is withheld below 30% coverage. With attribution off, `provenance` reads `{"unavailable": "attribution_off"}` and change rows carry none.diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex f94179a6c..b3702eee9 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -1584,11 +1584,12 @@ repowise coverage suggest-gates --format json### `repowise components`-`check` validates `.repowise/components.yaml` and a repo-root `catalog-info.yaml` (Backstage entities, see [CONFIG.md](CONFIG.md#repowisecomponentsyaml)) against the files git tracks, and exits 1 on any error, so it fits a CI step. `list` shows declared and derived components with their file counts.+`check` validates `.repowise/components.yaml` and a repo-root `catalog-info.yaml` (Backstage entities, see [CONFIG.md](CONFIG.md#repowisecomponentsyaml)) against the files git tracks, and exits 1 on any error, so it fits a CI step. `list` shows declared and derived components with their file counts. `ownership` compares each component's declared owners (catalog `spec.owner`, CODEOWNERS, [`.repowise/teams.yaml`](CONFIG.md#repowiseteamsyaml)) with indexed commits in the last 90 days and lists findings: a high or critical component with no active declared owner or a bus factor of 1, a declared owner with no recent changes, and a catalog entry that claims no files. An owner none of whose identities appears in the indexed history is unknown, never inactive, so `critical_no_active_owner` does not fire when every declared owner is unknown. Individuals match only through an exact git email or a forge noreply login, and a bare `@name` outside `.github/CODEOWNERS` that names no declared team stays unresolved (on GitLab it may be a group). Findings name components and teams; individual owners are counted, never named.```bashrepowise components check [--path PATH] [--format table|json]repowise components list [--path PATH] [--format table|json]+repowise components ownership [--path PATH] [--format table|json]```---diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex a18207ad3..f580e9788 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -594,6 +594,23 @@ rules:Conditions are `attribution`, `agent_tier` (1, 2 or 3), `reaching_tests` (`missing` or `present`), `contract_break`, `decision_crossed` and `bus_factor_below`; there is no risk-score condition. A condition whose evidence is not available (no index, attribution off) leaves the rule not evaluated, and it never fires. Exit 2 (`policy_invalid`, every problem listed) on an unknown key, condition or gate option, a bad action, or a duplicate rule name.+### `.repowise/teams.yaml`++Declared teams with the members who count as the team's activity, for `repowise components ownership` and `get_context(include=["ownership"])` on a component. Each team is a Backstage `Group` whose `spec.members` lists forge logins and whose `repowise.dev/member-emails` annotation lists git author emails; members are used only for matching commits and never appear in output. A CODEOWNERS `@org/team` (GitHub or GitLab, sections included) and a catalog `spec.owner` of `group:default/team` both resolve to the Group named `team`. Group entities in the catalog files add team names; their `spec.members` is not read.++```yaml+apiVersion: backstage.io/v1alpha1+kind: Group+metadata:+ name: payments+ annotations:+ repowise.dev/member-emails: "[email protected], [email protected]"+spec:+ type: team+ children: []+ members: [ana-acme, li-acme]+```+### The `security:` blockSecret shapes of your own for `repowise security check`.diff --git a/packages/cli/src/repowise/cli/commands/components_cmd.py b/packages/cli/src/repowise/cli/commands/components_cmd.pyindex d922ffea6..fd670b404 100644--- a/packages/cli/src/repowise/cli/commands/components_cmd.py+++ b/packages/cli/src/repowise/cli/commands/components_cmd.py@@ -4,6 +4,8 @@validates them against the files git tracks; it needs no index and exitsnon-zero on any error, so it fits a CI step. ``list`` shows declared andderived components with their file counts, from the index when there is one.+``ownership`` compares declared owners (catalog, CODEOWNERS, teams.yaml) with+recent commit activity per component and lists the findings."""from __future__ import annotations@@ -160,3 +162,70 @@ def components_list(repo: str | None, fmt: str) -> None:console.print("[dim]No index found: derived components are top-level directories.[/dim]")if data["catalog"].errors:console.print("[yellow]The catalog has errors; run `repowise components check`.[/yellow]")+++async def _ownership(root: Path) -> dict[str, Any]:+ from repowise.core.components.ownership import Activity, assess_component+ from repowise.core.components.store import (+ component_ownership,+ component_rollups,+ load_repo_components,+ workspace_services,+ )+ from repowise.core.ownership.directory import team_directories++ async with repo_index_session(root) as opened:+ if opened is not None:+ session, repo_id = opened+ found = await load_repo_components(+ session, repo_id, root, services=workspace_services(root)+ )+ files = found.resolved.files+ rollups = await component_rollups(+ session, repo_id, {n: p for n, p in files.items() if p}, found.test_files+ )+ comps = [(c, files[c.name]) for c in found.resolved.components]+ blocks, issues = await component_ownership(+ session, repo_id, root, comps, {n: r["bus_factor"] for n, r in rollups.items()}+ )+ return {"indexed": True, "components": comps, "blocks": blocks, "issues": issues}+ data = await _list(root)+ declared = team_directories.get().load(root)+ resolved = data["resolved"]+ comps = [(c, resolved.files[c.name]) for c in resolved.components]+ blocks = {c.name: assess_component(c, p, declared, Activity()) for c, p in comps}+ return {"indexed": False, "components": comps, "blocks": blocks, "issues": declared.issues}+++@components_group.command("ownership")[email protected]("--path", "repo", default=None, help="Repo path (defaults to cwd).")+@format_option()+def components_ownership(repo: str | None, fmt: str) -> None:+ """Compare declared owners with recent activity per component."""+ root = _repo_root(repo)+ data = run_async(_ownership(root))+ blocks = data["blocks"]+ if fmt == "json":+ out = {+ "indexed": data["indexed"],+ "components": [{"name": c.name, **blocks[c.name]} for c, _ in data["components"]],+ }+ if data["issues"]:+ out["directory_issues"] = data["issues"]+ emit_json(out)+ return+ from rich.markup import escape++ for issue in data["issues"]:+ console.print(f"[yellow]warning[/yellow] {escape(issue)}")++ findings = [(c.name, f) for c, _ in data["components"] for f in blocks[c.name]["findings"]]+ for name, f in findings:+ console.print(f"[yellow]{f['kind']}[/yellow] {escape(name)}: {escape(f['message'])}")+ if not findings:+ console.print("[green]No ownership findings.[/green]")+ if not data["indexed"]:+ console.print(+ "[dim]No index found: recent activity is unknown, "+ "so only declared facts are checked.[/dim]"+ )diff --git a/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.pyindex 7e7195fb9..97370339c 100644--- a/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_suggest_gates_cmd.py@@ -61,19 +61,15 @@ def coverage_suggest_gates(repo: str | None, fmt: str) -> None:def _codeowners(root: Path):- from repowise.core.analysis.patch_coverage.suggest import (- CODEOWNERS_PATHS,- GateSource,- codeowners_gates,- )-- for rel in CODEOWNERS_PATHS:- path = root / rel- if path.is_file():- gates = codeowners_gates(path.read_text(encoding="utf-8", errors="replace"))- detail = rel if gates else f"{rel} names no owned paths"- return GateSource("codeowners", detail, gates)- return GateSource("codeowners", "no CODEOWNERS file")+ from repowise.core.analysis.patch_coverage.suggest import GateSource, codeowners_gates+ from repowise.core.ownership.codeowners import read_codeowners++ found = read_codeowners(root)+ if found is None:+ return GateSource("codeowners", "no CODEOWNERS file")+ rel, text = found+ gates = codeowners_gates(text)+ return GateSource("codeowners", rel if gates else f"{rel} names no owned paths", gates)def _layout(root: Path):diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/suggest.py b/packages/core/src/repowise/core/analysis/patch_coverage/suggest.pyindex 0d26319d9..e76d46926 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/suggest.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/suggest.py@@ -12,16 +12,14 @@ import jsonimport posixpathimport refrom collections import defaultdict-from collections.abc import Iterable, Iterator, Mapping, Sequence+from collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass, fieldfrom pathlib import PurePosixPathfrom ...ingestion.languages.registry import REGISTRY+from ...ownership.codeowners import parse_codeownersfrom ...test_paths import is_test_related_path-#: Where GitHub and GitLab look for CODEOWNERS; the first found is read.-CODEOWNERS_PATHS = (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS", ".gitlab/CODEOWNERS")-#: Directories whose children are a monorepo's packages.MONOREPO_ROOTS = ("packages", "apps", "services", "libs")@@ -36,12 +34,6 @@ _CATCH_ALL = frozenset({"*", "**", "/**", "/*"})_SOURCE_SUFFIXES = REGISTRY.non_infra_code_extensions()-# A ``#`` at the start of a line or after whitespace (space or tab) opens a comment.-_COMMENT = re.compile(r"(?:^|\s)#.*$")-# Fields split on whitespace a backslash does not escape (``docs/my\ file.md``).-_FIELDS = re.compile(r"(?<!\\)\s+")-# A GitLab section header, ``[Name]`` or ``^[Name][2]``, with optional default owners.-_SECTION = re.compile(r"^\^?\[[^\]]+\](?:\[\d+\])?(?:\s+(.*))?$")_GLOB_CHARS = re.compile(r"[*?\[]")@@ -83,7 +75,8 @@ def codeowners_gates(text: str) -> list[SuggestedGate]:``[Section] @owners`` header, owner-less lines take the section's owners."""paths: dict[str, list[str]] = {}- for pattern, owners in _codeowners_rules(text):+ for rule in parse_codeowners(text):+ pattern, owners = rule.pattern, rule.ownersif pattern in _CATCH_ALL:paths.clear()continue@@ -99,20 +92,6 @@ def codeowners_gates(text: str) -> list[SuggestedGate]:]-def _codeowners_rules(text: str) -> Iterator[tuple[str, list[str]]]:- """``(pattern, owners)`` per rule line; owner-less lines take a GitLab section's owners."""- defaults: list[str] = []- for raw in text.splitlines():- line = _COMMENT.sub("", raw).strip()- if not line:- continue- if section := _SECTION.match(line):- defaults = _FIELDS.split(section.group(1)) if section.group(1) else []- continue- pattern, *owners = _FIELDS.split(line)- yield pattern, owners or defaults--def layout_gates(tracked: Iterable[str]) -> list[SuggestedGate]:"""One gate per package of a monorepo, else per top-level source directory.diff --git a/packages/core/src/repowise/core/components/ownership.py b/packages/core/src/repowise/core/components/ownership.pynew file mode 100644index 000000000..69a97cc8e--- /dev/null+++ b/packages/core/src/repowise/core/components/ownership.py@@ -0,0 +1,235 @@+"""Declared against observed ownership, per component.++Declared owners come from the :mod:`team-directory <repowise.core.ownership.directory>`+seam: the component's catalog ``spec.owner`` (all its files) and the+CODEOWNERS owners of its files (the files each one is assigned). Observed+activity is the indexed commits by people (automation left out) in the+:data:`ACTIVITY_WINDOW_DAYS` before the newest indexed commit.++A declared owner is active when someone it covers changed one of the files it+owns in that window. A team is matched through the members ``teams.yaml``+(or a plugin directory) declares; an individual through a git email, or a+login seen on a forge noreply address. An owner none of whose identities+appears anywhere in the indexed history is ``unknown``, never inactive.++Findings are about components and teams only. An individual owner is counted,+never named.+"""++from __future__ import annotations++from collections.abc import Iterable+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any++from repowise.core import forges+from repowise.core.analysis.owners import ACTIVITY_WINDOW_DAYS+from repowise.core.author_identity import IdentityResolver, build_identity_resolver+from repowise.core.components.catalog import Component+from repowise.core.ownership.directory import DeclaredOwnership, OwnerRef++#: Criticality levels the critical-component findings apply to.+CRITICAL_LEVELS = frozenset({"high", "critical"})+++@dataclass+class Activity:+ """Who changed which file recently, as identity keys. Built by :func:`build_activity`."""++ resolve: IdentityResolver | None = None+ #: Every human identity in the indexed history.+ known: set[str] = field(default_factory=set)+ #: Login (lower-cased) to the identities seen committing as its noreply address.+ login_keys: dict[str, set[str]] = field(default_factory=dict)+ #: File to the human identities that changed it in the window.+ recent: dict[str, set[str]] = field(default_factory=dict)+ #: File to the commits that changed it in the window.+ recent_commits: dict[str, set[str]] = field(default_factory=dict)+ as_of: datetime | None = None++ @property+ def available(self) -> bool:+ return self.resolve is not None++ def keys_of(self, ref: OwnerRef) -> set[str] | None:+ """The identities *ref* covers that history knows; ``None`` when none is known."""+ if self.resolve is None or ref.kind == "unresolved":+ return None+ if ref.kind == "team":+ team = ref.team+ tokens = [*team.logins, *team.emails] if team is not None else []+ else:+ tokens = [ref.name]+ keys: set[str] = set()+ for token in tokens:+ if "@" in token:+ key = self.resolve(None, token)+ if key in self.known:+ keys.add(key)+ else:+ keys |= self.login_keys.get(token, set())+ return keys or None+++def build_activity(+ authors: Iterable[tuple[str | None, str | None]],+ recent_rows: Iterable[tuple[str, str, str | None, str | None]],+ as_of: datetime | None,+) -> Activity:+ """*authors*: every commit's ``(name, email)``; *recent_rows*: ``(file, sha,+ name, email)`` for each file a commit in the window changed."""+ pairs = list(authors)+ if not pairs:+ return Activity()+ resolve = build_identity_resolver(pairs)+ activity = Activity(resolve=resolve, as_of=as_of)+ for name, email in pairs:+ key = resolve(name, email)+ if resolve.is_bot(key) or not key:+ continue+ activity.known.add(key)+ login = forges.noreply_login(email)+ if login:+ activity.login_keys.setdefault(login[1].lower(), set()).add(key)+ for path, sha, name, email in recent_rows:+ key = resolve(name, email)+ if key in activity.known:+ activity.recent.setdefault(path, set()).add(key)+ activity.recent_commits.setdefault(path, set()).add(sha)+ return activity+++def assess_component(+ comp: Component,+ files: list[str],+ declared: DeclaredOwnership,+ activity: Activity,+ bus_factor: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """The ``ownership`` block for one component: declared owners, recent+ activity and findings."""+ findings: list[dict[str, str]] = []+ critical = comp.criticality in CRITICAL_LEVELS+ out: dict[str, Any] = {"file_count": len(files)}+ if not files:+ if comp.declared:+ findings.append(+ _finding("catalog_entry_no_code", "Declared in the catalog; claims no files.")+ )+ out["findings"] = findings+ return out++ owned = _declared_files(comp, files, declared)+ teams: list[dict[str, Any]] = []+ individuals = {"count": 0, "no_recent_changes": 0, "unknown": 0}+ unresolved = 0+ states: list[str] = []+ for ref, paths in owned.items():+ state = _activity_state(ref, paths, activity)+ states.append(state)+ if ref.kind == "team":+ row: dict[str, Any] = {"team": ref.name, "files": len(paths), "activity": state}+ if ref.team is None:+ row["in_directory"] = False # no Group or teams.yaml entry by this name+ teams.append(row)+ if state == "no_recent_changes":+ findings.append(+ _finding(+ "declared_owner_inactive",+ f"Declared owner team {ref.name!r} has no changes to its "+ f"{len(paths)} file(s) here in the last {ACTIVITY_WINDOW_DAYS} days.",+ )+ )+ elif ref.kind == "unresolved":+ unresolved += 1+ else:+ individuals["count"] += 1+ if state in ("no_recent_changes", "unknown"):+ individuals[state] += 1+ if individuals["no_recent_changes"]:+ findings.append(+ _finding(+ "declared_owner_inactive",+ f"{individuals['no_recent_changes']} declared individual owner(s) have no "+ f"changes here in the last {ACTIVITY_WINDOW_DAYS} days.",+ )+ )++ covered = {p for paths in owned.values() for p in paths}+ out["files_with_declared_owner"] = len(covered)+ if teams:+ out["declared_teams"] = sorted(teams, key=lambda t: (-t["files"], t["team"]))+ if individuals["count"]:+ out["declared_individuals"] = individuals+ if unresolved:+ # Bare handles that may be a person or a group: counted, never named.+ out["declared_unresolved"] = unresolved+ if activity.available:+ out["recent"] = {+ "commits": len({s for p in files for s in activity.recent_commits.get(p, ())}),+ "contributors": len({k for p in files for k in activity.recent.get(p, ())}),+ "window_days": ACTIVITY_WINDOW_DAYS,+ }+ if activity.as_of is not None:+ out["recent"]["as_of"] = activity.as_of.date().isoformat()++ if critical:+ if not owned:+ findings.append(+ _finding(+ "critical_no_active_owner",+ f"Criticality {comp.criticality}, and no team or person is declared as owner.",+ )+ )+ elif states and all(s == "no_recent_changes" for s in states):+ findings.append(+ _finding(+ "critical_no_active_owner",+ f"Criticality {comp.criticality}, and no declared owner changed it in the "+ f"last {ACTIVITY_WINDOW_DAYS} days.",+ )+ )+ if bus_factor and bus_factor.get("basis") == "measured" and bus_factor.get("value") == 1:+ findings.append(+ _finding(+ "critical_bus_factor_one",+ f"Criticality {comp.criticality}, and one person is the primary owner of "+ "over half of its owned files.",+ )+ )+ out["findings"] = findings+ out["basis"] = "measured" if activity.available else "unavailable"+ out["method"] = (+ "declared owners from the catalog spec.owner and CODEOWNERS; activity from indexed "+ f"commits in the {ACTIVITY_WINDOW_DAYS} days before the newest one, matched through "+ "declared team members, git emails and forge noreply logins"+ )+ return out+++def _declared_files(+ comp: Component, files: list[str], declared: DeclaredOwnership+) -> dict[OwnerRef, list[str]]:+ """Each declared owner of the component and the files it is declared for."""+ owned: dict[OwnerRef, dict[str, None]] = {}+ if comp.owner:+ owned[declared.from_backstage(comp.owner)] = dict.fromkeys(files)+ if declared.rules:+ for path in files:+ for owner in declared.codeowners_of(path):+ owned.setdefault(declared.from_codeowners(owner), {})[path] = None+ return {ref: list(paths) for ref, paths in owned.items()}+++def _activity_state(ref: OwnerRef, paths: list[str], activity: Activity) -> str:+ keys = activity.keys_of(ref)+ if keys is None:+ return "unknown"+ if any(keys & activity.recent.get(p, set()) for p in paths):+ return "active"+ return "no_recent_changes"+++def _finding(kind: str, message: str) -> dict[str, str]:+ return {"kind": kind, "message": message}diff --git a/packages/core/src/repowise/core/components/store.py b/packages/core/src/repowise/core/components/store.pyindex 85e5e8e74..eddba8039 100644--- a/packages/core/src/repowise/core/components/store.py+++ b/packages/core/src/repowise/core/components/store.py@@ -8,10 +8,11 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any-from sqlalchemy import select+from sqlalchemy import func, selectfrom repowise.core.analysis.finding_registry import excluded_types-from repowise.core.components.catalog import Catalog, read_catalog+from repowise.core.components.catalog import Catalog, Component, read_catalog+from repowise.core.components.ownership import Activity, assess_component, build_activityfrom repowise.core.components.resolve import (ResolvedComponents,derive_from_directories,@@ -24,6 +25,8 @@ from repowise.core.persistence.crud import code_file_rowsfrom repowise.core.persistence.crud.repository import ANALYSIS_RAN_KEYfrom repowise.core.persistence.models import (DeadCodeFinding,+ GitCommit,+ GitCommitFile,GitMetadata,GraphNode,HealthFileMetric,@@ -211,3 +214,68 @@ async def component_rollups()for name, paths in files_by_component.items()}+++async def load_activity(session: Any, repository_id: str, files: list[str]) -> Activity:+ """Recent commit activity on *files*, and every author the index knows."""+ from datetime import timedelta++ from repowise.core.analysis.owners import ACTIVITY_WINDOW_DAYS, as_utc++ authors = (+ await session.execute(+ select(GitCommit.author_name, GitCommit.author_email, func.count()).where(+ GitCommit.repository_id == repository_id+ ).group_by(GitCommit.author_name, GitCommit.author_email)+ )+ ).all()+ # The bound keeps the stored value's form (naive on SQLite), as other window reads do.+ newest = await session.scalar(+ select(func.max(GitCommit.committed_at)).where(GitCommit.repository_id == repository_id)+ )+ recent: list[Any] = []+ if newest is not None and files:+ query = (+ select(+ GitCommitFile.file_path,+ GitCommit.sha,+ GitCommit.author_name,+ GitCommit.author_email,+ )+ .join(+ GitCommit,+ (GitCommit.repository_id == GitCommitFile.repository_id)+ & (GitCommit.sha == GitCommitFile.sha),+ )+ .where(+ GitCommitFile.repository_id == repository_id,+ GitCommit.committed_at >= newest - timedelta(days=ACTIVITY_WINDOW_DAYS),+ )+ )+ recent = await _rows_for(session, query, GitCommitFile.file_path, files)+ # One pair per commit, so the resolver's counts match every other people figure.+ pairs = [(name, email) for name, email, n in authors for _ in range(n)]+ return build_activity(pairs, [tuple(r) for r in recent], as_utc(newest))+++async def component_ownership(+ session: Any,+ repository_id: str,+ repo_root: Path | str,+ components: list[tuple[Component, list[str]]],+ bus_factors: dict[str, dict[str, Any]] | None = None,+) -> tuple[dict[str, dict[str, Any]], list[str]]:+ """The ``ownership`` block per component name (see :mod:`.ownership`), and+ the team directory's read problems."""+ from repowise.core.ownership.directory import team_directories++ declared = team_directories.get().load(Path(repo_root))+ files = sorted({f for _c, paths in components for f in paths})+ activity = await load_activity(session, repository_id, files)+ out = {+ comp.name: assess_component(+ comp, paths, declared, activity, (bus_factors or {}).get(comp.name)+ )+ for comp, paths in components+ }+ return out, list(declared.issues)diff --git a/packages/core/src/repowise/core/ownership/__init__.py b/packages/core/src/repowise/core/ownership/__init__.pynew file mode 100644index 000000000..6511ee57d--- /dev/null+++ b/packages/core/src/repowise/core/ownership/__init__.py@@ -0,0 +1,2 @@+"""Declared ownership inputs: CODEOWNERS (:mod:`.codeowners`) and the+``team-directory`` seam with its local file-based default (:mod:`.directory`)."""diff --git a/packages/core/src/repowise/core/ownership/codeowners.py b/packages/core/src/repowise/core/ownership/codeowners.pynew file mode 100644index 000000000..fc96a5489--- /dev/null+++ b/packages/core/src/repowise/core/ownership/codeowners.py@@ -0,0 +1,102 @@+"""CODEOWNERS parsing and matching, shared by every reader of the file.++GitHub reads ``.github/``, the repository root and ``docs/``; GitLab reads the+root, ``docs/`` and ``.gitlab/``. The first file found is the one in force.++GitHub gives a file to the last pattern matching it. GitLab adds sections:+``[Name]``, optionally ``^[Name]`` (optional approval) and ``[Name][2]``+(approval count), each with optional default owners that owner-less lines in+the section take. Each section picks its own last match and a file's owners+are the union across sections; sections with the same name (any case) are+one section. Rules before the first header form the default section.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass+from pathlib import Path++import pathspec+from pathspec.patterns.gitwildmatch import GitWildMatchPatternError++#: Where GitHub and GitLab look for CODEOWNERS; the first found is read.+CODEOWNERS_PATHS = (".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS", ".gitlab/CODEOWNERS")++# A ``#`` at the start of a line or after whitespace (space or tab) opens a comment.+_COMMENT = re.compile(r"(?:^|\s)#.*$")+# Fields split on whitespace a backslash does not escape (``docs/my\ file.md``).+_FIELDS = re.compile(r"(?<!\\)\s+")+# A GitLab section header, ``[Name]`` or ``^[Name][2]``, with optional default owners.+_SECTION = re.compile(r"^\^?\[([^\]]+)\](?:\[\d+\])?(?:\s+(.*))?$")+++@dataclass(frozen=True)+class CodeownersRule:+ pattern: str+ #: The line's owners, or its GitLab section's default owners when it names none.+ owners: tuple[str, ...]+ #: The GitLab section, lower-cased; ``None`` for rules before any header.+ section: str | None = None+++def parse_codeowners(text: str) -> list[CodeownersRule]:+ """Every rule line in file order."""+ rules: list[CodeownersRule] = []+ section: str | None = None+ defaults: list[str] = []+ for raw in text.splitlines():+ line = _COMMENT.sub("", raw).strip()+ if not line:+ continue+ if header := _SECTION.match(line):+ section = header.group(1).strip().lower()+ defaults = _FIELDS.split(header.group(2)) if header.group(2) else []+ continue+ pattern, *owners = _FIELDS.split(line)+ rules.append(CodeownersRule(pattern, tuple(owners or defaults), section))+ return rules+++def read_codeowners(repo_root: Path | str) -> tuple[str, str] | None:+ """``(repo-relative path, text)`` of the CODEOWNERS file in force, else ``None``."""+ root = Path(repo_root)+ for rel in CODEOWNERS_PATHS:+ path = root / rel+ if path.is_file():+ try:+ return rel, path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return None+ return None+++class CodeownersMatcher:+ """Owners of a path under one parsed file; patterns compile once."""++ def __init__(self, rules: Iterable[CodeownersRule]):+ self._rules: list[tuple[pathspec.PathSpec, CodeownersRule]] = []+ for rule in rules:+ try:+ spec = pathspec.PathSpec.from_lines("gitwildmatch", [rule.pattern])+ except (GitWildMatchPatternError, ValueError):+ continue # a pattern git cannot read owns nothing+ self._rules.append((spec, rule))++ def owners(self, path: str) -> tuple[str, ...]:+ """Union of each section's last matching rule's owners, in first-seen order."""+ last: dict[str | None, CodeownersRule] = {}+ for spec, rule in self._rules:+ if spec.match_file(path):+ last[rule.section] = rule+ return tuple(dict.fromkeys(o for rule in last.values() for o in rule.owners))+++__all__ = [+ "CODEOWNERS_PATHS",+ "CodeownersMatcher",+ "CodeownersRule",+ "parse_codeowners",+ "read_codeowners",+]diff --git a/packages/core/src/repowise/core/ownership/directory.py b/packages/core/src/repowise/core/ownership/directory.pynew file mode 100644index 000000000..ed61b30df--- /dev/null+++ b/packages/core/src/repowise/core/ownership/directory.py@@ -0,0 +1,211 @@+"""Declared ownership: who a repository says owns what.++A :class:`TeamDirectory` returns :class:`DeclaredOwnership`: the CODEOWNERS+rules in force and the teams the repository declares. The local default,+``local``, reads only files in the repository:++* CODEOWNERS (:mod:`.codeowners`; GitHub and GitLab, sections included);+* Backstage Group entities in the component catalog files+ (``.repowise/components.yaml``, ``catalog-info.yaml``): names only, their+ ``spec.members`` is never read;+* ``.repowise/teams.yaml``: Backstage Group entities whose membership is+ read, only to tell whether a team changed a component recently. Members+ never appear in any output::++ apiVersion: backstage.io/v1alpha1+ kind: Group+ metadata:+ name: payments+ annotations:+ repowise.dev/member-emails: "[email protected], [email protected]"+ spec:+ type: team+ children: []+ members: [ana-acme, li-acme] # forge logins++A plugin registers another directory (SCIM, forge teams) under+``SeamRegistry("team-directory")``, selected with ``REPOWISE_SEAM_TEAM_DIRECTORY``.+"""++from __future__ import annotations++import re+from dataclasses import dataclass, field+from functools import cached_property+from pathlib import Path+from typing import Any, Protocol++import yaml++from repowise.core.ownership.codeowners import (+ CodeownersMatcher,+ CodeownersRule,+ parse_codeowners,+ read_codeowners,+)+from repowise.core.registry.plugins import SeamRegistry++TEAMS_FILE = ".repowise/teams.yaml"+MEMBER_EMAILS_ANNOTATION = "repowise.dev/member-emails"+_API_VERSION = "backstage.io/v1alpha1"+_MAX_TEAMS_BYTES = 1_000_000+++@dataclass(frozen=True)+class Team:+ name: str+ #: Forge logins and git author emails, lower-cased. Used to match commits+ #: to the team; never output.+ logins: tuple[str, ...] = ()+ emails: tuple[str, ...] = ()++ @property+ def has_members(self) -> bool:+ return bool(self.logins or self.emails)+++@dataclass(frozen=True)+class OwnerRef:+ """A declared owner: a team, or an individual (a login or an email)."""++ #: "unresolved" is a bare ``@name`` that may be a person or a GitLab group.+ kind: str # "team" | "individual" | "unresolved"+ #: The team name, or the individual's login or email (lower-cased).+ name: str+ team: Team | None = None+++@dataclass+class DeclaredOwnership:+ teams: dict[str, Team] = field(default_factory=dict) # by lower-cased name+ codeowners_file: str | None = None+ rules: list[CodeownersRule] = field(default_factory=list)+ issues: list[str] = field(default_factory=list)++ @cached_property+ def _matcher(self) -> CodeownersMatcher:+ return CodeownersMatcher(self.rules)++ def codeowners_of(self, path: str) -> tuple[str, ...]:+ return self._matcher.owners(path)++ def from_codeowners(self, owner: str) -> OwnerRef:+ """``@org/team`` is a team (named by its last segment) and an email an+ individual. A bare ``@name`` is a declared team of that name, else an+ individual in ``.github/CODEOWNERS`` (GitHub has no bare team handles),+ else unresolved: on GitLab it may name a group."""+ token = owner.strip()+ if not token.startswith("@"):+ return OwnerRef("individual", token.lower())+ handle = token[1:]+ if "/" in handle:+ return self._team(handle.rsplit("/", 1)[-1])+ team = self.teams.get(handle.lower())+ if team is not None:+ return OwnerRef("team", team.name, team)+ if self.codeowners_file == ".github/CODEOWNERS":+ return OwnerRef("individual", handle.lower())+ return OwnerRef("unresolved", handle.lower())++ def from_backstage(self, owner: str) -> OwnerRef:+ """A Backstage owner ref; without a kind it names a Group, as in Backstage."""+ kind, sep, rest = owner.strip().partition(":")+ ref = rest if sep else owner.strip()+ name = ref.rsplit("/", 1)[-1]+ if sep and kind.lower() == "user":+ return OwnerRef("individual", name.lower())+ return self._team(name)++ def _team(self, name: str) -> OwnerRef:+ team = self.teams.get(name.lower())+ return OwnerRef("team", team.name if team else name, team)+++class TeamDirectory(Protocol):+ def load(self, repo_root: Path) -> DeclaredOwnership:+ """Declared ownership for the repository at *repo_root*."""+ ...+++class LocalTeamDirectory:+ """CODEOWNERS, catalog Groups and ``.repowise/teams.yaml``; files only."""++ def load(self, repo_root: Path) -> DeclaredOwnership:+ from repowise.core.components.catalog import read_catalog++ out = DeclaredOwnership()+ found = read_codeowners(repo_root)+ if found is not None:+ out.codeowners_file, text = found+ out.rules = parse_codeowners(text)+ for group in read_catalog(repo_root).groups:+ out.teams.setdefault(group.name.lower(), Team(group.name))+ for team in _read_teams(Path(repo_root) / TEAMS_FILE, out.issues):+ out.teams[team.name.lower()] = team # membership comes from teams.yaml+ return out+++def _read_teams(path: Path, issues: list[str]) -> list[Team]:+ if not path.is_file():+ return []+ try:+ if path.stat().st_size > _MAX_TEAMS_BYTES:+ issues.append(f"{TEAMS_FILE}: larger than {_MAX_TEAMS_BYTES} bytes; not read")+ return []+ docs = [d for d in yaml.safe_load_all(path.read_text(encoding="utf-8")) if d is not None]+ except yaml.YAMLError as exc:+ # A fixed message: PyYAML quotes the source, which holds member emails.+ mark = getattr(exc, "problem_mark", None)+ where = f" near line {mark.line + 1}" if mark is not None else ""+ issues.append(f"{TEAMS_FILE}: invalid YAML{where}; not read")+ return []+ except (OSError, UnicodeDecodeError):+ issues.append(f"{TEAMS_FILE}: cannot be read as UTF-8 text; not read")+ return []+ teams: list[Team] = []+ for doc in docs:+ team = _team_entity(doc)+ if team is None:+ issues.append(f"{TEAMS_FILE}: a document is not a {_API_VERSION} Group with a name")+ else:+ teams.append(team)+ return teams+++def _team_entity(doc: Any) -> Team | None:+ if not isinstance(doc, dict) or doc.get("kind") != "Group":+ return None+ if doc.get("apiVersion") != _API_VERSION:+ return None+ metadata = doc.get("metadata") if isinstance(doc.get("metadata"), dict) else {}+ name = metadata.get("name")+ if not isinstance(name, str) or not name.strip():+ return None+ spec = doc.get("spec") if isinstance(doc.get("spec"), dict) else {}+ members = spec.get("members") if isinstance(spec.get("members"), list) else []+ # A Backstage user ref (``user:default/ana``) names the login ``ana``.+ logins = [str(m).rsplit("/", 1)[-1].split(":")[-1].lstrip("@") for m in members]+ annotations = metadata.get("annotations")+ raw = annotations.get(MEMBER_EMAILS_ANNOTATION) if isinstance(annotations, dict) else None+ emails = re.split(r"[,\s]+", str(raw or ""))+ return Team(+ name.strip(),+ tuple(dict.fromkeys(m.strip().lower() for m in logins if m.strip())),+ tuple(dict.fromkeys(e.strip().lower() for e in emails if "@" in e)),+ )+++team_directories: SeamRegistry[TeamDirectory] = SeamRegistry("team-directory")+team_directories.register("local", LocalTeamDirectory(), default=True)+++__all__ = [+ "MEMBER_EMAILS_ANNOTATION",+ "TEAMS_FILE",+ "DeclaredOwnership",+ "LocalTeamDirectory",+ "OwnerRef",+ "Team",+ "TeamDirectory",+ "team_directories",+]diff --git a/packages/server/src/repowise/server/mcp_server/_components.py b/packages/server/src/repowise/server/mcp_server/_components.pyindex ab48e8a6b..975a14f4c 100644--- a/packages/server/src/repowise/server/mcp_server/_components.py+++ b/packages/server/src/repowise/server/mcp_server/_components.py@@ -1,9 +1,11 @@"""Component targets for get_context and the component list for get_overview.Both are opt-in: a ``component:<name>`` target, or ``include=["components"]``.-Neither runs on a default call. The resolved components are cached per repo,-index state, catalog file times, workspace graph and exclusion rules, so a-batch of component targets and a later overview resolve them once.+Neither runs on a default call. A component card gains declared against+observed ownership only with ``include=["ownership"]``. The resolved+components are cached per repo, index state, catalog file times, workspace+graph and exclusion rules, so a batch of component targets and a later+overview resolve them once."""from __future__ import annotations@@ -14,6 +16,7 @@ from typing import Anyfrom repowise.core.components.catalog import CATALOG_FILES, Componentfrom repowise.core.components.store import (RepoComponents,+ component_ownership,component_rollups,load_repo_components,services_from_system_graph,@@ -125,9 +128,11 @@ async def component_cards(repo_root: Any,alias: str | None,exclude_spec: Any,+ ownership: bool = False,) -> dict[str, dict[str, Any]]:"""get_context cards for ``component:<name>`` *targets*: components resolved- once and each fact table read once for the whole batch, in turn on *session*."""+ once and each fact table read once for the whole batch, in turn on *session*.+ *ownership* adds each card's declared against observed ownership block."""found = await _load(session, repository, repo_root, alias, exclude_spec)wanted = {t: found.resolved.get(t[len(COMPONENT_PREFIX) :].strip()) for t in targets}to_fold = {@@ -140,6 +145,17 @@ async def component_cards(if to_foldelse {})+ owners: dict[str, dict[str, Any]] = {}+ directory_issues: list[str] = []+ if ownership:+ found_comps = {c.name: c for c in wanted.values() if c is not None}+ owners, directory_issues = await component_ownership(+ session,+ repository.id,+ repo_root,+ [(c, found.resolved.files[c.name]) for c in found_comps.values()],+ {n: r["bus_factor"] for n, r in rollups.items()},+ )cards: dict[str, dict[str, Any]] = {}for target, comp in wanted.items():name = target[len(COMPONENT_PREFIX) :].strip()@@ -164,6 +180,12 @@ async def component_cards(facts.pop("file_count")card["sample_files"] = files[:_SAMPLE_FILES]card["facts"] = facts+ if comp.name in owners:+ card["ownership"] = dict(owners[comp.name])+ if directory_issues:+ # Once per call, on the first card that carries ownership.+ card["ownership"]["directory_issues"] = directory_issues+ directory_issues = []cards[target] = cardreturn cardsdiff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex 26da9eff3..7e5475fe9 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -17,7 +17,9 @@ Optional ``include`` parameter widens the response:- include=["references"]→ every live edit site of a symbol (definition,imports, calls, other mentions) and whetherthe list is complete (symbol targets only)- - include=["ownership"] → primary owner, bus factor, contributor count+ - include=["ownership"] → primary owner, bus factor, contributor count; on a+ component target, declared owners against recent+ activity, with findings- include=["last_change"]→ last commit date and author- include=["metrics"] → PageRank, betweenness, percentile ranks- include=["community"] → community membership + neighbors@@ -211,7 +213,12 @@ async def get_context(# Component and change targets resolve first, in turn on this session,# so they never share the session with the gather.cards = await _component_cards(- session, repository, [t for t in targets if is_component_target(t)], ctx, exclude_spec+ session,+ repository,+ [t for t in targets if is_component_target(t)],+ ctx,+ exclude_spec,+ ownership="ownership" in include_set,)cards |= await _change_cards(session, repository, [t for t in targets if is_change_target(t)], collector@@ -342,7 +349,13 @@ async def get_context(async def _component_cards(- session: Any, repository: Any, targets: list[str], ctx: Any, exclude_spec: Any+ session: Any,+ repository: Any,+ targets: list[str],+ ctx: Any,+ exclude_spec: Any,+ *,+ ownership: bool = False,) -> dict[str, Any]:"""Cards for the batch's component targets; a failure becomes each one's error."""if not targets:@@ -355,6 +368,7 @@ async def _component_cards(repo_root=ctx.path,alias=ctx.alias,exclude_spec=exclude_spec,+ ownership=ownership,)except Exception as exc:return {t: exc for t in targets}diff --git a/tests/unit/cli/test_components_cmd.py b/tests/unit/cli/test_components_cmd.pyindex c162b647d..d5bc17455 100644--- a/tests/unit/cli/test_components_cmd.py+++ b/tests/unit/cli/test_components_cmd.py@@ -90,3 +90,45 @@ def test_list_without_an_index_uses_directories_and_the_catalog(repo):# The derived "src" keeps the file the declared component did not claim.assert rows["src"]["source"] == "directory" and rows["src"]["files"] == 1assert data["catalog_errors"] == 0+++def test_ownership_without_index_checks_declared_facts(repo):+ _write_catalog(+ repo,+ _CATALOG+ + """---+apiVersion: backstage.io/v1alpha1+kind: Component+metadata:+ name: ledger+ annotations:+ repowise.dev/paths: src/ledger/**+ repowise.dev/criticality: critical+spec: {type: service, lifecycle: production, owner: group:default/money}+""",+ )+ result = _invoke(["components", "ownership", "--path", str(repo), "--format", "json"])+ assert result.exit_code == 0, result.output+ data = json.loads(result.output)+ assert data["indexed"] is False+ by_name = {c["name"]: c for c in data["components"]}+ # Activity is unknown without an index, so the owned api component has no finding.+ assert by_name["api"]["findings"] == []+ assert by_name["api"]["declared_teams"][0]["activity"] == "unknown"+ assert [f["kind"] for f in by_name["ledger"]["findings"]] == ["catalog_entry_no_code"]++ text = _invoke(["components", "ownership", "--path", str(repo)])+ assert "catalog_entry_no_code ledger" in text.output+++def test_ownership_reports_a_bad_teams_file_once_without_its_content(repo):+ _write_catalog(repo, _CATALOG)+ (repo / ".repowise" / "teams.yaml").write_text(+ 'members: ["[email protected]", [\n', encoding="utf-8"+ )+ result = _invoke(["components", "ownership", "--path", str(repo), "--format", "json"])+ assert result.exit_code == 0, result.output+ data = json.loads(result.output)+ assert len(data["directory_issues"]) == 1+ assert all("directory_issues" not in c for c in data["components"])+ assert "hidden" not in result.outputdiff --git a/tests/unit/core/test_components_ownership.py b/tests/unit/core/test_components_ownership.pynew file mode 100644index 000000000..a09c8e763--- /dev/null+++ b/tests/unit/core/test_components_ownership.py@@ -0,0 +1,151 @@+"""Declared against observed ownership per component: the four findings."""++from __future__ import annotations++import json+from datetime import UTC, datetime++from repowise.core.components.catalog import Component+from repowise.core.components.ownership import Activity, assess_component, build_activity+from repowise.core.ownership.codeowners import parse_codeowners+from repowise.core.ownership.directory import DeclaredOwnership, Team++_FILES = ["src/pay/a.py", "src/pay/b.py"]+_AS_OF = datetime(2026, 10, 1, tzinfo=UTC)+_HISTORY = [+ ("Ana Lima", "[email protected]"),+ ("Li Wu", "[email protected]"),+ ("Old Hand", "[email protected]"),+ ("Kim", "[email protected]"),+ ("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com"),+]+++def _activity(recent: list[tuple[str, str, str, str]]) -> Activity:+ return build_activity(_HISTORY, recent, _AS_OF)+++def _declared(codeowners: str = "", teams: list[Team] | None = None) -> DeclaredOwnership:+ return DeclaredOwnership(+ teams={t.name.lower(): t for t in teams or []},+ codeowners_file=".github/CODEOWNERS",+ rules=parse_codeowners(codeowners),+ )+++def _comp(**kw) -> Component:+ return Component(name="pay", paths=("src/pay/**",), **kw)+++def _kinds(block: dict) -> list[str]:+ return [f["kind"] for f in block["findings"]]+++def test_active_team_owner_has_no_findings() -> None:+ team = Team("payments", emails=("[email protected]",))+ block = assess_component(+ _comp(owner="group:default/payments", criticality="critical"),+ _FILES,+ _declared(teams=[team]),+ _activity([("src/pay/a.py", "s1", "Ana Lima", "[email protected]")]),+ )+ assert block["findings"] == []+ assert block["declared_teams"] == [{"team": "payments", "files": 2, "activity": "active"}]+ assert block["recent"] == {+ "commits": 1,+ "contributors": 1,+ "window_days": 90,+ "as_of": "2026-10-01",+ }+ assert block["files_with_declared_owner"] == 2+++def test_inactive_team_and_critical_without_active_owner() -> None:+ team = Team("payments", logins=("old-gh",), emails=("[email protected]",))+ block = assess_component(+ _comp(owner="payments", criticality="high"),+ _FILES,+ _declared(teams=[team]),+ _activity([("src/pay/a.py", "s1", "Li Wu", "[email protected]")]),+ )+ assert _kinds(block) == ["declared_owner_inactive", "critical_no_active_owner"]+ assert "'payments'" in block["findings"][0]["message"]+++def test_owner_with_no_known_identity_is_unknown_not_inactive() -> None:+ teams = [Team("payments"), Team("ghosts", emails=("[email protected]",))]+ block = assess_component(+ _comp(owner="payments", criticality="critical"),+ _FILES,+ _declared("/src/pay/ @acme/ghosts\n", teams),+ _activity([]),+ )+ assert {t["activity"] for t in block["declared_teams"]} == {"unknown"}+ assert block["findings"] == []+++def test_critical_with_no_declared_owner() -> None:+ block = assess_component(_comp(criticality="critical"), _FILES, _declared(), _activity([]))+ assert _kinds(block) == ["critical_no_active_owner"]+ # Not critical: nothing to report.+ block = assess_component(_comp(criticality="medium"), _FILES, _declared(), _activity([]))+ assert block["findings"] == []+++def test_individual_owners_are_counted_never_named() -> None:+ codeowners = "/src/pay/a.py @kim-gh\n/src/pay/b.py [email protected]\n"+ recent = [+ ("src/pay/a.py", "s1", "Kim", "[email protected]"),+ ("src/pay/b.py", "s2", "Li Wu", "[email protected]"),+ ]+ block = assess_component(_comp(), _FILES, _declared(codeowners), _activity(recent))+ assert block["declared_individuals"] == {"count": 2, "no_recent_changes": 1, "unknown": 0}+ assert _kinds(block) == ["declared_owner_inactive"]+ text = json.dumps(block)+ for person in ("kim", "old@", "Kim", "Li Wu", "li@acme"):+ assert person not in text+++def test_bot_changes_are_not_activity() -> None:+ team = Team("payments", emails=("[email protected]",))+ bot = ("dependabot[bot]", "49699333+dependabot[bot]@users.noreply.github.com")+ recent = [("src/pay/a.py", "s1", *bot)]+ block = assess_component(+ _comp(owner="payments"), _FILES, _declared(teams=[team]), _activity(recent)+ )+ assert block["declared_teams"][0]["activity"] == "no_recent_changes"+ assert block["recent"]["contributors"] == 0+++def test_critical_bus_factor_one_only_when_measured() -> None:+ team = Team("payments", emails=("[email protected]",))+ recent = _activity([("src/pay/a.py", "s", "Ana Lima", "[email protected]")])+ args = (_FILES, _declared(teams=[team]), recent)+ comp = _comp(owner="payments", criticality="critical")+ measured = assess_component(comp, *args, {"value": 1, "basis": "measured"})+ assert _kinds(measured) == ["critical_bus_factor_one"]+ inferred = assess_component(comp, *args, {"value": 1, "basis": "inferred"})+ assert inferred["findings"] == []+++def test_catalog_entry_with_no_code() -> None:+ block = assess_component(_comp(criticality="critical"), [], _declared(), _activity([]))+ assert _kinds(block) == ["catalog_entry_no_code"]+ derived = Component(name="lib", source="directory", root="lib")+ assert assess_component(derived, [], _declared(), _activity([]))["findings"] == []+++def test_no_history_leaves_activity_unavailable() -> None:+ block = assess_component(_comp(owner="payments"), _FILES, _declared(), Activity())+ assert block["basis"] == "unavailable"+ assert "recent" not in block+ assert block["declared_teams"][0]["activity"] == "unknown"+++def test_unresolved_bare_handle_counts_as_owner_but_raises_nothing() -> None:+ declared = _declared("/src/pay/ @payments-group\n")+ declared.codeowners_file = ".gitlab/CODEOWNERS"+ block = assess_component(_comp(criticality="critical"), _FILES, declared, _activity([]))+ assert block["declared_unresolved"] == 1+ assert block["findings"] == []+ assert "payments-group" not in json.dumps(block)diff --git a/tests/unit/core/test_ownership_codeowners.py b/tests/unit/core/test_ownership_codeowners.pynew file mode 100644index 000000000..9116af5a8--- /dev/null+++ b/tests/unit/core/test_ownership_codeowners.py@@ -0,0 +1,70 @@+"""The shared CODEOWNERS parser and matcher: GitHub and GitLab semantics."""++from __future__ import annotations++from repowise.core.ownership.codeowners import (+ CodeownersMatcher,+ CodeownersRule,+ parse_codeowners,+ read_codeowners,+)++_GITLAB = """\+# Default section: rules before any header.+* @acme/platform++[Docs] @acme/writers+/docs/+/docs/api/ @acme/api-docs++^[Backend][2] @acme/backend+/src/+/src/billing/ @acme/billing+/src/vendor/++[frontend]+/web/ @acme/web++[FRONTEND] @acme/design+/web/styles/+"""+++def test_gitlab_sections_parse_with_defaults_optional_and_counts() -> None:+ rules = parse_codeowners(_GITLAB)+ assert rules[0] == CodeownersRule("*", ("@acme/platform",), None)+ assert CodeownersRule("/docs/", ("@acme/writers",), "docs") in rules+ assert CodeownersRule("/src/", ("@acme/backend",), "backend") in rules+ # An owner-less line takes the section default; ``^`` and ``[2]`` are accepted.+ assert CodeownersRule("/src/vendor/", ("@acme/backend",), "backend") in rules+ # Section names are one section whatever their case; each header keeps its defaults.+ assert CodeownersRule("/web/styles/", ("@acme/design",), "frontend") in rules+++def test_gitlab_owners_are_the_union_of_each_sections_last_match() -> None:+ match = CodeownersMatcher(parse_codeowners(_GITLAB))+ assert match.owners("docs/api/ref.md") == ("@acme/platform", "@acme/api-docs")+ assert match.owners("src/billing/pay.py") == ("@acme/platform", "@acme/billing")+ assert match.owners("src/core.py") == ("@acme/platform", "@acme/backend")+ # Two headers with one name are one section: the later rule wins inside it.+ assert match.owners("web/styles/a.css") == ("@acme/platform", "@acme/design")+ assert match.owners("web/app.ts") == ("@acme/platform", "@acme/web")+ assert match.owners("README.md") == ("@acme/platform",)+++def test_github_last_match_wins_and_ownerless_line_clears() -> None:+ text = "* @org/all\n/pkg/ @org/pkg # pkg team\n/pkg/vendor/\n*.md [email protected]\n"+ match = CodeownersMatcher(parse_codeowners(text))+ assert match.owners("pkg/a.py") == ("@org/pkg",)+ assert match.owners("pkg/vendor/x.py") == ()+ assert match.owners("pkg/README.md") == ("[email protected]",)+ assert match.owners("lib/b.py") == ("@org/all",)+++def test_read_codeowners_takes_the_first_location(tmp_path) -> None:+ assert read_codeowners(tmp_path) is None+ (tmp_path / "docs").mkdir()+ (tmp_path / "docs" / "CODEOWNERS").write_text("* @b\n", encoding="utf-8")+ (tmp_path / ".github").mkdir()+ (tmp_path / ".github" / "CODEOWNERS").write_text("* @a\n", encoding="utf-8")+ assert read_codeowners(tmp_path) == (".github/CODEOWNERS", "* @a\n")diff --git a/tests/unit/core/test_ownership_directory.py b/tests/unit/core/test_ownership_directory.pynew file mode 100644index 000000000..f21f72d8b--- /dev/null+++ b/tests/unit/core/test_ownership_directory.py@@ -0,0 +1,129 @@+"""The team-directory seam and its local default (CODEOWNERS, Backstage, teams.yaml)."""++from __future__ import annotations++from repowise.core.ownership.directory import (+ LocalTeamDirectory,+ OwnerRef,+ Team,+ team_directories,+)++_CATALOG_INFO = """\+apiVersion: backstage.io/v1alpha1+kind: Component+metadata:+ name: payments+ annotations:+ repowise.dev/paths: src/payments/**+ repowise.dev/criticality: critical+spec: {type: service, lifecycle: production, owner: group:default/payments-team}+---+apiVersion: backstage.io/v1alpha1+kind: Group+metadata: {name: payments-team}+spec:+ type: team+ children: []+ members: [should-not-be-read]+---+apiVersion: backstage.io/v1alpha1+kind: Group+metadata: {name: platform}+spec: {type: team, children: []}+"""++_TEAMS = """\+apiVersion: backstage.io/v1alpha1+kind: Group+metadata:+ name: platform+ annotations:+ repowise.dev/member-emails: "[email protected], [email protected]"+spec:+ type: team+ children: []+ members: [user:default/ana-gh, "@li-gh"]+---+kind: Group+metadata: {name: no-api-version}+"""+++def _repo(tmp_path):+ (tmp_path / ".repowise").mkdir()+ (tmp_path / "catalog-info.yaml").write_text(_CATALOG_INFO, encoding="utf-8")+ (tmp_path / ".repowise" / "teams.yaml").write_text(_TEAMS, encoding="utf-8")+ (tmp_path / "CODEOWNERS").write_text("/src/ @acme/platform\n", encoding="utf-8")+ return tmp_path+++def test_local_directory_reads_codeowners_groups_and_teams_file(tmp_path) -> None:+ declared = LocalTeamDirectory().load(_repo(tmp_path))+ assert declared.codeowners_file == "CODEOWNERS"+ assert declared.codeowners_of("src/a.py") == ("@acme/platform",)+ # Catalog Groups are names only: their spec.members is never read.+ assert declared.teams["payments-team"] == Team("payments-team")+ assert declared.teams["platform"] == Team(+ "platform", ("ana-gh", "li-gh"), ("[email protected]", "[email protected]")+ )+ assert declared.issues == [+ ".repowise/teams.yaml: a document is not a backstage.io/v1alpha1 Group with a name"+ ]+++def test_owner_refs_from_codeowners_and_backstage(tmp_path) -> None:+ declared = LocalTeamDirectory().load(_repo(tmp_path))+ platform = declared.teams["platform"]+ assert declared.from_codeowners("@acme/platform") == OwnerRef("team", "platform", platform)+ assert declared.from_codeowners("@gitlab-org/sub/platform").team is platform+ assert declared.from_codeowners("@acme/unknown") == OwnerRef("team", "unknown", None)+ # A bare handle is a team only when one is declared by that name; outside+ # .github/ it may be a GitLab group, so it stays unresolved.+ assert declared.from_codeowners("@platform").kind == "team"+ assert declared.from_codeowners("@Someone") == OwnerRef("unresolved", "someone")+ assert declared.from_codeowners("[email protected]") == OwnerRef("individual", "[email protected]")+ assert declared.from_backstage("group:default/payments-team").kind == "team"+ assert declared.from_backstage("platform").team is platform+ assert declared.from_backstage("user:default/jdoe") == OwnerRef("individual", "jdoe")+++def test_seam_defaults_to_the_local_directory() -> None:+ assert team_directories.default == "local"+ assert isinstance(team_directories.get(), LocalTeamDirectory)+++def test_nothing_declared_is_an_empty_directory(tmp_path) -> None:+ declared = LocalTeamDirectory().load(tmp_path)+ assert (declared.teams, declared.rules, declared.issues) == ({}, [], [])+ assert declared.codeowners_of("a.py") == ()+++def test_bare_handle_is_an_individual_only_in_a_github_file(tmp_path) -> None:+ (tmp_path / ".github").mkdir()+ (tmp_path / ".github" / "CODEOWNERS").write_text("* @someone\n", encoding="utf-8")+ declared = LocalTeamDirectory().load(tmp_path)+ assert declared.from_codeowners("@someone") == OwnerRef("individual", "someone")+++def test_gitlab_bare_group_handle_is_unresolved(tmp_path) -> None:+ (tmp_path / ".gitlab").mkdir()+ (tmp_path / ".gitlab" / "CODEOWNERS").write_text(+ "[Backend] @backend-group\n/src/\n", encoding="utf-8"+ )+ declared = LocalTeamDirectory().load(tmp_path)+ (owner,) = declared.codeowners_of("src/a.py")+ assert declared.from_codeowners(owner) == OwnerRef("unresolved", "backend-group")+++def test_malformed_teams_file_never_echoes_its_content(tmp_path) -> None:+ (tmp_path / ".repowise").mkdir()+ (tmp_path / ".repowise" / "teams.yaml").write_text(+ "kind: Group\nmetadata:\n annotations:\n"+ ' repowise.dev/member-emails: "[email protected]\n bad: [unclosed\n',+ encoding="utf-8",+ )+ declared = LocalTeamDirectory().load(tmp_path)+ assert len(declared.issues) == 1+ assert declared.issues[0].startswith(".repowise/teams.yaml: invalid YAML")+ assert "secret" not in declared.issues[0] and "acme" not in declared.issues[0]diff --git a/tests/unit/server/mcp/test_components_mcp.py b/tests/unit/server/mcp/test_components_mcp.pyindex f1a392d99..c8e3b3542 100644--- a/tests/unit/server/mcp/test_components_mcp.py+++ b/tests/unit/server/mcp/test_components_mcp.py@@ -222,3 +222,69 @@ async def test_a_component_batch_reads_each_fact_table_once(setup_mcp, tmp_path,assert all("facts" in result["targets"][t] for t in result["targets"])# git, health and dead-code rows once each, and the run status once, for three components.assert (len(reads), len(runs)) == (3, 1)+++_TEAMS = """\+apiVersion: backstage.io/v1alpha1+kind: Group+metadata:+ name: identity+ annotations:+ repowise.dev/member-emails: [email protected]+spec: {type: team, children: []}+"""+++async def test_component_ownership_only_with_include(setup_mcp, session, tmp_path):+ from datetime import UTC, datetime++ from repowise.core.persistence.models import GitCommit, GitCommitFile+ from repowise.server.mcp_server import get_context+ from repowise.server.mcp_server._components import reset_cache++ when = datetime(2026, 9, 1, tzinfo=UTC)+ session.add_all(+ [+ GitCommit(+ repository_id="repo1",+ sha="a" * 40,+ author_name="Carol Diaz",+ author_email="[email protected]",+ committed_at=datetime(2026, 1, 1, tzinfo=UTC),+ ),+ GitCommit(+ repository_id="repo1",+ sha="b" * 40,+ author_name="Dan Wu",+ author_email="[email protected]",+ committed_at=when,+ ),+ GitCommitFile(repository_id="repo1", sha="a" * 40, file_path="src/auth/service.py"),+ GitCommitFile(repository_id="repo1", sha="b" * 40, file_path="src/auth/service.py"),+ ]+ )+ await session.commit()+ _write_catalog(tmp_path)+ (tmp_path / ".repowise" / "teams.yaml").write_text(_TEAMS, encoding="utf-8")+ reset_cache()++ plain = (await get_context(targets=["component:auth"]))["targets"]["component:auth"]+ assert "ownership" not in plain++ result = await get_context(+ targets=["component:auth", "component:billing"], include=["ownership"]+ )+ auth = result["targets"]["component:auth"]["ownership"]+ assert auth["declared_teams"] == [+ {"team": "identity", "files": 2, "activity": "no_recent_changes"}+ ]+ assert [f["kind"] for f in auth["findings"]] == [+ "declared_owner_inactive",+ "critical_no_active_owner",+ ]+ assert auth["recent"]["commits"] == 1+ billing = result["targets"]["component:billing"]["ownership"]+ assert [f["kind"] for f in billing["findings"]] == ["catalog_entry_no_code"]+ text = json.dumps(result["targets"])+ assert "carol" not in text.lower() and "dan@" not in text