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: agent co-author detection + derived decision scope (#803)
Swati Ahuja23f0e663e0fb
diff --git a/packages/api-client/src/types/decisions.ts b/packages/api-client/src/types/decisions.tsindex 93de970a5..26db63460 100644--- a/packages/api-client/src/types/decisions.ts+++ b/packages/api-client/src/types/decisions.ts@@ -25,6 +25,11 @@ export interface DecisionRecordResponse {last_code_change: string | null;/** Trust tier of the decision's primary supporting evidence. */verification?: DecisionVerification;+ /**+ * Derived granularity of the decision's blast area. Absent on older+ * backends; null when the record has no code linkage at all.+ */+ scope?: "file" | "module" | "cross-module" | null;created_at: string;updated_at: string;/** Evidence rows backing the record. Populated by the list endpoint only. */diff --git a/packages/core/src/repowise/core/analysis/decisions/scope.py b/packages/core/src/repowise/core/analysis/decisions/scope.pynew file mode 100644index 000000000..1e931ee85--- /dev/null+++ b/packages/core/src/repowise/core/analysis/decisions/scope.py@@ -0,0 +1,51 @@+"""Derived decision granularity — how much of the codebase a decision spans.++Pure derivation from a record's existing linkage fields (no LLM, no I/O), so+it can run at serialization time for any record, old or new. Levels, narrowest+first: ``file`` < ``module`` < ``cross-module``. ``None`` means the record has+no code linkage at all — better no claim than defaulting the least-grounded+records to the widest level.+"""++from __future__ import annotations++from collections.abc import Sequence++__all__ = ["derive_decision_scope"]+++def derive_decision_scope(+ affected_files: Sequence[str] | None,+ affected_modules: Sequence[str] | None,+ *,+ evidence_file: str | None = None,+) -> str | None:+ """Return the scope level for one decision record, or ``None``.++ Rules, in order:++ - nothing linked at all: ``file`` when an *evidence_file* pins the record+ to one file, else ``None`` — explicit file/module linkage always+ outranks the evidence-file fallback+ - exactly one affected file → ``file``+ - otherwise count distinct modules — the explicitly linked ones, or when+ none are linked, the top-level directories of the affected files: one →+ ``module``, several → ``cross-module``; multiple root-level files with+ no directory stay ``file``.++ An evidence line narrows nothing on its own — a line without a resolved+ symbol still only proves file-level scope — so it is deliberately not a+ parameter.+ """+ files = {f for f in (affected_files or []) if f}+ modules = {m for m in (affected_modules or []) if m}++ if not files and not modules:+ return "file" if evidence_file else None+ if len(files) == 1:+ return "file"+ if not modules:+ modules = {f.split("/", 1)[0] for f in files if "/" in f}+ if not modules:+ return "file"+ return "module" if len(modules) == 1 else "cross-module"diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.pyindex 135d8b678..67c0dc6dc 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py@@ -118,6 +118,23 @@ _AGENT_ALIASES: list[tuple[str, str]] = [_SERVICE_EMAILS: dict[str, tuple[str, int]] = {"[email protected]": ("cursor", 1),"devin-ai-integration[bot]@users.noreply.github.com": ("devin", 1),+ # Primarily Claude's co-author identity; as AUTHOR it is tier 1 like every+ # other service e-mail here.+ "[email protected]": ("claude", 1),+}++# Agent-vendor e-mail domains → the exact agent identities each vendor emits.+# A domain alone is never enough — real humans work at these companies — so an+# identity here counts only when the LOCAL PART fully matches the vendor's+# allowlisted agent identity (anchored fullmatch, never a substring scan, and+# per vendor, never a flat token set): ``[email protected]`` and the+# ``claude-<model>`` slugs match; ``[email protected]``,+# ``[email protected]`` and ``[email protected]`` never do.+_VENDOR_DOMAIN_LOCALS: dict[str, tuple[re.Pattern[str], str]] = {+ "anthropic.com": (re.compile(r"claude(?:-(?:opus|sonnet|haiku)(?:-[\w.]+)?)?"), "claude"),+ "openai.com": (re.compile(r"codex"), "codex"),+ "cursor.com": (re.compile(r"cursor(?:agent)?"), "cursor"),+ "devin.ai": (re.compile(r"devin"), "devin"),}# Commit-message footers → agent (exact service phrases only).@@ -158,6 +175,13 @@ _COAUTHOR_PATTERNS: list[tuple[str, str]] = [_AIDER_NAME_RE = re.compile(r"\(aider\)\s*$")+# Any ``Co-authored-by:`` trailer's e-mail, for registry-based identity+# matching: agent service identities the explicit patterns above don't name+# (bot noreply logins, exact service e-mails, vendor-domain identities) are+# resolved through the same :meth:`AgentProvenanceClassifier._identity_match`+# registry — one list, no parallel patterns.+_COAUTHOR_EMAIL_RE = re.compile(r"^co-authored-by:[^<\n]*<([^>\s]+)>", re.IGNORECASE | re.MULTILINE)+def _normalize_agent_token(value: str, *, allow_slug: bool) -> str | None:"""Resolve a free-text tool/agent name to a canonical label.@@ -274,6 +298,10 @@ class AgentProvenanceClassifier:m = self._bot_email_re.match(e)if m:return (_BOT_LOGINS[m.group(1).lower()], 1)+ local, _, domain = e.partition("@")+ vendor = _VENDOR_DOMAIN_LOCALS.get(domain)+ if vendor and vendor[0].fullmatch(local):+ return (vendor[1], 1)return Nonedef classify(@@ -328,6 +356,10 @@ class AgentProvenanceClassifier:for pat, agent in self._coauthors:if pat.search(message):return AgentProvenance(agent, 3, "coauthor_trailer", "high")+ for m in _COAUTHOR_EMAIL_RE.finditer(message):+ hit = self._identity_match(m.group(1))+ if hit:+ return AgentProvenance(hit[0], 3, "coauthor_trailer", "high")return _HUMANdiff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.pyindex 76b363d17..e7c4c48f8 100644--- a/packages/server/src/repowise/server/schemas/decisions.py+++ b/packages/server/src/repowise/server/schemas/decisions.py@@ -7,6 +7,8 @@ from datetime import datetimefrom pydantic import BaseModel+from repowise.core.analysis.decisions.scope import derive_decision_scope+class EvidencePreview(BaseModel):"""The top-ranked evidence row, slimmed for list rows."""@@ -38,6 +40,10 @@ class DecisionRecordResponse(BaseModel):confidence: floatstaleness_score: floatverification: str = "unverified"+ # Derived granularity: file | module | cross-module, or None when the+ # record has no code linkage at all. Computed at serialization time from+ # the linkage fields, so old records get it too.+ scope: str | None = Nonesuperseded_by: str | Nonelast_code_change: datetime | Nonecreated_at: datetime@@ -51,6 +57,8 @@ class DecisionRecordResponse(BaseModel):@classmethoddef from_orm(cls, obj: object) -> DecisionRecordResponse:+ affected_files = json.loads(obj.affected_files_json) # type: ignore[attr-defined]+ affected_modules = json.loads(obj.affected_modules_json) # type: ignore[attr-defined]return cls(id=obj.id, # type: ignore[attr-defined]repository_id=obj.repository_id, # type: ignore[attr-defined]@@ -67,8 +75,8 @@ class DecisionRecordResponse(BaseModel):rationale=obj.rationale, # type: ignore[attr-defined]alternatives=json.loads(obj.alternatives_json), # type: ignore[attr-defined]consequences=json.loads(obj.consequences_json), # type: ignore[attr-defined]- affected_files=json.loads(obj.affected_files_json), # type: ignore[attr-defined]- affected_modules=json.loads(obj.affected_modules_json), # type: ignore[attr-defined]+ affected_files=affected_files,+ affected_modules=affected_modules,tags=json.loads(obj.tags_json), # type: ignore[attr-defined]source=obj.source, # type: ignore[attr-defined]evidence_commits=json.loads(obj.evidence_commits_json), # type: ignore[attr-defined]@@ -77,6 +85,11 @@ class DecisionRecordResponse(BaseModel):confidence=obj.confidence, # type: ignore[attr-defined]staleness_score=obj.staleness_score, # type: ignore[attr-defined]verification=obj.verification, # type: ignore[attr-defined]+ scope=derive_decision_scope(+ affected_files,+ affected_modules,+ evidence_file=obj.evidence_file, # type: ignore[attr-defined]+ ),superseded_by=obj.superseded_by, # type: ignore[attr-defined]last_code_change=obj.last_code_change, # type: ignore[attr-defined]created_at=obj.created_at, # type: ignore[attr-defined]diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.tsindex 2af5ec983..1d098b941 100644--- a/packages/types/src/decisions.ts+++ b/packages/types/src/decisions.ts@@ -19,6 +19,9 @@ export type DecisionSource =| "readme_mining"| "cli";+/** Derived granularity of a decision's blast area, narrowest first. */+export type DecisionScope = "file" | "module" | "cross-module";+export interface DecisionRecord {id: string;repository_id: string;@@ -42,6 +45,11 @@ export interface DecisionRecord {last_code_change: string | null;/** Trust tier of the decision's primary supporting evidence. Optional for back-compat. */verification?: DecisionVerification;+ /**+ * Derived granularity level. Optional for back-compat with older backends;+ * null when the record has no code linkage at all.+ */+ scope?: DecisionScope | null;created_at: string;updated_at: string;/** Number of evidence rows backing the record. List endpoint only. */diff --git a/packages/ui/__tests__/decisions/decisions-table.test.tsx b/packages/ui/__tests__/decisions/decisions-table.test.tsxindex 3fc593a7c..fc6ee9f67 100644--- a/packages/ui/__tests__/decisions/decisions-table.test.tsx+++ b/packages/ui/__tests__/decisions/decisions-table.test.tsx@@ -66,6 +66,74 @@ describe("DecisionsTable", () => {});});+ it("renders a scope badge when the record carries one", () => {+ render(+ <DecisionsTable+ {...baseProps}+ decisions={[+ makeDecision({ id: "1", scope: "file" }),+ makeDecision({ id: "2", title: "Adopt SWR", scope: "cross-module" }),+ ]}+ />,+ );+ // The scope <select> options share these labels, so exclude them.+ expect(screen.getAllByText("File").some((el) => el.tagName !== "OPTION")).toBe(true);+ expect(+ screen.getAllByText("Cross-module").some((el) => el.tagName !== "OPTION"),+ ).toBe(true);+ });++ it("invokes onFiltersChange when the scope filter changes", () => {+ const onFiltersChange = vi.fn();+ render(+ <DecisionsTable+ {...baseProps}+ onFiltersChange={onFiltersChange}+ decisions={[makeDecision({ id: "1", scope: "file" })]}+ />,+ );+ fireEvent.change(screen.getByLabelText("Filter by scope"), {+ target: { value: "module" },+ });+ expect(onFiltersChange).toHaveBeenCalledWith({+ status: "all",+ source: "all",+ scope: "module",+ });+ });++ it("hides the scope filter and ignores a scope value when no record carries scope", () => {+ render(+ <DecisionsTable+ {...baseProps}+ filters={{ status: "all", source: "all", scope: "file" }}+ decisions={[+ makeDecision({ id: "1", title: "Pick Postgres" }),+ makeDecision({ id: "2", title: "Adopt SWR" }),+ ]}+ />,+ );+ expect(screen.queryByLabelText("Filter by scope")).not.toBeInTheDocument();+ // Rows are NOT filtered out by the stale scope value.+ expect(screen.getByText("Pick Postgres")).toBeInTheDocument();+ expect(screen.getByText("Adopt SWR")).toBeInTheDocument();+ });++ it("filters rows client-side by scope", () => {+ render(+ <DecisionsTable+ {...baseProps}+ filters={{ status: "all", source: "all", scope: "file" }}+ decisions={[+ makeDecision({ id: "1", title: "Pick Postgres", scope: "file" }),+ makeDecision({ id: "2", title: "Adopt SWR", scope: "cross-module" }),+ ]}+ />,+ );+ expect(screen.getByText("Pick Postgres")).toBeInTheDocument();+ expect(screen.queryByText("Adopt SWR")).not.toBeInTheDocument();+ });+it("renders a retry button when an error is supplied with no decisions", () => {const onRetry = vi.fn();render(diff --git a/packages/ui/src/decisions/decisions-table.tsx b/packages/ui/src/decisions/decisions-table.tsxindex 24945a9dc..c8db10480 100644--- a/packages/ui/src/decisions/decisions-table.tsx+++ b/packages/ui/src/decisions/decisions-table.tsx@@ -14,6 +14,7 @@ import type {DecisionRecord,DecisionStatus,DecisionSource,+ DecisionScope,} from "@repowise-dev/types/decisions";const STATUS_VARIANT: Record<string, "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"> = {@@ -30,12 +31,25 @@ const SOURCE_LABEL: Record<string, string> = {cli: "Manual",};+const SCOPE_LABEL: Record<string, string> = {+ file: "File",+ module: "Module",+ "cross-module": "Cross-module",+};+export type DecisionStatusFilter = DecisionStatus | "all";export type DecisionSourceFilter = DecisionSource | "all";+export type DecisionScopeFilter = DecisionScope | "all";export interface DecisionsTableFilters {status: DecisionStatusFilter;source: DecisionSourceFilter;+ /**+ * Optional for back-compat with callers that predate scope. Unlike+ * status/source (server query params), scope is derived at serialization+ * time, so the table filters rows client-side.+ */+ scope?: DecisionScopeFilter;}export interface DecisionsTableProps {@@ -71,6 +85,16 @@ export function DecisionsTable({const prefix = linkPrefix ?? `/repos/${repoId}`;const Link = LinkComponent;+ // Scope is derived at serialization time (no server-side query param), so+ // this filter applies client-side to the fetched rows. Backends that don't+ // serve scope yet leave every row null: hide the filter (it could only+ // empty the table) and ignore any lingering scope value.+ const scopeFilter = filters.scope ?? "all";+ const hasScope = (decisions ?? []).some((d) => d.scope != null);+ const visibleDecisions = (decisions ?? []).filter(+ (d) => !hasScope || scopeFilter === "all" || d.scope === scopeFilter,+ );+const columns: ResponsiveColumn<DecisionRecord>[] = [{key: "title",@@ -123,6 +147,17 @@ export function DecisionsTable({cellClassName: "text-[var(--color-text-secondary)]",render: (d) => SOURCE_LABEL[d.source] ?? d.source,},+ {+ key: "scope",+ header: "Scope",+ priority: 3,+ render: (d) =>+ d.scope ? (+ <Badge variant="outline">{SCOPE_LABEL[d.scope] ?? d.scope}</Badge>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">—</span>+ ),+ },{key: "trust",header: "Trust",@@ -234,11 +269,26 @@ export function DecisionsTable({<option value="readme_mining">Docs mining</option><option value="cli">Manual</option></select>+ {hasScope && (+ <select+ value={filters.scope ?? "all"}+ onChange={(e) =>+ onFiltersChange({ ...filters, scope: e.target.value as DecisionScopeFilter })+ }+ aria-label="Filter by scope"+ className="w-full sm:w-auto rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-3 py-1.5 text-sm text-[var(--color-text-primary)]"+ >+ <option value="all">All scopes</option>+ <option value="file">File</option>+ <option value="module">Module</option>+ <option value="cross-module">Cross-module</option>+ </select>+ )}</div><ResponsiveTablecolumns={columns}- rows={decisions ?? []}+ rows={visibleDecisions}rowKey={(d) => d.id}empty={empty}/>diff --git a/tests/unit/analysis/test_decision_scope.py b/tests/unit/analysis/test_decision_scope.pynew file mode 100644index 000000000..4b9e90b8b--- /dev/null+++ b/tests/unit/analysis/test_decision_scope.py@@ -0,0 +1,55 @@+"""Unit tests for the derived decision scope level — one test per rule branch."""++from __future__ import annotations++from repowise.core.analysis.decisions.scope import derive_decision_scope+++def test_single_file_is_file() -> None:+ assert derive_decision_scope(["a/b.py"], []) == "file"+++def test_evidence_file_counts_when_nothing_else_is_linked() -> None:+ assert derive_decision_scope([], [], evidence_file="a/b.py") == "file"+++def test_modules_outrank_the_evidence_file_fallback() -> None:+ assert (+ derive_decision_scope([], ["server", "ui", "core"], evidence_file="README.md")+ == "cross-module"+ )+ assert derive_decision_scope([], ["server"], evidence_file="README.md") == "module"+++def test_multiple_files_one_module_is_module() -> None:+ assert derive_decision_scope(["a/b.py", "a/c.py"], ["a"]) == "module"+++def test_multiple_files_without_modules_infers_from_top_level_dirs() -> None:+ assert derive_decision_scope(["a/b.py", "a/c.py"], []) == "module"+ assert derive_decision_scope(["a/b.py", "z/c.py"], []) == "cross-module"+++def test_multiple_root_level_files_without_modules_is_file() -> None:+ assert derive_decision_scope(["README.md", "LICENSE"], []) == "file"+++def test_files_spanning_modules_is_cross_module() -> None:+ assert derive_decision_scope(["a/b.py", "z/c.py"], ["a", "z"]) == "cross-module"+++def test_only_one_module_is_module() -> None:+ assert derive_decision_scope([], ["a"]) == "module"+++def test_only_multiple_modules_is_cross_module() -> None:+ assert derive_decision_scope([], ["a", "z"]) == "cross-module"+++def test_nothing_linked_is_none() -> None:+ assert derive_decision_scope([], []) is None+ assert derive_decision_scope(None, None) is None+++def test_duplicate_file_entries_collapse_to_one_file() -> None:+ assert derive_decision_scope(["a/b.py", "a/b.py"], []) == "file"diff --git a/tests/unit/ingestion/test_agent_provenance.py b/tests/unit/ingestion/test_agent_provenance.pyindex 64b75e3cf..5e2c0b12d 100644--- a/tests/unit/ingestion/test_agent_provenance.py+++ b/tests/unit/ingestion/test_agent_provenance.py@@ -27,7 +27,9 @@ from repowise.core.ingestion.git_indexer.records import _CommitRecCLF = AgentProvenanceClassifier()-def _classify(an="Dev", ae="[email protected]", cn="Dev", ce="[email protected]", msg="feat: thing", note_agent=None):+def _classify(+ an="Dev", ae="[email protected]", cn="Dev", ce="[email protected]", msg="feat: thing", note_agent=None+):return CLF.classify(an, ae, cn, ce, msg, note_agent=note_agent)@@ -101,6 +103,45 @@ def test_coauthor_trailer_is_tier3() -> None:assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 3, "coauthor_trailer")+def test_coauthor_trailer_with_bot_noreply_email_is_tier3() -> None:+ """A co-author trailer whose e-mail is a known bot noreply identity is+ matched through the identity registry — no explicit pattern needed."""+ msg = (+ "chore: bump deps\n\n"+ "Co-authored-by: gemini-code-assist[bot] "+ "<176961590+gemini-code-assist[bot]@users.noreply.github.com>"+ )+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("gemini", 3, "coauthor_trailer")+++def test_coauthor_trailer_with_vendor_domain_email_is_tier3() -> None:+ msg = "fix: retry\n\nCo-authored-by: Codex <[email protected]>"+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("codex", 3, "coauthor_trailer")+++def test_agent_local_part_at_vendor_domain_author_is_tier1() -> None:+ prov = _classify(an="Claude", ae="[email protected]")+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 1, "service_email")+ prov = _classify(an="Claude", ae="[email protected]")+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 1, "service_email")+++def test_vendor_domain_committer_over_human_author_is_tier2() -> None:+ prov = _classify(cn="Claude", ce="[email protected]")+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 2, "service_committer")+++def test_human_at_vendor_domain_is_unlabelled() -> None:+ """The vendor domain alone must never label a commit — the local part has+ to name the agent."""+ prov = _classify(an="Jane Doe", ae="[email protected]")+ assert prov.agent is None+ msg = "fix: typo\n\nCo-authored-by: Jane Doe <[email protected]>"+ assert _classify(msg=msg).agent is None++def test_tier_precedence_footer_beats_trailer() -> None:"""A commit carrying both a T2 footer and a T3 trailer is T2 — first matchin tier order wins."""@@ -129,6 +170,45 @@ def test_mentioning_claude_in_prose_is_not_a_footer() -> None:assert prov.agent is None+def test_vendor_domain_lookalike_locals_are_unlabelled() -> None:+ """The vendor-domain channel is an exact allowlist on the local part —+ a human at an agent vendor whose address merely CONTAINS an agent token+ must never classify as an agent."""+ for email in (+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ):+ assert _classify(an="Someone", ae=email).agent is None, email+++def test_vendor_domain_allowlists_are_per_vendor_not_a_flat_set() -> None:+ """codex is OpenAI's agent identity, not Anthropic's."""+ assert _classify(an="X", ae="[email protected]").agent is None+++def test_coauthor_human_name_containing_agent_token_is_unlabelled() -> None:+ msg = "feat: sonata\n\nCo-authored-by: Claude Debussy <[email protected]>"+ assert _classify(msg=msg).agent is None+++def test_mixed_case_coauthor_trailer_matches() -> None:+ msg = "fix: z\n\nCO-AUTHORED-BY: Claude <[email protected]>"+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 3, "coauthor_trailer")+++def test_multi_coauthor_human_first_agent_second_is_detected() -> None:+ msg = (+ "feat: pairing\n\n"+ "Co-authored-by: Jane Doe <[email protected]>\n"+ "Co-authored-by: Claude <[email protected]>"+ )+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier) == ("claude", 3)++def test_devin_service_trailer_matches() -> None:msg = ("feat: connector\n\n"