Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(attribution): three-state AI labels with coverage, and a switch to turn attribution off (#3732)

Raghav Chamadiya2edc120a847e
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 54683cc9c..7642b18bf 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2217,6 +2217,20 @@ does not know or list the commands. See [pluggable storage and capability seams]
---
+### `repowise attribution`
+
+Inspect and clear AI attribution for a repository.
+
+```bash
+repowise attribution status [PATH] [--format json] # what is on, for which agents, coverage
+repowise attribution purge [PATH] [--yes] # delete attribution derived into the local index
+```
+
+`purge` leaves git history, trailers and notes in the repository as they are.
+Settings live in the `attribution:` block of [CONFIG.md](CONFIG.md#the-attribution-block).
+
+---
+
### `repowise config hints on|off`
Now and then, at a moment where it would help (a finished `init`, a slow
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index 59c7f4339..1d7f74fda 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -138,7 +138,7 @@ workspace overlays, MCP responses, and CLI output.
| Stable file flag | File with more than 10 total commits and no recent 90-day commits. | `_index_file()` | `is_stable: true` |
| Co-change partner | File historically changed in the same commits, with temporal decay. | `compute_co_changes_and_entropy()` | `{file_path: "src/schema.py", co_change_count: 3.72, last_co_change: "2026-04-14"}` |
| Agent provenance (commit) | Which coding agent (if any) authored a commit, from local-git channels only (identity fields, message footers, co-author trailers); tier 1 = near-autonomous bot account, 2 = human-driven agent, 3 = assisted. | `agent_provenance.AgentProvenanceClassifier.classify()` | `{agent_name: "claude", agent_autonomy_tier: 2, agent_channel: "message_footer", agent_confidence: "high"}` |
-| Agent-authored share (file) | Fraction of a file's indexed commits that are agent-attributed, with per-tier counts. | `_index_file()` | `{agent_authored_pct: 0.42, agent_commit_count: 21, agent_tier_counts: {"2": 18, "3": 3}}` |
+| Agent-authored share (file) | Agent share of a file's commits with a known source (agent or human-attested), shown beside the coverage (known / all commits) and withheld below 30% coverage. Unknown commits are never counted as human. | `_add_agent_rollup()`, `attribution.file_share()` | `{agent_authored_pct: 0.6, attribution_coverage: 0.5, agent_commit_count: 3, agent_tier_counts: {"2": 3}}` |
| Git index summary | Repo-level indexing result. | `GitIndexSummary` | `{files_indexed: 420, hotspots: 38, stable_files: 71, duration_seconds: 12.4}` |
## Generated Wiki Pages
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 4d57f235a..2e7ba95dd 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -15,6 +15,7 @@ The `.repowise/` directory, provider setup, API keys, and what's customizable.
[The `mcp:` block](#the-mcp-block) ·
[The `decisions:` block](#the-decisions-block) ·
[The `security:` block](#the-security-block) ·
+[The `attribution:` block](#the-attribution-block) ·
[The `refactoring:` block](#the-refactoring-block) ·
[The `assertions:` block](#the-assertions-block)
@@ -587,6 +588,17 @@ security:
- Exit 2 (`config_invalid`, every problem listed) on an unknown key, a missing name or regex, a duplicate or badly shaped name, a bad severity, or a regex that does not compile, can match zero characters, or nests repetition like `(a+)+` or `(a|aa)+` (best effort).
- At most 50 patterns of 500 characters. Lines over 4096 characters are not matched and are counted (`long_lines_skipped` in JSON); a slow regex that passes the checks stays slow.
+### The `attribution:` block
+
+```yaml
+attribution:
+ enabled: true # read public AI markers: bot authors, trailers, footers, git-ai notes, Agent Trace files
+ capture: off # off, local or notes
+ agents: [] # agent target ids, e.g. claude-code, codex
+```
+
+The same block in `~/.repowise/config.yaml` applies to every repository, and the stricter value wins per key: `enabled: false` in either file, the lower capture level, and the agents both files list. With `enabled: false` nothing about AI is stored or shown in the API, CLI, MCP, web or wiki, and `DO_NOT_TRACK=1` keeps capture off. `repowise attribution status` shows the effective, repo and user values with the coverage of the indexed history.
+
### The `refactoring:` block
Controls the refactoring-intelligence layer: the structured Extract Class /
diff --git a/docs/start/DASHBOARD.md b/docs/start/DASHBOARD.md
index 340fe8535..c4277b578 100644
--- a/docs/start/DASHBOARD.md
+++ b/docs/start/DASHBOARD.md
@@ -259,7 +259,8 @@ anywhere.
The commit table led by repo-relative review priority, a supporting diff-shape
score distribution, a
code-evolution chart, commit-category breakdowns, and AI-agent provenance
-badges plus their trend over time where the commits carry agent trailers. The
+badges plus their trend over time, shown as agent, human-attested and unknown
+commits with the agent share of covered commits beside its coverage. The
risk model is documented in
[docs/layers/CHANGE_RISK.md](../layers/CHANGE_RISK.md).
diff --git a/packages/api-client/src/git.ts b/packages/api-client/src/git.ts
index a5d83934a..7bc69e62e 100644
--- a/packages/api-client/src/git.ts
+++ b/packages/api-client/src/git.ts
@@ -120,7 +120,7 @@ export async function getCommitsPage(
repoId: string,
options: {
sort?: "risk" | "date";
- authorship?: "all" | "agent" | "human";
+ authorship?: "all" | "agent" | "human" | "unknown";
/** Narrows the whole repository, not the page: the high review-priority
* band, or bug-fix commits. */
kind?: "all" | "high" | "fixes";
diff --git a/packages/api-client/src/types/git.ts b/packages/api-client/src/types/git.ts
index 7660bf473..7fae86442 100644
--- a/packages/api-client/src/types/git.ts
+++ b/packages/api-client/src/types/git.ts
@@ -41,11 +41,14 @@ export interface GitMetadataResponse {
commit_count_capped?: boolean;
original_path?: string | null;
test_gap?: boolean | null;
- // Agent-provenance rollup (deterministic local-git channels). The pct is
- // null/absent for indexes built before the provenance-aware walk.
- agent_commit_count?: number;
+ // Agent-provenance rollup. The pct (0-1) is the agent share of commits with a
+ // known source, null below the coverage floor; every field is null when
+ // attribution is off for the repository.
+ agent_commit_count?: number | null;
agent_authored_pct?: number | null;
- agent_tier_counts?: Record<string, number>;
+ agent_tier_counts?: Record<string, number> | null;
+ attribution_coverage?: number | null;
+ agent_share_suppressed?: string | null;
}
export interface HotspotResponse {
@@ -127,11 +130,13 @@ export interface CommitResponse {
author_experience?: number | null;
/** Commits by this author across the indexed history (identities folded). */
author_commit_count?: number | null;
- /** Coding-agent attribution; null for human-authored commits. */
+ /** Coding-agent attribution; null for human-attested and unknown commits. */
agent_name?: string | null;
/** 1 = near-autonomous bot, 2 = human-driven agent, 3 = assisted. */
agent_autonomy_tier?: number | null;
agent_confidence?: string | null;
+ /** agent / human_attested / unknown; null when attribution is off. */
+ attribution?: "agent" | "human_attested" | "unknown" | null;
}
export interface RiskDriverResponse {
@@ -195,19 +200,27 @@ export interface CommitDetailResponse extends CommitResponse {
health?: CommitHealthResponse | null;
}
-export interface AgentTrendBucket {
- month: string;
+/** Commits by attribution label; the agent share is of covered commits and
+ * null below the coverage floor. Percentages are 0-100. */
+export interface AttributionShareFields {
total_commits: number;
agent_commits: number;
- agent_pct: number;
+ human_attested_commits: number;
+ unknown_commits: number;
+ coverage_pct: number | null;
+ agent_pct_of_covered: number | null;
+ suppressed_reason: string | null;
+}
+
+export interface AgentTrendBucket extends AttributionShareFields {
+ month: string;
tier_counts: Record<string, number>;
}
-export interface AgentTrend {
+export interface AgentTrend extends AttributionShareFields {
+ enabled: boolean;
+ coverage_floor_pct: number;
buckets: AgentTrendBucket[];
- total_commits: number;
- agent_commits: number;
- agent_pct: number;
agent_names: { name: string; count: number }[];
}
@@ -252,7 +265,10 @@ export interface CommitStats {
total_commits: number;
high_priority_count: number;
fix_commit_count: number;
- agent_commit_count: number;
+ /** Null, like the two figures below, when attribution is off. */
+ agent_commit_count: number | null;
+ agent_pct_of_covered?: number | null;
+ attribution_coverage_pct?: number | null;
avg_entropy: number;
/** Binned on the raw score, not the percentile — percentile ranks are
* uniform by construction, so only the raw axis has a shape to draw. */
diff --git a/packages/api-client/src/types/ownership.ts b/packages/api-client/src/types/ownership.ts
index dc331fffb..0e0d4ff61 100644
--- a/packages/api-client/src/types/ownership.ts
+++ b/packages/api-client/src/types/ownership.ts
@@ -63,15 +63,6 @@ export interface OwnerProfileResponse {
/** Uncapped count behind the co_authors slice (for "+N more"). */
co_authors_total?: number;
commit_categories: Record<string, number>;
- /** Agent activity on owned files; null when nothing attributed. */
- agent_collab?: OwnerAgentCollab | null;
-}
-
-export interface OwnerAgentCollab {
- files_with_agent_commits: number;
- agent_commit_count: number;
- agent_share_pct: number | null;
- tier_counts: Record<string, number>;
}
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/repowise/cli/commands/attribution_cmd.py b/packages/cli/src/repowise/cli/commands/attribution_cmd.py
new file mode 100644
index 000000000..e77fc0cc8
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/attribution_cmd.py
@@ -0,0 +1,210 @@
+"""``repowise attribution``: inspect and clear AI attribution for a repository.
+
+``status`` shows what is switched on (effective value beside the repo and user
+values), for which agents, and how much of the indexed history has a known
+source. ``purge`` deletes the attribution the local index derived. Capture is
+not wired yet, so there is no sidecar, cursor or Repowise-written note to
+remove; third-party git-ai notes are never touched.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console, repo_index_session, resolve_repo_path, run_async
+from repowise.cli.output import emit_json, format_option
+
+
+def _settings(repo_path: Path) -> Any:
+ from repowise.cli.agent_targets.registry import list_target_ids
+ from repowise.core.attribution import load_attribution_settings
+
+ return load_attribution_settings(repo_path, known_agents=list_target_ids())
+
+
+async def _label_counts(repo_path: Path) -> dict[str, int] | None:
+ """Indexed commits by attribution label, or ``None`` without an index."""
+ from sqlalchemy import func, select
+
+ from repowise.core.attribution import commit_label
+ from repowise.core.persistence.models import GitCommit
+
+ async with repo_index_session(repo_path) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ rows = await session.execute(
+ select(GitCommit.attribution, GitCommit.agent_name, func.count())
+ .where(GitCommit.repository_id == repo_id)
+ .group_by(GitCommit.attribution, GitCommit.agent_name)
+ )
+ counts = {"agent": 0, "human_attested": 0, "unknown": 0}
+ for attribution, agent_name, n in rows.all():
+ counts[commit_label(attribution, agent_name)] += int(n)
+ return counts
+
+
+_DEFAULTS: dict[str, Any] = {"enabled": True, "capture": "off", "agents": ()}
+
+
+def _fmt(value: Any) -> str:
+ if isinstance(value, (tuple, list)):
+ return ", ".join(value) or "none"
+ return str(value).lower() if isinstance(value, bool) else str(value)
+
+
+def _explanations(settings: Any) -> list[str]:
+ """Plain-words reasons wherever a value a config file sets is not the effective one."""
+ reasons: list[str] = []
+ layers = (
+ ("repo", settings.repo, "user", settings.user),
+ ("user", settings.user, "repo", settings.repo),
+ )
+ for key in ("enabled", "capture", "agents"):
+ effective = getattr(settings, key)
+ for name, layer, other_name, other in layers:
+ value = getattr(layer, key)
+ if value is None or (tuple(value) if key == "agents" else value) == effective:
+ continue
+ other_value = getattr(other, key)
+ if key != "enabled" and not settings.enabled:
+ why = "attribution is switched off"
+ elif key != "enabled" and settings.do_not_track:
+ why = "DO_NOT_TRACK is set"
+ elif key == "agents" and settings.capture == "off":
+ why = "capture is off, so no agent is captured"
+ elif other_value is None:
+ why = (
+ f"the {other_name} config does not set it, so the default"
+ f" ({_fmt(_DEFAULTS[key])}) applies there and the stricter value wins"
+ )
+ else:
+ why = (
+ f"the {other_name} config sets {_fmt(other_value)}"
+ " and the stricter value wins"
+ )
+ reasons.append(
+ f"{key}: the {name} config sets {_fmt(value)}, but {_fmt(effective)} applies"
+ f" because {why}."
+ )
+ return reasons
+
+
+def _layer(layer: Any) -> dict[str, Any]:
+ return {
+ "enabled": layer.enabled,
+ "capture": layer.capture,
+ "agents": list(layer.agents) if layer.agents is not None else None,
+ }
+
+
[email protected](name="attribution")
+def attribution_group() -> None:
+ """Inspect and clear AI attribution for this repository."""
+
+
+@attribution_group.command(name="status")
[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))
+@format_option(choices=("table", "json"))
+def attribution_status(path: str | None, fmt: str) -> None:
+ """Show what is on, for which agents, and the provenance coverage."""
+ from repowise.core.attribution import attribution_share
+
+ repo_path = resolve_repo_path(path)
+ settings = _settings(repo_path)
+ counts = run_async(_label_counts(repo_path)) if settings.enabled else None
+ share = (
+ attribution_share(counts["agent"], counts["human_attested"], sum(counts.values()))
+ if counts is not None
+ else None
+ )
+ if fmt == "json":
+ emit_json(
+ {
+ "effective": {
+ "enabled": settings.enabled,
+ "capture": settings.capture,
+ "agents": list(settings.agents),
+ },
+ "repo": _layer(settings.repo),
+ "user": _layer(settings.user),
+ "do_not_track": settings.do_not_track,
+ "errors": list(settings.errors),
+ "explanations": _explanations(settings),
+ "commits": counts,
+ "coverage": share.coverage if share else None,
+ "agent_share_of_covered": share.agent_share if share else None,
+ "suppressed_reason": share.suppressed_reason if share else None,
+ }
+ )
+ return
+
+ def _show(value: Any) -> str:
+ return "[dim]unset[/dim]" if value is None else _fmt(value)
+
+ console.print("[bold]AI attribution[/bold]")
+ for key in ("enabled", "capture", "agents"):
+ console.print(
+ f" {key:<8} {_show(getattr(settings, key))}"
+ f" (repo: {_show(getattr(settings.repo, key))},"
+ f" user: {_show(getattr(settings.user, key))})"
+ )
+ if settings.do_not_track:
+ console.print(" DO_NOT_TRACK is set: capture stays off.")
+ for error in settings.errors:
+ console.print(f" [yellow]![/yellow] {error} (treated as the strictest value)")
+ for reason in _explanations(settings):
+ console.print(f" [dim]{reason}[/dim]")
+ if not settings.enabled:
+ console.print(" Nothing about AI is stored or shown for this repository.")
+ elif counts is None:
+ console.print(" No index yet. Run `repowise init` to read public attribution markers.")
+ else:
+ console.print(
+ f" commits {counts['agent']} agent, {counts['human_attested']} human-attested,"
+ f" {counts['unknown']} unknown"
+ )
+ if share is not None:
+ console.print(f" share {share.summary()}")
+
+
+async def _purge(repo_path: Path) -> bool:
+ from repowise.core.persistence.crud import clear_attribution
+
+ async with repo_index_session(repo_path) as opened:
+ if opened is None:
+ return False
+ session, repo_id = opened
+ await clear_attribution(session, repo_id)
+ return True
+
+
+@attribution_group.command(name="purge")
[email protected]("path", required=False, type=click.Path(exists=True, file_okay=False))
[email protected]("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.")
+def attribution_purge(path: str | None, yes: bool) -> None:
+ """Delete the AI attribution derived into the local index.
+
+ Clears every commit label and file rollup. Git history, trailers and notes
+ in the repository are left as they are.
+ """
+ repo_path = resolve_repo_path(path)
+ if not yes and not click.confirm(
+ "Delete all AI attribution derived into this repository's index?", default=False
+ ):
+ console.print("Nothing deleted.")
+ return
+ if not run_async(_purge(repo_path)):
+ console.print("No index found; nothing to delete.")
+ return
+ console.print("[green]✓[/green] AI attribution deleted from the local index.")
+ if _settings(repo_path).enabled:
+ console.print(
+ " Attribution is still enabled: `repowise update` labels new commits, and a"
+ " full re-index labels past ones again. Set `attribution.enabled: false` in"
+ " .repowise/config.yaml to keep it off."
+ )
+
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index f7ce2d38f..c15a5d7dc 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -143,6 +143,7 @@ async def _backfill_git(
)
from repowise.core.persistence import get_session
from repowise.core.persistence.crud import (
+ clear_attribution_if_disabled,
recompute_git_percentiles,
upsert_git_commits_bulk,
upsert_git_metadata_bulk,
@@ -172,6 +173,7 @@ async def _backfill_git(
# (Foundation 1 only wrote them on the full orchestrator index).
if summary.commit_rows:
await upsert_git_commits_bulk(session, repo_id, summary.commit_rows)
+ await clear_attribution_if_disabled(session, repo_id)
console.print(
f"Git tier upgraded to FULL: [cyan]{summary.files_indexed}[/cyan] files "
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index c6ab185ed..8ca3fdde3 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -87,6 +87,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("export", "export_cmd:export_command"),
("hook", "hook_cmd:hook_group"),
("agents", "agents_cmd:agents_group"),
+ ("attribution", "attribution_cmd:attribution_group"),
("uninstall", "uninstall_cmd:uninstall_command"),
("status", "status_cmd:status_command"),
("next", "next_cmd:next_command"),
diff --git a/packages/core/alembic/versions/0109_attribution_three_state.py b/packages/core/alembic/versions/0109_attribution_three_state.py
new file mode 100644
index 000000000..a9b8332d1
--- /dev/null
+++ b/packages/core/alembic/versions/0109_attribution_three_state.py
@@ -0,0 +1,55 @@
+"""Three-state commit attribution and the per-file known-source count.
+
+``git_commits.attribution`` is ``agent``, ``human_attested`` or ``unknown``; a
+commit without a marker used to read as human. ``git_metadata`` gains
+``attribution_known_count`` and ``agent_authored_pct`` becomes the agent share
+of those known commits. Existing rows are rewritten to the same meaning: before
+this revision no source could attest a human, so every agent commit was the
+whole known set.
+
+Local SQLite stores never run Alembic; ``init_db`` adds the columns there and
+readers derive the label for NULL rows until the next index.
+
+Revision ID: 0109
+Revises: 0108
+Create Date: 2026-10-14
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0109"
+down_revision: str | None = "0108"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column("git_commits", sa.Column("attribution", sa.String(16), nullable=True))
+ op.add_column(
+ "git_metadata",
+ sa.Column("attribution_known_count", sa.Integer, nullable=False, server_default="0"),
+ )
+ op.execute(
+ "UPDATE git_commits SET attribution = "
+ "CASE WHEN agent_name IS NOT NULL THEN 'agent' ELSE 'unknown' END"
+ )
+ op.execute(
+ "UPDATE git_metadata SET attribution_known_count = agent_commit_count, "
+ "agent_authored_pct = CASE WHEN agent_commit_count > 0 THEN 1.0 ELSE NULL END"
+ )
+
+
+def downgrade() -> None:
+ op.execute(
+ "UPDATE git_metadata SET agent_authored_pct = "
+ "CASE WHEN commit_count_total > 0 "
+ "THEN CAST(agent_commit_count AS FLOAT) / commit_count_total ELSE NULL END"
+ )
+ op.drop_column("git_metadata", "attribution_known_count")
+ op.drop_column("git_commits", "attribution")
diff --git a/packages/core/src/repowise/core/analysis/owners.py b/packages/core/src/repowise/core/analysis/owners.py
index 7cb9de314..9f26da065 100644
--- a/packages/core/src/repowise/core/analysis/owners.py
+++ b/packages/core/src/repowise/core/analysis/owners.py
@@ -97,12 +97,6 @@ class OwnerAccumulator:
dead_code_files: set[str] = field(default_factory=set)
dead_code_lines: int = 0
- # Agent-provenance rollup across primary-owned files.
- owned_files_with_agents: int = 0
- owned_agent_commits: int = 0
- owned_attributed_commits: int = 0 # total commits on owned files with a rollup
- owned_agent_tier_counts: Counter[str] = field(default_factory=Counter)
-
# co-author tally: other_key -> shared file count
coauthor_shared: Counter[str] = field(default_factory=Counter)
coauthor_meta: dict[str, tuple[str, str | None]] = field(default_factory=dict)
@@ -232,16 +226,6 @@ def aggregate_owners(
primary.module_hotspots[module] += 1
if (row_field(m, "bus_factor") or 0) <= 1:
primary.bus_factor_risk_files += 1
- # agent_authored_pct is None on rows indexed before provenance
- # existed; skip those so the agent share stays honest.
- if row_field(m, "agent_authored_pct") is not None:
- primary.owned_attributed_commits += row_field(m, "commit_count_total") or 0
- agent_commits = row_field(m, "agent_commit_count") or 0
- if agent_commits > 0:
- primary.owned_files_with_agents += 1
- primary.owned_agent_commits += agent_commits
- for tier, n in json_field(m, "agent_tier_counts_json", {}).items():
- primary.owned_agent_tier_counts[str(tier)] += int(n)
# Co-author tally: each pair of distinct touchers shares this file.
for i, a in enumerate(touchers):
diff --git a/packages/core/src/repowise/core/attribution.py b/packages/core/src/repowise/core/attribution.py
new file mode 100644
index 000000000..19a708c61
--- /dev/null
+++ b/packages/core/src/repowise/core/attribution.py
@@ -0,0 +1,298 @@
+"""AI attribution settings and the honest share arithmetic every surface uses.
+
+Settings live under ``attribution:`` in the repo's ``.repowise/config.yaml``
+and in the user's ``~/.repowise/config.yaml``; per key the stricter value wins:
+
+* ``enabled`` (default true): read public git markers (bot authors, trailers,
+ footers, git-ai notes, Agent Trace files already in the repo). ``false`` in
+ either file means nothing about AI is stored or shown.
+* ``capture``: ``off`` (default) < ``local`` < ``notes``; the lower one wins and
+ ``DO_NOT_TRACK`` forces ``off``.
+* ``agents``: which agents are captured; the intersection of both lists.
+
+An unset key takes its default before the comparison, so capture needs both the
+repo and the user to opt in. An invalid value counts as the strictest value.
+
+Commits carry a three-state label: ``agent``, ``human_attested`` (only from an
+explicit human record) or ``unknown``. Unknown is never counted as human: an AI
+share is the agent share of *covered* commits (agent plus human-attested), shown
+with its coverage and withheld below :data:`COVERAGE_FLOOR`.
+"""
+
+from __future__ import annotations
+
+import functools
+from collections.abc import Iterable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+AGENT = "agent"
+HUMAN_ATTESTED = "human_attested"
+UNKNOWN = "unknown"
+
+CAPTURE_LEVELS: tuple[str, ...] = ("off", "local", "notes")
+
+#: Below this share of commits with a known source, an AI share is withheld.
+COVERAGE_FLOOR = 0.30
+
+SUPPRESSED_NO_COMMITS = "no_commits"
+SUPPRESSED_LOW_COVERAGE = "coverage_below_floor"
+
+_SECTION = "attribution"
+
+# Each config problem is logged once per process, not on every request.
+_warned: set[str] = set()
+
+
+@dataclass(frozen=True)
+class AttributionLayer:
+ """What one config file says. ``None`` means the key is not set there."""
+
+ enabled: bool | None = None
+ capture: str | None = None
+ agents: tuple[str, ...] | None = None
+
+
+@dataclass(frozen=True)
+class AttributionSettings:
+ """The effective settings, with the two layers they came from."""
+
+ enabled: bool = True
+ capture: str = "off"
+ agents: tuple[str, ...] = ()
+ repo: AttributionLayer = AttributionLayer()
+ user: AttributionLayer = AttributionLayer()
+ do_not_track: bool = False
+ errors: tuple[str, ...] = ()
+
+
+def user_config_path() -> Path:
+ """Resolved per call so tests can redirect ``Path.home``."""
+ return Path.home() / ".repowise" / "config.yaml"
+
+
+def _read_yaml(path: Path) -> tuple[dict[str, Any], str | None]:
+ if not path.is_file():
+ return {}, None
+ try:
+ import yaml # type: ignore[import-untyped]
+
+ data = yaml.safe_load(path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ return {}, f"{path}: could not be read ({exc})"
+ if data is None:
+ return {}, None
+ if not isinstance(data, dict):
+ return {}, f"{path}: expected a YAML mapping"
+ return data, None
+
+
+def _parse_layer(
+ config: dict[str, Any], source: str, known_agents: Iterable[str] | None
+) -> tuple[AttributionLayer, list[str]]:
+ block = config.get(_SECTION)
+ if block is None:
+ return AttributionLayer(), []
+ if not isinstance(block, dict):
+ return AttributionLayer(enabled=False), [f"{source}: attribution must be a mapping"]
+ errors: list[str] = []
+ enabled = block.get("enabled")
+ if enabled is not None and not isinstance(enabled, bool):
+ errors.append(f"{source}: attribution.enabled must be true or false")
+ enabled = False
+ capture = block.get("capture")
+ if capture is not None:
+ capture = str(capture).strip().lower()
+ if capture not in CAPTURE_LEVELS:
+ levels = ", ".join(CAPTURE_LEVELS)
+ errors.append(f"{source}: attribution.capture must be one of {levels}")
+ capture = "off"
+ agents: tuple[str, ...] | None = None
+ raw_agents = block.get("agents")
+ if raw_agents is not None:
+ if isinstance(raw_agents, str):
+ raw_agents = [raw_agents]
+ if not isinstance(raw_agents, list):
+ errors.append(f"{source}: attribution.agents must be a list")
+ raw_agents = []
+ known = set(known_agents) if known_agents is not None else None
+ kept: list[str] = []
+ for name in raw_agents:
+ agent = str(name).strip()
+ if known is not None and agent not in known:
+ errors.append(f"{source}: unknown agent {agent!r} in attribution.agents")
+ continue
+ if agent and agent not in kept:
+ kept.append(agent)
+ agents = tuple(kept)
+ return AttributionLayer(enabled=enabled, capture=capture, agents=agents), errors
+
+
+def _do_not_track() -> bool:
+ from repowise.core.platform.telemetry import _env_truthy
+
+ return _env_truthy("DO_NOT_TRACK")
+
+
+def load_attribution_settings(
+ repo_path: Path | str | None, *, known_agents: Iterable[str] | None = None
+) -> AttributionSettings:
+ """Resolve the effective settings for *repo_path* (``None``: user file only).
+
+ *known_agents* validates ``attribution.agents``; the CLI passes the agent
+ target ids. Without it any name is accepted.
+ """
+ errors: list[str] = []
+ repo_layer = AttributionLayer()
+ if repo_path is not None:
+ repo_file = Path(repo_path) / ".repowise" / "config.yaml"
+ data, err = _read_yaml(repo_file)
+ if err:
+ errors.append(err)
+ repo_layer = AttributionLayer(enabled=False)
+ else:
+ repo_layer, layer_errors = _parse_layer(data, str(repo_file), known_agents)
+ errors.extend(layer_errors)
+ user_file = user_config_path()
+ data, err = _read_yaml(user_file)
+ if err:
+ errors.append(err)
+ user_layer = AttributionLayer(enabled=False)
+ else:
+ user_layer, layer_errors = _parse_layer(data, str(user_file), known_agents)
+ errors.extend(layer_errors)
+
+ layers = (repo_layer, user_layer)
+ enabled = all(layer.enabled is not False for layer in layers)
+ capture = min((layer.capture or "off" for layer in layers), key=CAPTURE_LEVELS.index)
+ agent_sets = [layer.agents or () for layer in layers]
+ agents = tuple(a for a in agent_sets[0] if a in agent_sets[1])
+ for error in errors:
+ if error not in _warned:
+ _warned.add(error)
+ import structlog
+
+ structlog.get_logger(__name__).warning(
+ "attribution_config_invalid", detail=error, treated_as="strictest value"
+ )
+ dnt = _do_not_track()
+ if dnt or not enabled:
+ capture = "off"
+ return AttributionSettings(
+ enabled=enabled,
+ capture=capture,
+ agents=agents if capture != "off" else (),
+ repo=repo_layer,
+ user=user_layer,
+ do_not_track=dnt,
+ errors=tuple(errors),
+ )
+
+
+def _stamp(path: Path) -> tuple[int, int]:
+ """``(mtime_ns, size)``: changes on any rewrite, even one inside a second."""
+ try:
+ st = path.stat()
+ return st.st_mtime_ns, st.st_size
+ except OSError:
+ return 0, -1
+
+
[email protected]_cache(maxsize=64)
+def _enabled_cached(
+ repo_path: str | None,
+ _repo_stamp: tuple[int, int],
+ _user_file: str,
+ _user_stamp: tuple[int, int],
+) -> bool:
+ return load_attribution_settings(repo_path).enabled
+
+
+def attribution_enabled(repo_path: Path | str | None) -> bool:
+ """Whether AI attribution may be stored or shown for *repo_path*.
+
+ Cached on both files' (mtime_ns, size), so per-request callers pay a stat,
+ not a parse.
+ A value that is not a path (no checkout) reads the user file only.
+ """
+ if not isinstance(repo_path, (str, Path)) or not str(repo_path):
+ repo_path = None
+ repo_stamp = (
+ _stamp(Path(repo_path) / ".repowise" / "config.yaml") if repo_path is not None else (0, -1)
+ )
+ key = str(repo_path) if repo_path is not None else None
+ user_file = user_config_path()
+ return _enabled_cached(key, repo_stamp, str(user_file), _stamp(user_file))
+
+
+def commit_label(attribution: str | None, agent_name: str | None) -> str:
+ """A stored commit's three-state label; rows written before the label are derived."""
+ if attribution in (AGENT, HUMAN_ATTESTED, UNKNOWN):
+ return attribution
+ return AGENT if agent_name else UNKNOWN
+
+
+@dataclass(frozen=True)
+class AttributionShare:
+ """Agent share of covered commits, with coverage and the unknown band.
+
+ ``coverage`` and ``agent_share`` are fractions in 0..1. ``agent_share`` is
+ ``None`` with a ``suppressed_reason`` when coverage is below the floor.
+ """
+
+ total: int
+ agent: int
+ human_attested: int
+ unknown: int
+ coverage: float | None
+ agent_share: float | None
+ suppressed_reason: str | None
+
+ def summary(self) -> str:
+ """One line for compact surfaces (MCP, CLI)."""
+ cov = f"{round((self.coverage or 0.0) * 100)}%"
+ if self.agent_share is None:
+ return f"withheld: coverage {cov} is below {round(COVERAGE_FLOOR * 100)}%"
+ return f"at least {round(self.agent_share * 100)}% of covered commits, coverage {cov}"
+
+
+def attribution_share(agent: int, human_attested: int, total: int) -> AttributionShare:
+ """The honest AI share over *total* commits.
+
+ Known sources never exceed *total*; a caller with inconsistent counts (rows
+ from an older index) gets them clamped rather than a share above 100%.
+ """
+ total = max(int(total or 0), 0)
+ agent = min(max(int(agent or 0), 0), total)
+ human_attested = min(max(int(human_attested or 0), 0), total - agent)
+ known = agent + human_attested
+ if total == 0:
+ return AttributionShare(0, 0, 0, 0, None, None, SUPPRESSED_NO_COMMITS)
+ coverage = known / total
+ share: float | None = agent / known if known else None
+ reason = None
+ if coverage < COVERAGE_FLOOR:
+ share, reason = None, SUPPRESSED_LOW_COVERAGE
+ return AttributionShare(
+ total=total,
+ agent=agent,
+ human_attested=human_attested,
+ unknown=total - known,
+ coverage=coverage,
+ agent_share=share,
+ suppressed_reason=reason,
+ )
+
+
+def file_share(
+ agent_commit_count: int | None, known_count: int | None, total: int | None
+) -> AttributionShare:
+ """:func:`attribution_share` from a ``git_metadata`` row's stored counts.
+
+ A row indexed before the known count existed has it at 0; its agent commits
+ are still known, so the known count never reads below them.
+ """
+ agent = int(agent_commit_count or 0)
+ known = max(int(known_count or 0), agent)
+ return attribution_share(agent, known - agent, int(total or 0))
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index 06f5c958b..b73ee604d 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -18,7 +18,7 @@ import structlog
if TYPE_CHECKING:
from .git_indexer import RenameTrail, _CommitRec
- from .git_indexer.agent_provenance import AgentProvenance
+ from .git_indexer.agent_provenance import AgentProvenance, GitAiNote
logger = structlog.get_logger(__name__)
@@ -50,28 +50,34 @@ def _count_non_merge_commits(repo: object) -> int | None:
return None
-def load_git_ai_note_agents(repo: object, commit_limit: int | None) -> dict[str, str]:
- """Map ``commit_sha → agent`` from git-ai authorship notes (``refs/notes/ai``).
+def load_git_ai_note_agents(repo: object, commit_limit: int | None) -> dict[str, GitAiNote]:
+ """Map ``commit_sha → GitAiNote`` from git-ai authorship notes (``refs/notes/ai``).
- A repo without the ref costs one ``for-each-ref`` and gets ``{}``. The
- notes walk covers *commit_limit* commits, or the whole history with
- ``None``. Any failure returns ``{}``: a notes read must never break the git
- index. See the git-ai standard v3.0.0 for the note format.
+ Only notes that name an agent or attest a human are kept. A repo without
+ the ref costs one ``for-each-ref`` and gets ``{}``, as does a repo with
+ ``attribution.enabled: false``. The notes walk covers *commit_limit*
+ commits, or the whole history with ``None``. Any failure returns ``{}``: a
+ notes read must never break the git index. See the git-ai standard v3.0.0
+ for the note format.
"""
+ from repowise.core.attribution import attribution_enabled
+
from .git_indexer import _FIELD_SEP, _RECORD_SEP
- from .git_indexer.agent_provenance import _agent_from_git_ai_note
+ from .git_indexer.agent_provenance import parse_git_ai_note
- agents: dict[str, str] = {}
+ if not attribution_enabled(getattr(repo, "working_tree_dir", None)):
+ return {}
+ notes: dict[str, GitAiNote] = {}
for chunk in _git_ai_notes_log(repo, commit_limit).split(_RECORD_SEP):
if not chunk.strip():
continue
- sha, sep, note = chunk.partition(_FIELD_SEP)
+ sha, sep, raw = chunk.partition(_FIELD_SEP)
if not sep:
continue
- agent = _agent_from_git_ai_note(note)
- if agent:
- agents[sha.strip()] = agent
- return agents
+ note = parse_git_ai_note(raw)
+ if note.agent or note.human:
+ notes[sha.strip()] = note
+ return notes
def _git_ai_notes_log(repo: object, commit_limit: int | None) -> str:
@@ -329,29 +335,19 @@ class _CommitLabeler:
) -> None:
from .git_indexer.agent_provenance import AgentProvenanceClassifier, AgentTraceIndex
- self._note_agents = load_git_ai_note_agents(repo, note_depth)
- self._trace_index = trace_index if trace_index is not None else AgentTraceIndex.load(repo)
self._classifier = classifier if classifier is not None else AgentProvenanceClassifier()
+ enabled = getattr(self._classifier, "enabled", True)
+ self._notes = load_git_ai_note_agents(repo, note_depth) if enabled else {}
+ if not enabled:
+ trace_index = AgentTraceIndex()
+ self._trace_index = trace_index if trace_index is not None else AgentTraceIndex.load(repo)
self._sink = sink
def label(self, header: dict, changes: list[tuple[str, int, int]]) -> AgentProvenance:
- # The agent-trace channel checks overlap with the commit's changed paths.
- trace_hit = (
- self._trace_index.resolve( # type: ignore[attr-defined]
- header["sha"], header["parents"], {t for t, _, _ in changes}
- )
- if self._trace_index
- else None
- )
- prov: AgentProvenance = self._classifier.classify( # type: ignore[attr-defined]
- header["author_name"],
- header["author_email"],
- header["committer_name"],
- header["committer_email"],
- f"{header['subject']}\n{header['body']}",
- note_agent=self._note_agents.get(header["sha"]),
- trace_agent=trace_hit[0] if trace_hit else None,
- trace_confidence=trace_hit[1] if trace_hit else "high",
+ from .git_indexer.agent_provenance import classify_commit
+
+ prov, trace_hit = classify_commit(
+ self._classifier, header, {t for t, _, _ in changes}, self._notes, self._trace_index
)
if self._sink is not None:
self._sink.append(_sink_row(header, changes, prov, trace_hit))
@@ -376,6 +372,7 @@ def _sink_row(
"agent_autonomy_tier": prov.autonomy_tier,
"agent_channel": prov.channel,
"agent_confidence": prov.confidence,
+ "attribution": prov.attribution,
# Model id only when the trace channel actually won: a note
# or service-identity match can outrank the trace above, and
# only the trace record carries a model.
@@ -424,6 +421,7 @@ class _FileBuckets:
deleted=deleted,
agent=prov.agent,
agent_tier=prov.autonomy_tier,
+ attribution=prov.attribution,
pure_move=target in pure_moves,
)
)
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/README.md b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
index 2ee84e5b4..7ff09e02a 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
@@ -154,10 +154,17 @@ Design rules:
(`service_emails`, `footer_patterns`, `coauthor_patterns`) — additive on top
of the built-ins, malformed entries skipped with a warning.
-Persisted as five nullable columns on `git_commits`
-(`agent_name`/`agent_autonomy_tier`/`agent_channel`/`agent_confidence`/`agent_model_id`)
+Every commit also carries a three-state `attribution` label: `agent`,
+`human_attested` (only from an explicit human record such as git-ai `h_` keys
+or an Agent Trace `human` contributor) or `unknown`. Shares are always of the
+commits with a known source and travel with that coverage, withheld below 30%
+(`repowise.core.attribution`). With `attribution.enabled: false` the walk
+labels nothing and reads no notes or trace files.
+
+Persisted as six nullable columns on `git_commits`
+(`agent_name`/`agent_autonomy_tier`/`agent_channel`/`agent_confidence`/`agent_model_id`/`attribution`)
and a per-file rollup on `git_metadata` (`agent_commit_count`,
-`agent_authored_pct`, `agent_tier_counts_json` at the commit level;
+`attribution_known_count`, `agent_authored_pct`, `agent_tier_counts_json` at the commit level;
`agent_line_count`, `agent_line_model_json` at the line level), surfaced in the
`/git-metadata` file view and the MCP `get_context` ownership block.
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.py
index b4a2b56b5..fda1a4a9e 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
@@ -31,8 +31,11 @@ Three cross-cutting channels ride the same rule set:
* a ``Generated-by:`` trailer (Apache's AI-attribution footer) naming a
recognized agent — Tier 2 (``generated_by_trailer`` channel).
-Precedence is tier order (1 > 2 > 3); first match wins. A commit with no
-match is human (``None``). Every pattern is anchored to a *service identity*
+Precedence is tier order (1 > 2 > 3); first match wins. Every commit gets a
+three-state label (:mod:`repowise.core.attribution`): ``agent`` on a match,
+``human_attested`` only when a git-ai note's attestation names nothing but
+``h_`` human keys or an agent-trace record says ``human``, and ``unknown``
+otherwise. No marker is never read as human. Every pattern is anchored to a *service identity*
(bot login, service e-mail, exact footer phrase) — never a bare name. A loose
name pattern is how a human contributor named "Devin" gets misclassified as
the Devin agent; a false "agent-authored" label on a human commit is worse
@@ -79,9 +82,11 @@ __all__ = [
"AgentProvenance",
"AgentProvenanceClassifier",
"AgentTraceIndex",
+ "GitAiNote",
"_agent_from_git_ai_note",
"agent_from_identity",
"classifier_from_repo_config",
+ "parse_git_ai_note",
]
@@ -217,38 +222,85 @@ def _normalize_agent_token(value: str, *, allow_slug: bool) -> str | None:
return slug or None
-def _agent_from_git_ai_note(note: str) -> str | None:
- """Resolve the dominant agent from a git-ai authorship note.
-
- A note (``refs/notes/ai``, git-ai standard v3.0.0) is
- ``<attestation>\\n---\\n<json metadata>``. We read
- ``sessions.<id>.agent_id.tool`` from the JSON metadata and return the tool
- owning the most sessions, normalized to our agent label. A tie between
- distinct tools returns ``None`` (ambiguous — precision-first; per-line
- dominance from the attestation section is the upgrade path). Any parse
- failure returns ``None``: a malformed note is never a signal.
+@dataclass(frozen=True)
+class GitAiNote:
+ """What one git-ai authorship note attests: its dominant agent, or that only
+ known humans wrote the attested lines."""
+
+ agent: str | None = None
+ human: bool = False
+ # Files the attestation names; a human attestation counts only when it
+ # covers every path the commit changed.
+ paths: frozenset[str] = frozenset()
+
+
+# A note is a few KB; past this it is not read (a hostile or broken ref must
+# not stall the walk).
+_GIT_AI_NOTE_MAX_CHARS = 1_000_000
+
+# Attestation keys (git-ai standard v3.0.0): ``s_<hex>::t_<hex>`` is an AI
+# session and trace, ``h_<hex>`` a known human, a bare 16-hex key a legacy AI
+# prompt. Anything else is ignored.
+_GIT_AI_HUMAN_KEY = re.compile(r"h_[0-9a-f]+")
+_GIT_AI_AI_KEY = re.compile(r"s_[0-9a-f]+(?:::t_[0-9a-f]+)?|[0-9a-f]{16}")
+
+
+def parse_git_ai_note(note: str) -> GitAiNote:
+ """Read a git-ai authorship note (``refs/notes/ai``, standard v3.0.0).
+
+ A note is ``<attestation>\\n---\\n<json metadata>``. The attestation has a
+ file path at column 0 and indented ``<key> <ranges>`` lines below it. The
+ agent is the tool owning the most ``sessions`` (``prompts`` for notes that
+ predate sessions), read from ``agent_id.tool``; a tie between tools is
+ ambiguous and yields no agent (precision first). ``human`` is set only when
+ the attestation carries ``h_`` keys and no AI key, and the metadata names no
+ agent. Identities in ``humans`` / ``human_author`` are never read. A
+ malformed or oversized note yields the empty result: it is never a signal.
+ The divider is the first column-0 ``---`` line, which ends the attestation.
"""
- if not note:
- return None
+ if not note or len(note) > _GIT_AI_NOTE_MAX_CHARS:
+ return GitAiNote()
try:
lines = note.splitlines()
- div = max((i for i, ln in enumerate(lines) if ln.strip() == "---"), default=-1)
+ div = next((i for i, ln in enumerate(lines) if ln.rstrip() == "---"), -1)
if div < 0:
- return None
- data = json.loads("\n".join(lines[div + 1 :]))
+ return GitAiNote()
+ # raw_decode: the metadata object ends the note; anything after it is ignored.
+ data, _ = json.JSONDecoder().raw_decode("\n".join(lines[div + 1 :]).lstrip())
+ if not isinstance(data, dict):
+ return GitAiNote()
+ entries = data.get("sessions") or data.get("prompts") or {}
counts: dict[str, int] = {}
- for sess in (data.get("sessions") or {}).values():
- tool = ((sess or {}).get("agent_id") or {}).get("tool")
+ for entry in entries.values() if isinstance(entries, dict) else []:
+ tool = ((entry or {}).get("agent_id") or {}).get("tool")
agent = _normalize_agent_token(str(tool), allow_slug=True) if tool else None
if agent:
counts[agent] = counts.get(agent, 0) + 1
- if not counts:
- return None
- top = max(counts.values())
- leaders = [a for a, c in counts.items() if c == top]
- return leaders[0] if len(leaders) == 1 else None
+ if counts:
+ top = max(counts.values())
+ leaders = [a for a, c in counts.items() if c == top]
+ return GitAiNote(agent=leaders[0] if len(leaders) == 1 else None)
+ human_keys = ai_keys = 0
+ paths: set[str] = set()
+ for line in lines[:div]:
+ if not line.strip():
+ continue
+ if not line[:1].isspace():
+ paths.add(line.strip().strip('"').lstrip("/"))
+ continue
+ key = line.split()[0].lower()
+ if _GIT_AI_HUMAN_KEY.fullmatch(key):
+ human_keys += 1
+ elif _GIT_AI_AI_KEY.fullmatch(key):
+ ai_keys += 1
+ return GitAiNote(human=human_keys > 0 and ai_keys == 0, paths=frozenset(paths))
except Exception:
- return None
+ return GitAiNote()
+
+
+def _agent_from_git_ai_note(note: str) -> str | None:
+ """The dominant agent of a git-ai note, or ``None`` (see :func:`parse_git_ai_note`)."""
+ return parse_git_ai_note(note).agent
# Agent-trace records (the vendor-neutral agent-trace standard, v0.1.x): JSONL
@@ -389,6 +441,34 @@ def _agent_from_trace_record(rec: object) -> tuple[str, str, frozenset[str], str
return None
+def _human_trace_record(rec: dict) -> tuple[str, frozenset[str]] | None:
+ """``(revision, paths)`` when every conversation in *rec* is ``human``.
+
+ A record mixing in any other contributor type is not a human attestation;
+ ``unknown`` contributors in particular never become human.
+ """
+ try:
+ revision = str((rec.get("vcs") or {}).get("revision") or "").strip().lower()
+ if not revision:
+ return None
+ paths: set[str] = set()
+ for f in rec.get("files") or []:
+ if not isinstance(f, dict):
+ continue
+ path = str(f.get("path") or "").strip().lstrip("/")
+ for conv in f.get("conversations") or []:
+ if not isinstance(conv, dict):
+ continue
+ kind = str((conv.get("contributor") or {}).get("type") or "").lower()
+ if kind != "human":
+ return None
+ if path:
+ paths.add(path)
+ return (revision, frozenset(paths)) if paths else None
+ except Exception:
+ return None
+
+
def _dominant(votes: Counter[str] | None) -> str | None:
"""The single most-common key in *votes*, or ``None`` on empty / a tie."""
if not votes:
@@ -421,10 +501,14 @@ class AgentTraceIndex:
records: list[tuple[str, str, frozenset[str], str | None]] | None = None,
line_intervals: dict[str, list[tuple[int, int]]] | None = None,
line_intervals_by_model: dict[str, dict[str, list[tuple[int, int]]]] | None = None,
+ human_records: list[tuple[str, frozenset[str]]] | None = None,
) -> None:
self._by_revision: dict[str, list[tuple[str, frozenset[str], str | None]]] = {}
for revision, agent, paths, model_id in records or []:
self._by_revision.setdefault(revision, []).append((agent, paths, model_id))
+ self._human_by_revision: dict[str, set[str]] = {}
+ for revision, paths in human_records or []:
+ self._human_by_revision.setdefault(revision, set()).update(paths)
# Collapse the accumulated intervals to counts once, up front.
self._line_shares: dict[str, tuple[int, dict[str, int]]] = {}
for path, intervals in (line_intervals or {}).items():
@@ -438,7 +522,7 @@ class AgentTraceIndex:
self._line_shares[path] = (total, {m: c for m, c in models.items() if c > 0})
def __bool__(self) -> bool:
- return bool(self._by_revision) or bool(self._line_shares)
+ return bool(self._by_revision or self._line_shares or self._human_by_revision)
def line_shares(self) -> dict[str, tuple[int, dict[str, int]]]:
"""``{path: (agent_line_count, {model_id: line_count})}`` — empty when
@@ -453,12 +537,17 @@ class AgentTraceIndex:
A missing file (the common case) returns an empty index after a single
stat call, so repos without traces pay nothing. Oversized files are
skipped whole and malformed lines individually: a broken trace log
- must never take down the git index.
+ must never take down the git index. With ``attribution.enabled: false``
+ the file is not read at all.
"""
try:
root = getattr(repo, "working_tree_dir", None)
if not root or not isinstance(root, (str, Path)):
return cls()
+ from repowise.core.attribution import attribution_enabled
+
+ if not attribution_enabled(root):
+ return cls()
path = Path(root) / _TRACE_FILE
if not path.is_file():
return cls()
@@ -470,6 +559,7 @@ class AgentTraceIndex:
logger.warning("agent_trace_read_failed", error=str(exc))
return cls()
records: list[tuple[str, str, frozenset[str], str | None]] = []
+ human_records: list[tuple[str, frozenset[str]]] = []
line_intervals: dict[str, list[tuple[int, int]]] = {}
line_intervals_by_model: dict[str, dict[str, list[tuple[int, int]]]] = {}
for line in text.splitlines():
@@ -484,6 +574,8 @@ class AgentTraceIndex:
parsed = _agent_from_trace_record(rec)
if parsed:
records.append(parsed)
+ elif human := _human_trace_record(rec):
+ human_records.append(human)
# Line share is agent-agnostic (AI vs human at line granularity) and
# revision-independent — accumulate regardless of whether the record
# resolved to a single dominant agent above.
@@ -495,7 +587,7 @@ class AgentTraceIndex:
line_intervals_by_model.setdefault(path, {}).setdefault(raw_model, []).extend(
intervals
)
- return cls(records, line_intervals, line_intervals_by_model)
+ return cls(records, line_intervals, line_intervals_by_model, human_records)
def resolve(
self, sha: str, parents: tuple[str, ...], changed_paths: set[str]
@@ -510,6 +602,17 @@ class AgentTraceIndex:
return hit[0], "medium", hit[1]
return None
+ def resolve_human(self, sha: str, parents: tuple[str, ...], changed_paths: set[str]) -> bool:
+ """Whether human-only records cover this commit: the same revision rule
+ as :meth:`resolve`, but every changed path must be attested human.
+ Partial overlap stays unknown; a false human is the worse error."""
+ if not changed_paths:
+ return False
+ return any(
+ changed_paths <= self._human_by_revision.get((rev or "").lower(), set())
+ for rev in (sha, *parents)
+ )
+
def _match(self, revision: str, changed_paths: set[str]) -> tuple[str, str | None] | None:
candidates = self._by_revision.get((revision or "").lower())
if not candidates:
@@ -534,15 +637,22 @@ class AgentTraceIndex:
@dataclass(frozen=True)
class AgentProvenance:
- """One commit's agent attribution. ``agent is None`` means human."""
+ """One commit's attribution. ``agent is None`` is not human: read ``attribution``
+ (``agent`` / ``human_attested`` / ``unknown``; ``None`` when attribution is off)."""
agent: str | None = None
autonomy_tier: int | None = None # 1 near-autonomous · 2 human-driven · 3 assisted
channel: str | None = None
confidence: str | None = None # "high" | "medium" (local channels: always high)
+ attribution: str | None = "unknown"
-_HUMAN = AgentProvenance()
+_UNKNOWN = AgentProvenance()
+_DISABLED = AgentProvenance(attribution=None)
+
+
+def _agent(agent: str, tier: int, channel: str, confidence: str = "high") -> AgentProvenance:
+ return AgentProvenance(agent, tier, channel, confidence, "agent")
class AgentProvenanceClassifier:
@@ -552,6 +662,8 @@ class AgentProvenanceClassifier:
:meth:`classify` is then a handful of anchored regex searches per commit.
Extra patterns merge on top of the built-in registry; they never replace
it (precision of the defaults is validated, user patterns are additive).
+ With ``enabled=False`` (``attribution.enabled: false``) every commit is
+ left unlabelled and nothing about AI is stored.
"""
def __init__(
@@ -560,7 +672,9 @@ class AgentProvenanceClassifier:
extra_service_emails: dict[str, tuple[str, int]] | None = None,
extra_footer_patterns: list[tuple[str, str]] | None = None,
extra_coauthor_patterns: list[tuple[str, str]] | None = None,
+ enabled: bool = True,
) -> None:
+ self.enabled = enabled
self._service_emails = {**_SERVICE_EMAILS, **(extra_service_emails or {})}
self._footers = [
(re.compile(p, re.IGNORECASE | re.MULTILINE), agent)
@@ -599,6 +713,8 @@ class AgentProvenanceClassifier:
note_agent: str | None = None,
trace_agent: str | None = None,
trace_confidence: str = "high",
+ note_human: bool = False,
+ trace_human: bool = False,
) -> AgentProvenance:
"""Classify one commit from local metadata. *message* is the full
commit message (subject + body) — trailers and footers live in the
@@ -607,54 +723,115 @@ class AgentProvenanceClassifier:
authorship note (``refs/notes/ai``), or ``None`` when absent — read out
of band by the caller so classification stays a pure function.
*trace_agent* / *trace_confidence* are the pre-resolved result of
- :meth:`AgentTraceIndex.resolve` for this commit, same contract."""
+ :meth:`AgentTraceIndex.resolve` for this commit, same contract.
+ *note_human* / *trace_human* say an explicit human record covers the
+ commit; they apply only when no agent channel matched."""
+ if not self.enabled:
+ return _DISABLED
+ prov = self._classify_agent(
+ author_name,
+ author_email,
+ committer_email,
+ message,
+ note_agent,
+ trace_agent,
+ trace_confidence,
+ )
+ if prov is not None:
+ return prov
+ if note_human:
+ return AgentProvenance(None, None, "git_ai_note", "high", "human_attested")
+ if trace_human:
+ return AgentProvenance(None, None, "agent_trace", "high", "human_attested")
+ return _UNKNOWN
+
+ def _classify_agent(
+ self,
+ author_name: str,
+ author_email: str,
+ committer_email: str,
+ message: str,
+ note_agent: str | None,
+ trace_agent: str | None,
+ trace_confidence: str,
+ ) -> AgentProvenance | None:
# T1 — agent service identity AUTHORED the commit.
hit = self._identity_match(author_email)
if hit:
- return AgentProvenance(hit[0], hit[1], "service_email", "high")
+ return _agent(hit[0], hit[1], "service_email")
# T2 — git-ai authorship note: an explicit line-level attestation on
# this commit. Below T1 (a bot service account is more autonomous) but
# above the message-derived channels.
if note_agent:
- return AgentProvenance(note_agent, 2, "git_ai_note", "high")
+ return _agent(note_agent, 2, "git_ai_note")
# T2 — agent-trace record resolved to this commit. Below the git-ai
# note (a commit-attached attestation beats heuristic revision
# mapping), above the message-derived channels.
if trace_agent:
- return AgentProvenance(trace_agent, 2, "agent_trace", trace_confidence)
+ return _agent(trace_agent, 2, "agent_trace", trace_confidence)
# T2 — message footer / aider author-name suffix.
for pat, agent in self._footers:
if pat.search(message):
- return AgentProvenance(agent, 2, "message_footer", "high")
+ return _agent(agent, 2, "message_footer")
if _AIDER_NAME_RE.search(author_name or ""):
- return AgentProvenance("aider", 2, "author_name_aider", "high")
+ return _agent("aider", 2, "author_name_aider")
# T2 — ``Generated-by:`` AI-attribution trailer (agent generated it).
m = _GENERATED_BY_RE.search(message)
if m:
agent = _normalize_agent_token(m.group(1), allow_slug=False)
if agent:
- return AgentProvenance(agent, 2, "generated_by_trailer", "high")
+ return _agent(agent, 2, "generated_by_trailer")
# T2 — service identity as COMMITTER over a human author: the agent
# pushed/amended a human-driven change. Deliberately tier 2, not 1.
hit = self._identity_match(committer_email)
if hit:
- return AgentProvenance(hit[0], max(hit[1], 2), "service_committer", "high")
+ return _agent(hit[0], max(hit[1], 2), "service_committer")
# T3 — ``Assisted-by:`` AI-attribution trailer (human wrote it, agent
# helped). Below the committer channel to keep tier order intact.
m = _ASSISTED_BY_RE.search(message)
if m:
agent = _normalize_agent_token(m.group(1), allow_slug=False)
if agent:
- return AgentProvenance(agent, 3, "assisted_by_trailer", "high")
+ return _agent(agent, 3, "assisted_by_trailer")
# T3 — co-author trailer naming an agent service identity.
for pat, agent in self._coauthors:
if pat.search(message):
- return AgentProvenance(agent, 3, "coauthor_trailer", "high")
+ return _agent(agent, 3, "coauthor_trailer")
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 _HUMAN
+ return _agent(hit[0], 3, "coauthor_trailer")
+ return None
+
+
+def classify_commit(
+ classifier: AgentProvenanceClassifier,
+ header: dict,
+ changed_paths: set[str],
+ notes: dict[str, GitAiNote] | None,
+ trace_index: AgentTraceIndex | None,
+) -> tuple[AgentProvenance, tuple[str, str, str | None] | None]:
+ """Label one parsed commit header; also returns the agent-trace hit, if any.
+
+ The one place the walks join notes and trace records to the classifier, so
+ the repo-wide and per-file walks cannot label the same commit differently.
+ """
+ sha, parents = header["sha"], header["parents"]
+ trace_hit = trace_index.resolve(sha, parents, changed_paths) if trace_index else None
+ note = (notes or {}).get(sha) or GitAiNote()
+ prov = classifier.classify(
+ header["author_name"],
+ header["author_email"],
+ header["committer_name"],
+ header["committer_email"],
+ f"{header['subject']}\n{header['body']}",
+ note_agent=note.agent,
+ trace_agent=trace_hit[0] if trace_hit else None,
+ trace_confidence=trace_hit[1] if trace_hit else "high",
+ note_human=note.human and bool(changed_paths) and changed_paths <= note.paths,
+ trace_human=bool(trace_index) and trace_index.resolve_human(sha, parents, changed_paths),
+ )
+ return prov, trace_hit
@lru_cache(maxsize=1)
@@ -694,8 +871,13 @@ def classifier_from_repo_config(repo_path: object) -> AgentProvenanceClassifier:
Reads the optional ``agent_provenance`` block of ``.repowise/config.yaml``
(see module docstring for the shape). Malformed entries are skipped with a
- warning — a broken user pattern must never take down the git index.
+ warning — a broken user pattern must never take down the git index. With
+ ``attribution.enabled: false`` the classifier labels nothing.
"""
+ from repowise.core.attribution import attribution_enabled
+
+ if not attribution_enabled(repo_path): # type: ignore[arg-type]
+ return AgentProvenanceClassifier(enabled=False)
extra_emails: dict[str, tuple[str, int]] = {}
extra_footers: list[tuple[str, str]] = []
extra_coauthors: list[tuple[str, str]] = []
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
index 86c18b24e..2ce737c9b 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/commit_rows.py
@@ -131,6 +131,7 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:
"agent_channel": c.get("agent_channel"),
"agent_confidence": c.get("agent_confidence"),
"agent_model_id": c.get("agent_model_id"),
+ "attribution": c.get("attribution"),
}
)
return rows
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
index 0861bba97..f89b05d2a 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py
@@ -130,9 +130,11 @@ def new_meta(file_path: str) -> dict[str, Any]:
"prior_defect_raw_count": 0,
# Repo-relative rank of prior_defect_count; see enrich.compute_percentiles.
"prior_defect_pct": 0.0,
- # Share of this file's indexed history that is agent-attributed (local
- # channels only); agent_authored_pct stays None for a file with no commits.
+ # Agent share of the file's commits with a known source (agent or
+ # human-attested); None when no commit has one. Never a share of all
+ # commits: unknown is not human (see repowise.core.attribution).
"agent_commit_count": 0,
+ "attribution_known_count": 0,
"agent_authored_pct": None,
"agent_tier_counts_json": "{}",
# Distinct agent-written lines and {model_id: line_count} from the
@@ -160,7 +162,7 @@ def _parse_per_file_log(
commit_limit: int,
follow_renames: bool,
provenance_classifier: Any | None = None,
- note_agents: dict[str, str] | None = None,
+ note_agents: dict[str, Any] | None = None,
trace_index: Any | None = None,
) -> tuple[list[_CommitRec] | None, str | None]:
"""Run a per-file ``git log --numstat`` and parse it into commit records.
@@ -207,6 +209,7 @@ def _parse_per_file_log(
prov = labeler.label(header, changed_paths)
current.agent = prov.agent
current.agent_tier = prov.autonomy_tier
+ current.attribution = prov.attribution
return commits, orig_path
@@ -281,28 +284,18 @@ class _CommitLabeler:
"""Labels a commit's agent provenance from its header and changed paths."""
def __init__(
- self, classifier: Any, note_agents: dict[str, str] | None, trace_index: Any | None
+ self, classifier: Any, note_agents: dict[str, Any] | None, trace_index: Any | None
) -> None:
self._classifier = classifier
self._note_agents = note_agents or {}
self._trace_index = trace_index
def label(self, header: dict, changed_paths: set[str]) -> Any:
- trace_hit = (
- self._trace_index.resolve(header["sha"], header["parents"], changed_paths)
- if self._trace_index
- else None
- )
- return self._classifier.classify(
- header["author_name"],
- header["author_email"],
- header["committer_name"],
- header["committer_email"],
- f"{header['subject']}\n{header['body']}",
- note_agent=self._note_agents.get(header["sha"]),
- trace_agent=trace_hit[0] if trace_hit else None,
- trace_confidence=trace_hit[1] if trace_hit else "high",
- )
+ from .agent_provenance import classify_commit
+
+ return classify_commit(
+ self._classifier, header, changed_paths, self._note_agents, self._trace_index
+ )[0]
def index_file(
@@ -316,7 +309,7 @@ def index_file(
precomputed_commits: list[_CommitRec] | None = None,
as_of_ts: float | None = None,
provenance_classifier: Any | None = None,
- note_agents: dict[str, str] | None = None,
+ note_agents: dict[str, Any] | None = None,
trace_index: Any | None = None,
history_only: bool = False,
forge: ForgeKind = ForgeKind.GENERIC,
@@ -481,10 +474,17 @@ class _Authors:
def _add_agent_rollup(meta: dict[str, Any], commits: list[_CommitRec]) -> None:
- """Share of the file's commits that are agent-attributed, and the per-tier breakdown."""
- agent_commits = [c for c in commits if getattr(c, "agent", None)]
+ """Agent commits, commits with a known source, and the per-tier breakdown.
+
+ Leaves the defaults when attribution is off (every label ``None``).
+ """
+ if all(c.attribution is None for c in commits):
+ return
+ agent_commits = [c for c in commits if c.agent]
+ known = len(agent_commits) + sum(1 for c in commits if c.attribution == "human_attested")
meta["agent_commit_count"] = len(agent_commits)
- meta["agent_authored_pct"] = len(agent_commits) / len(commits)
+ meta["attribution_known_count"] = known
+ meta["agent_authored_pct"] = len(agent_commits) / known if known else None
tier_counts: Counter[str] = Counter(str(c.agent_tier) for c in agent_commits if c.agent_tier)
meta["agent_tier_counts_json"] = json.dumps(dict(tier_counts))
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index 0e584bc86..0dc0c8436 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -330,7 +330,7 @@ class GitIndexer:
if on_start is not None:
on_start(len(indexable_files) + len(history_files))
- fallback_note_agents: dict[str, str] = {}
+ fallback_note_agents: dict[str, Any] = {}
if fallback_files.intersection(indexable_files):
from ..git_commit_index import load_git_ai_note_agents
@@ -684,7 +684,7 @@ class GitIndexer:
fallback_files = sample.fallback_files
history_files -= fallback_files
history_changed -= fallback_files
- fallback_note_agents: dict[str, str] = {}
+ fallback_note_agents: dict[str, Any] = {}
if fallback_files.intersection(changed_file_paths):
from ..git_commit_index import load_git_ai_note_agents
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
index 7467b60c4..4efe847a3 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
@@ -84,6 +84,8 @@ class _CommitRec:
# the record so per-file rollups don't re-run the regex per touched file).
agent: str | None = None
agent_tier: int | None = None
+ # ``agent`` / ``human_attested`` / ``unknown``; None when attribution is off.
+ attribution: str | None = "unknown"
# The commit only moved this file (a rename row with 0/0 lines). It counts
# as one of the file's commits but credits nobody with ownership.
pure_move: bool = False
diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.py
index eab9fb2b2..f598ff95c 100644
--- a/packages/core/src/repowise/core/persistence/crud/git.py
+++ b/packages/core/src/repowise/core/persistence/crud/git.py
@@ -10,7 +10,7 @@ import json
from collections.abc import Sequence
from datetime import UTC, datetime
-from sqlalchemy import ColumnElement, and_, delete, func, or_, select, text
+from sqlalchemy import ColumnElement, and_, delete, func, or_, select, text, update
from sqlalchemy.engine import Connection
from sqlalchemy.ext.asyncio import AsyncSession
@@ -23,6 +23,7 @@ from ..models import (
GitCommitHealthFinding,
GitFunctionBlame,
GitMetadata,
+ Repository,
_new_uuid,
_now_utc,
)
@@ -738,13 +739,68 @@ async def get_author_commit_counts(session: AsyncSession, repository_id: str) ->
return [tuple(row) for row in result.all()]
+async def clear_attribution(session: AsyncSession, repository_id: str) -> None:
+ """Delete every AI attribution value derived into the index for a repository.
+
+ Commit labels and the per-file rollups go; git history, trailers and notes
+ in the repository are untouched. ``repowise attribution purge`` and the
+ ``attribution.enabled: false`` sweep below both use this.
+ """
+ await session.execute(
+ update(GitCommit)
+ .where(GitCommit.repository_id == repository_id)
+ .values(
+ agent_name=None,
+ agent_autonomy_tier=None,
+ agent_channel=None,
+ agent_confidence=None,
+ agent_model_id=None,
+ attribution=None,
+ )
+ )
+ await session.execute(
+ update(GitMetadata)
+ .where(GitMetadata.repository_id == repository_id)
+ .values(
+ agent_commit_count=0,
+ attribution_known_count=0,
+ agent_authored_pct=None,
+ agent_tier_counts_json="{}",
+ agent_line_count=0,
+ agent_line_model_json="{}",
+ )
+ )
+
+
+async def clear_attribution_if_disabled(session: AsyncSession, repository_id: str) -> bool:
+ """Run :func:`clear_attribution` when ``attribution.enabled`` is false.
+
+ Called after every git write, so switching attribution off and running
+ ``repowise update`` leaves nothing about AI in the index, including rows
+ an earlier index wrote. Returns whether it cleared.
+ """
+ from ...attribution import attribution_enabled
+
+ repo = await session.get(Repository, repository_id)
+ if attribution_enabled(repo.local_path if repo is not None else None):
+ return False
+ await clear_attribution(session, repository_id)
+ return True
+
+
def _commit_authorship_clause(authorship: str | None):
- """Optional authorship predicate: ``agent`` keeps agent-attributed commits,
- ``human`` keeps the rest. ``None`` / ``"all"`` means no filtering."""
+ """Optional authorship predicate over the three-state label: ``agent``,
+ ``human`` (human-attested only; a commit without a marker is never human)
+ or ``unknown``. ``None`` / ``"all"`` means no filtering."""
if authorship == "agent":
return GitCommit.agent_name.is_not(None)
if authorship == "human":
- return GitCommit.agent_name.is_(None)
+ return GitCommit.attribution == "human_attested"
+ if authorship == "unknown":
+ return and_(
+ GitCommit.agent_name.is_(None),
+ or_(GitCommit.attribution.is_(None), GitCommit.attribution == "unknown"),
+ )
return None
@@ -841,7 +897,7 @@ async def get_git_commits(
``sort="risk"`` ranks by ``change_risk_score`` descending (the review-
priority order); ``sort="date"`` ranks by ``committed_at`` descending.
- ``authorship`` narrows to ``agent`` / ``human``; ``kind`` narrows to the
+ ``authorship`` narrows to ``agent`` / ``human`` / ``unknown``; ``kind`` narrows to the
``high`` review-priority band or to ``fixes``. Both filter the repository
rather than the page, so a filter still answers when the page it would
have filtered is uniform.
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index e50e6db67..03282d08c 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -695,13 +695,15 @@ class GitMetadata(Base):
# a busy repository clears for most of its files.
prior_defect_pct: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
- # Agent-provenance rollup: how much of this file's indexed history is
- # agent-attributed (deterministic local-channel classification — identity
- # fields, message footers, co-author trailers; see
- # ingestion.git_indexer.agent_provenance). agent_tier_counts_json maps
+ # Agent-provenance rollup (deterministic local channels; see
+ # ingestion.git_indexer.agent_provenance). attribution_known_count is the
+ # file's commits with a known source (agent or human-attested), and
+ # agent_authored_pct the agent share of those, never of all commits: unknown
+ # is not human (repowise.core.attribution). agent_tier_counts_json maps
# autonomy tier ("1" near-autonomous / "2" human-driven / "3" assisted)
- # to commit counts. agent_authored_pct stays NULL until the next reindex.
+ # to commit counts.
agent_commit_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ attribution_known_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
agent_authored_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
agent_tier_counts_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
@@ -785,8 +787,10 @@ class GitCommit(Base):
# Agent provenance: which coding agent (if any) authored this commit, at
# what autonomy tier (1 near-autonomous bot account · 2 human-driven agent
# · 3 assisted/co-authored), via which attribution channel, and with what
- # confidence band. NULL throughout = human-authored (or pre-migration rows;
- # back-populated on the next index). Deterministic local-git channels only.
+ # confidence band. Deterministic local-git channels only. attribution is the
+ # three-state label (agent / human_attested / unknown); NULL on rows written
+ # before it existed (read through repowise.core.attribution.commit_label) or
+ # while attribution is switched off.
agent_name: Mapped[str | None] = mapped_column(String(32), nullable=True)
agent_autonomy_tier: Mapped[int | None] = mapped_column(Integer, nullable=True)
agent_channel: Mapped[str | None] = mapped_column(String(32), nullable=True)
@@ -796,6 +800,7 @@ class GitCommit(Base):
# attributed the commit. Set only for the ``agent_trace`` channel (no other
# local channel carries a model); NULL for human or non-trace commits.
agent_model_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ attribution: Mapped[str | None] = mapped_column(String(16), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index d52d8b6ac..8eefecaea 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1491,6 +1491,7 @@ async def persist_incremental_commits(
"""
from repowise.core.ingestion.git_indexer import GitIndexer
from repowise.core.persistence.crud import (
+ clear_attribution_if_disabled,
get_latest_commit_committed_at,
get_repository,
update_repo_git_totals,
@@ -1534,6 +1535,7 @@ async def persist_incremental_commits(
await upsert_git_commits_bulk(session, repo_id, rows)
if file_rows:
await upsert_git_commit_files_bulk(session, repo_id, file_rows)
+ await clear_attribution_if_disabled(session, repo_id)
# What the new commits did to health is scanned by the caller once this
# transaction commits (commit_health.refresh_commit_health_after_update):
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index b0d16734f..260de1d7b 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1822,6 +1822,7 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:
``(repo_id, sha)`` — safe to call incrementally and on resume.
"""
from repowise.core.persistence.crud import (
+ clear_attribution_if_disabled,
prune_fix_events_before,
update_repo_git_totals,
upsert_fix_events_bulk,
@@ -1843,6 +1844,7 @@ async def persist_git(result: Any, session: Any, repo_id: str) -> None:
commit_file_rows = getattr(summary, "commit_file_rows", None)
if commit_file_rows:
await upsert_git_commit_files_bulk(session, repo_id, commit_file_rows)
+ await clear_attribution_if_disabled(session, repo_id)
# Per fix-commit x file rows (with their SZZ candidates). The prune keeps a
# re-index of an already-indexed repo from leaving behind events that have
@@ -1955,6 +1957,7 @@ async def persist_git_refresh(
from sqlalchemy import select
from repowise.core.persistence.crud import (
+ clear_attribution_if_disabled,
recompute_git_percentiles,
upsert_git_metadata_bulk,
)
@@ -1978,6 +1981,7 @@ async def persist_git_refresh(
]
await upsert_git_metadata_bulk(session, repo_id, [*git_meta_map.values(), *decay_rows])
await recompute_git_percentiles(session, repo_id)
+ await clear_attribution_if_disabled(session, repo_id)
async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index eb86e4ed8..f124bec53 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -21,6 +21,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.communities import has_community
from repowise.core.analysis.decisions.lifecycle import is_governing
from repowise.core.analysis.decisions.scope import binds_to_paths
+from repowise.core.attribution import attribution_enabled, file_share
from repowise.core.generation.page_selection import STALE_STATUSES
from repowise.core.ingestion.models import (
NON_DEPENDENCY_EDGE_TYPES,
@@ -1164,10 +1165,17 @@ async def _resolve_one_target(
if recent and recent != meta.primary_owner_name:
ownership["recent_owner"] = recent
ownership["recent_owner_pct"] = getattr(meta, "recent_owner_commit_pct", None)
- # Agent provenance — only surfaced when agent-attributed
- # commits exist, so human-only files stay noise-free.
- if getattr(meta, "agent_commit_count", 0):
- ownership["agent_authored_pct"] = getattr(meta, "agent_authored_pct", None)
+ # Agent provenance, only when agent-attributed commits exist
+ # and attribution is on. The share is of commits with a known
+ # source, with its coverage; unknown is never human.
+ if getattr(meta, "agent_commit_count", 0) and attribution_enabled(
+ repository.local_path
+ ):
+ ownership["agent_share"] = file_share(
+ meta.agent_commit_count,
+ getattr(meta, "attribution_known_count", 0),
+ meta.commit_count_total,
+ ).summary()
ownership["agent_commit_count"] = meta.agent_commit_count
with contextlib.suppress(TypeError, ValueError):
ownership["agent_tier_counts"] = json.loads(
diff --git a/packages/server/src/repowise/server/routers/_local_git.py b/packages/server/src/repowise/server/routers/_local_git.py
index 031fc32c9..dab87bdfc 100644
--- a/packages/server/src/repowise/server/routers/_local_git.py
+++ b/packages/server/src/repowise/server/routers/_local_git.py
@@ -53,3 +53,12 @@ def revision_exists(repo_path: str, rev: str) -> bool:
text=True,
)
return result.returncode == 0
+
+
+async def repo_attribution_on(session: AsyncSession, repo_id: str) -> bool:
+ """Whether AI attribution may be shown for this repository (its config and
+ the user's); a repository without a checkout reads the user config only."""
+ from repowise.core.attribution import attribution_enabled
+
+ repo = await crud.get_repository(session, repo_id)
+ return attribution_enabled(repo.local_path if repo is not None else None)
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 2838d63ea..7da08a131 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -23,6 +23,7 @@ from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.aggregation import NLOC_NULL_REASON
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.trends import file_trend
+from repowise.core.attribution import attribution_enabled
from repowise.core.ids import is_external
from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence import crud
@@ -45,6 +46,7 @@ from repowise.server.routers.code_health import (
_score_breakdown_from_findings,
)
from repowise.server.routers.git import _hotspot_from_row
+from repowise.server.schemas.git import file_attribution_fields
router = APIRouter(
prefix="/api/repos",
@@ -331,11 +333,12 @@ async def file_detail(
git["fix_symbol_counts"] = _json_or(git_meta.fix_symbol_counts_json, {})
# The blame owner's share of current lines, next to their commit share.
git["primary_owner_line_pct"] = git_meta.primary_owner_line_pct
- git["agent"] = {
- "agent_commit_count": git_meta.agent_commit_count or 0,
- "agent_authored_pct": git_meta.agent_authored_pct,
- "tier_counts": _json_or(git_meta.agent_tier_counts_json, {}),
- }
+ # None when attribution is off for the repository. This view has always
+ # named the tier map ``tier_counts``.
+ agent = file_attribution_fields(git_meta, attribution_enabled(repo.local_path))
+ if agent:
+ agent["tier_counts"] = agent.pop("agent_tier_counts")
+ git["agent"] = agent or None
git["first_commit_at"] = (
git_meta.first_commit_at.isoformat() if git_meta.first_commit_at else None
)
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index e16d99c70..feb96e3d4 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -29,6 +29,13 @@ from repowise.core.analysis.change_risk import (
)
from repowise.core.analysis.owners import people_resolver
from repowise.core.analysis.risk_semantics import change_risk_authority
+from repowise.core.attribution import (
+ AGENT,
+ COVERAGE_FLOOR,
+ HUMAN_ATTESTED,
+ attribution_share,
+ commit_label,
+)
from repowise.core.co_change import MIN_CO_CHANGE_SUPPORT, parse_partners
from repowise.core.ingestion.git_indexer._constants import (
EVOLUTION_CATEGORIES,
@@ -40,7 +47,11 @@ from repowise.core.persistence.models import GitCommit, GitMetadata, Repository
from repowise.core.persistence.sql import is_missing_table
from repowise.server.deps import get_db_session, verify_api_key
from repowise.server.mcp_server.tool_risk import _check_test_gap
-from repowise.server.routers._local_git import resolve_local_repo, revision_exists
+from repowise.server.routers._local_git import (
+ repo_attribution_on,
+ resolve_local_repo,
+ revision_exists,
+)
from repowise.server.schemas import (
AgentTrendBucket,
AgentTrendResponse,
@@ -156,9 +167,16 @@ async def _author_commit_counts(session: AsyncSession, repo_id: str) -> dict[str
def _commit_fields(
- r: GitCommit, normalizer: RiskNormalizer, author_counts: dict[str, int] | None = None
+ r: GitCommit,
+ normalizer: RiskNormalizer,
+ author_counts: dict[str, int] | None = None,
+ *,
+ attribution_on: bool,
) -> dict:
- """Shared CommitResponse field map (raw row + repo-relative normalization)."""
+ """Shared CommitResponse field map (raw row + repo-relative normalization).
+
+ Attribution fields stay None when attribution is off for the repository.
+ """
risk = _commit_risk(r)
top_driver = risk.top_driver.label if risk and risk.top_driver else None
return {
@@ -186,16 +204,28 @@ def _commit_fields(
if author_counts is not None
else None
),
- "agent_name": r.agent_name,
- "agent_autonomy_tier": r.agent_autonomy_tier,
- "agent_confidence": r.agent_confidence,
+ **(
+ {
+ "agent_name": r.agent_name,
+ "agent_autonomy_tier": r.agent_autonomy_tier,
+ "agent_confidence": r.agent_confidence,
+ "attribution": commit_label(r.attribution, r.agent_name),
+ }
+ if attribution_on
+ else {}
+ ),
}
def _commit_from_row(
- r: GitCommit, normalizer: RiskNormalizer, author_counts: dict[str, int] | None = None
+ r: GitCommit,
+ normalizer: RiskNormalizer,
+ author_counts: dict[str, int] | None = None,
+ *,
+ attribution_on: bool,
) -> CommitResponse:
- return CommitResponse(**_commit_fields(r, normalizer, author_counts))
+ fields = _commit_fields(r, normalizer, author_counts, attribution_on=attribution_on)
+ return CommitResponse(**fields)
async def _commit_files(session: AsyncSession, repo_id: str, sha: str) -> list[CommitFileResponse]:
@@ -269,6 +299,8 @@ def _commit_detail_from_row(
author_counts: dict[str, int] | None = None,
files: list[CommitFileResponse] | None = None,
health: CommitHealthResponse | None = None,
+ *,
+ attribution_on: bool,
) -> CommitDetailResponse:
"""Map a commit row to its detail view, recomputing the risk-driver
breakdown from the persisted Kamei features + author experience.
@@ -288,9 +320,9 @@ def _commit_detail_from_row(
for d in (risk.top_drivers if risk else [])
]
return CommitDetailResponse(
- **_commit_fields(r, normalizer, author_counts),
+ **_commit_fields(r, normalizer, author_counts, attribution_on=attribution_on),
drivers=drivers,
- agent_channel=r.agent_channel,
+ agent_channel=r.agent_channel if attribution_on else None,
files=files or [],
health=health,
)
@@ -300,7 +332,7 @@ def _commit_detail_from_row(
async def get_commits(
repo_id: str,
sort: str = Query("date", pattern="^(risk|date)$"),
- authorship: str = Query("all", pattern="^(all|agent|human)$"),
+ authorship: str = Query("all", pattern="^(all|agent|human|unknown)$"),
kind: str = Query("all", pattern="^(all|high|fixes)$"),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
@@ -310,11 +342,15 @@ async def get_commits(
``sort=date`` (default) orders by recency; ``sort=risk`` orders by the
supporting diff-shape score descending. ``authorship`` narrows to
- agent-attributed or human commits, and ``kind`` to the ``high``
+ agent-attributed, human-attested or unknown commits (ignored when
+ attribution is off), and ``kind`` to the ``high``
review-priority band or to ``fixes``. Each commit carries a
**repo-relative** ``risk_percentile`` + ``review_priority`` so the ranking
is portable across repos (the absolute calibration band is not).
"""
+ attribution_on = await repo_attribution_on(session, repo_id)
+ if not attribution_on:
+ authorship = "all"
normalizer = RiskNormalizer.from_scores(await crud.get_commit_risk_scores(session, repo_id))
# The high band is a tercile of the repo's own scores, so the boundary has
# to be resolved before the page is cut rather than derived per row.
@@ -333,7 +369,10 @@ async def get_commits(
high_cut=high_cut,
)
author_counts = await _author_commit_counts(session, repo_id)
- items = [_commit_from_row(r, normalizer, author_counts) for r in rows]
+ items = [
+ _commit_from_row(r, normalizer, author_counts, attribution_on=attribution_on)
+ for r in rows
+ ]
next_offset = offset + limit if offset + limit < total else None
return Paginated[CommitResponse](
items=items,
@@ -348,50 +387,48 @@ async def get_agent_trend(
repo_id: str,
session: AsyncSession = Depends(get_db_session),
) -> AgentTrendResponse:
- """Monthly agent-vs-human commit volume across the indexed window.
+ """Monthly commits by attribution label across the indexed window.
- Buckets the bounded ``git_commits`` table in Python (portable across
- SQLite/Postgres date functions). Months with zero commits are omitted.
+ Each month and the window carry agent, human-attested and unknown counts,
+ the coverage (known / all) and the agent share of covered commits, withheld
+ below the coverage floor. Buckets the bounded ``git_commits`` table in
+ Python (portable across SQLite/Postgres date functions). Months with zero
+ commits are omitted.
"""
+ floor_pct = COVERAGE_FLOOR * 100.0
+ if not await repo_attribution_on(session, repo_id):
+ return AgentTrendResponse(enabled=False, coverage_floor_pct=floor_pct)
result = await session.execute(
select(
GitCommit.committed_at,
GitCommit.agent_name,
GitCommit.agent_autonomy_tier,
+ GitCommit.attribution,
).where(GitCommit.repository_id == repo_id)
)
- buckets: dict[str, dict] = {}
- total = 0
- agent_total = 0
+ buckets: dict[str, Counter[str]] = {}
+ tiers: dict[str, Counter[str]] = {}
+ window: Counter[str] = Counter()
names: dict[str, int] = {}
- for committed_at, agent_name, tier in result.all():
+ for committed_at, agent_name, tier, attribution in result.all():
if committed_at is None:
continue
month = committed_at.strftime("%Y-%m")
- b = buckets.setdefault(month, {"total": 0, "agent": 0, "tiers": {}})
- b["total"] += 1
- total += 1
- if agent_name:
- b["agent"] += 1
- agent_total += 1
+ label = commit_label(attribution, agent_name)
+ for counts in (buckets.setdefault(month, Counter()), window):
+ counts["total"] += 1
+ counts[label] += 1
+ if label == AGENT and agent_name:
names[agent_name] = names.get(agent_name, 0) + 1
if tier is not None:
- key = str(tier)
- b["tiers"][key] = b["tiers"].get(key, 0) + 1
+ tiers.setdefault(month, Counter())[str(tier)] += 1
return AgentTrendResponse(
+ coverage_floor_pct=floor_pct,
buckets=[
- AgentTrendBucket(
- month=m,
- total_commits=b["total"],
- agent_commits=b["agent"],
- agent_pct=(b["agent"] / b["total"] * 100.0) if b["total"] else 0.0,
- tier_counts=b["tiers"],
- )
- for m, b in sorted(buckets.items())
+ AgentTrendBucket(month=m, tier_counts=dict(tiers.get(m, {})), **_share_fields(c))
+ for m, c in sorted(buckets.items())
],
- total_commits=total,
- agent_commits=agent_total,
- agent_pct=(agent_total / total * 100.0) if total else 0.0,
+ **_share_fields(window),
agent_names=sorted(
[{"name": k, "count": v} for k, v in names.items()],
key=lambda x: x["count"],
@@ -400,6 +437,22 @@ async def get_agent_trend(
)
+def _share_fields(counts: Counter[str]) -> dict:
+ """``AttributionShareFields`` from per-label commit counts, in percent."""
+ share = attribution_share(counts[AGENT], counts[HUMAN_ATTESTED], counts["total"])
+ return {
+ "total_commits": share.total,
+ "agent_commits": share.agent,
+ "human_attested_commits": share.human_attested,
+ "unknown_commits": share.unknown,
+ "coverage_pct": share.coverage * 100.0 if share.coverage is not None else None,
+ "agent_pct_of_covered": (
+ share.agent_share * 100.0 if share.agent_share is not None else None
+ ),
+ "suppressed_reason": share.suppressed_reason,
+ }
+
+
@router.get("/{repo_id}/commits/stats", response_model=CommitStatsResponse)
async def get_commit_stats(
repo_id: str,
@@ -422,10 +475,21 @@ async def get_commit_stats(
func.sum(case((GitCommit.is_fix.is_(True), 1), else_=0)),
func.avg(GitCommit.entropy),
func.sum(case((GitCommit.agent_name.is_not(None), 1), else_=0)),
+ func.sum(case((GitCommit.attribution == HUMAN_ATTESTED, 1), else_=0)),
).where(GitCommit.repository_id == repo_id)
)
).one()
- fix_count, avg_entropy, agent_count = agg
+ fix_count, avg_entropy, agent_count, human_count = agg
+ attribution: dict = {}
+ if await repo_attribution_on(session, repo_id):
+ counts = Counter({AGENT: int(agent_count or 0), HUMAN_ATTESTED: int(human_count or 0)})
+ counts["total"] = total
+ fields = _share_fields(counts)
+ attribution = {
+ "agent_commit_count": fields["agent_commits"],
+ "agent_pct_of_covered": fields["agent_pct_of_covered"],
+ "attribution_coverage_pct": fields["coverage_pct"],
+ }
scores = await crud.get_commit_risk_scores(session, repo_id)
normalizer = RiskNormalizer.from_scores(scores)
@@ -435,7 +499,7 @@ async def get_commit_stats(
total_commits=total,
high_priority_count=high_priority,
fix_commit_count=int(fix_count or 0),
- agent_commit_count=int(agent_count or 0),
+ **attribution,
avg_entropy=float(avg_entropy or 0.0),
risk_histogram=_risk_histogram(normalizer.scores),
moderate_cut=normalizer.moderate_cut,
@@ -557,7 +621,14 @@ async def get_commit(
author_counts = await _author_commit_counts(session, repo_id)
files = await _commit_files(session, repo_id, row.sha)
health = await _commit_health(session, repo_id, row.sha)
- return _commit_detail_from_row(row, normalizer, author_counts, files, health)
+ return _commit_detail_from_row(
+ row,
+ normalizer,
+ author_counts,
+ files,
+ health,
+ attribution_on=await repo_attribution_on(session, repo_id),
+ )
@router.get("/{repo_id}/git-metadata", response_model=GitMetadataResponse)
@@ -570,7 +641,9 @@ async def get_git_metadata(
meta = await crud.get_git_metadata(session, repo_id, file_path)
if meta is None:
raise HTTPException(status_code=404, detail="Git metadata not found")
- response = GitMetadataResponse.from_orm(meta)
+ response = GitMetadataResponse.from_orm(
+ meta, attribution_on=await repo_attribution_on(session, repo_id)
+ )
response.test_gap = await _check_test_gap(session, repo_id, file_path)
return response
diff --git a/packages/server/src/repowise/server/routers/graph/neighborhoods.py b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
index eaddc06f5..638631cd4 100644
--- a/packages/server/src/repowise/server/routers/graph/neighborhoods.py
+++ b/packages/server/src/repowise/server/routers/graph/neighborhoods.py
@@ -6,6 +6,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.attribution import attribution_enabled
from repowise.core.ingestion.models import TEMPORAL_EDGE_TYPES
from repowise.core.persistence.crud.analysis.shown import ungated
from repowise.core.persistence.models import (
@@ -13,6 +14,7 @@ from repowise.core.persistence.models import (
GitMetadata,
GraphEdge,
GraphNode,
+ Repository,
)
from repowise.server.deps import get_db_session
from repowise.server.routers.graph._common import with_repo
@@ -43,7 +45,7 @@ async def ego_graph(
node_id: str = Query(..., description="Center node ID"),
hops: int = Query(2, ge=1, le=3),
session: AsyncSession = Depends(get_db_session),
- _repo: object = Depends(with_repo),
+ repo: Repository = Depends(with_repo),
) -> EgoGraphResponse:
"""Return the N-hop neighborhood of a given node."""
try:
@@ -109,7 +111,13 @@ async def ego_graph(
)
)
git_row = git_result.scalar_one_or_none()
- git_meta = GitMetadataResponse.from_orm(git_row) if git_row else None
+ git_meta = (
+ GitMetadataResponse.from_orm(
+ git_row, attribution_on=attribution_enabled(repo.local_path)
+ )
+ if git_row
+ else None
+ )
signals = await collect_node_signals(session, repo_id, list(ego_node_ids))
diff --git a/packages/server/src/repowise/server/routers/owners.py b/packages/server/src/repowise/server/routers/owners.py
index 3c5651a30..7495a3fd2 100644
--- a/packages/server/src/repowise/server/routers/owners.py
+++ b/packages/server/src/repowise/server/routers/owners.py
@@ -21,7 +21,6 @@ from repowise.server.schemas import (
OwnerProfileResponse,
Paginated,
)
-from repowise.server.schemas.ownership import OwnerAgentCollab
from repowise.server.services.owner_profile import (
_OwnerAccumulator,
aggregate_owners,
@@ -111,19 +110,6 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerP
)
)
- agent_collab: OwnerAgentCollab | None = None
- if acc.owned_attributed_commits > 0 or acc.owned_agent_commits > 0:
- agent_collab = OwnerAgentCollab(
- files_with_agent_commits=acc.owned_files_with_agents,
- agent_commit_count=acc.owned_agent_commits,
- agent_share_pct=(
- acc.owned_agent_commits / acc.owned_attributed_commits * 100.0
- if acc.owned_attributed_commits
- else None
- ),
- tier_counts=dict(acc.owned_agent_tier_counts),
- )
-
return OwnerProfileResponse(
key=acc.key,
name=acc.name,
@@ -145,7 +131,6 @@ def _to_profile(acc: _OwnerAccumulator, module_totals: dict[str, int]) -> OwnerP
co_authors=co_authors,
co_authors_total=len(acc.coauthor_shared),
commit_categories=dict(acc.commit_categories),
- agent_collab=agent_collab,
)
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 7a26403fa..a060d6678 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -210,7 +210,6 @@ if TYPE_CHECKING:
ModuleHealthDetail,
ModuleHealthOwner,
ModuleHealthSummary,
- OwnerAgentCollab,
OwnerCoAuthor,
OwnerFileEntry,
OwnerListEntry,
@@ -519,7 +518,6 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
"ModuleHealthDetail",
"ModuleHealthOwner",
"ModuleHealthSummary",
- "OwnerAgentCollab",
"OwnerCoAuthor",
"OwnerFileEntry",
"OwnerListEntry",
@@ -806,7 +804,6 @@ __all__ = [
"NeighboringCommunity",
"NodeSearchResult",
"OkResponse",
- "OwnerAgentCollab",
"OwnerCoAuthor",
"OwnerFileEntry",
"OwnerListEntry",
diff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.py
index 15c381958..3179c2950 100644
--- a/packages/server/src/repowise/server/schemas/git.py
+++ b/packages/server/src/repowise/server/schemas/git.py
@@ -8,6 +8,7 @@ from typing import Any
from pydantic import BaseModel
+from repowise.core.attribution import file_share
from repowise.core.co_change import parse_partners
from repowise.server.schemas.risk_semantics import RiskAuthority
@@ -58,17 +59,18 @@ class GitMetadataResponse(BaseModel):
# Rename lineage: the file's path before its most recent move, if any.
original_path: str | None = None
test_gap: bool | None = None
- # Agent-provenance rollup: share of the file's indexed commits that are
- # agent-attributed (deterministic local-git channels), with the autonomy-
- # tier breakdown ({"1": n, "2": n, "3": n}). agent_authored_pct is None
- # for rows persisted before the provenance-aware index ran.
- agent_commit_count: int = 0
+ # Agent-provenance rollup (see file_attribution_fields). All None when AI
+ # attribution is switched off for the repository.
+ agent_commit_count: int | None = None
agent_authored_pct: float | None = None
- agent_tier_counts: dict = {}
+ agent_tier_counts: dict | None = None
+ attribution_coverage: float | None = None
+ agent_share_suppressed: str | None = None
@classmethod
- def from_orm(cls, obj: object) -> GitMetadataResponse:
+ def from_orm(cls, obj: object, *, attribution_on: bool) -> GitMetadataResponse:
return cls(
+ **file_attribution_fields(obj, attribution_on),
file_path=obj.file_path, # type: ignore[attr-defined]
commit_count_total=obj.commit_count_total, # type: ignore[attr-defined]
commit_count_90d=obj.commit_count_90d, # type: ignore[attr-defined]
@@ -111,12 +113,34 @@ class GitMetadataResponse(BaseModel):
temporal_hotspot_score=obj.temporal_hotspot_score, # type: ignore[attr-defined]
commit_count_capped=bool(obj.commit_count_capped), # type: ignore[attr-defined]
original_path=obj.original_path, # type: ignore[attr-defined]
- agent_commit_count=getattr(obj, "agent_commit_count", 0) or 0,
- agent_authored_pct=getattr(obj, "agent_authored_pct", None),
- agent_tier_counts=json.loads(getattr(obj, "agent_tier_counts_json", None) or "{}"),
)
+def file_attribution_fields(obj: object, attribution_on: bool) -> dict:
+ """A file's agent rollup, honest about what is unknown.
+
+ ``agent_authored_pct`` is the agent share (0-1) of the file's commits with a
+ known source, withheld (None) below the coverage floor with the reason in
+ ``agent_share_suppressed``; ``attribution_coverage`` is known / all commits.
+ Unknown is never counted as human. Empty when attribution is off.
+ """
+ if not attribution_on:
+ return {}
+ agent = getattr(obj, "agent_commit_count", 0) or 0
+ share = file_share(
+ agent,
+ getattr(obj, "attribution_known_count", 0),
+ getattr(obj, "commit_count_total", 0),
+ )
+ return {
+ "agent_commit_count": agent,
+ "agent_authored_pct": share.agent_share,
+ "agent_tier_counts": json.loads(getattr(obj, "agent_tier_counts_json", None) or "{}"),
+ "attribution_coverage": share.coverage,
+ "agent_share_suppressed": share.suppressed_reason,
+ }
+
+
class HotspotResponse(BaseModel):
file_path: str
commit_count_total: int = 0
@@ -215,10 +239,12 @@ class CommitResponse(BaseModel):
# from. Identities are folded, so noreply variants of one person count once.
author_commit_count: int | None = None
# Agent provenance (deterministic local-git attribution channels).
- # agent_name is None for human-authored commits.
+ # attribution is agent / human_attested / unknown; agent_name is None for
+ # both of the latter. All None when attribution is off for the repository.
agent_name: str | None = None
agent_autonomy_tier: int | None = None
agent_confidence: str | None = None
+ attribution: str | None = None
class RiskDriverResponse(BaseModel):
@@ -283,23 +309,42 @@ class CommitDetailResponse(CommitResponse):
health: CommitHealthResponse | None = None
-class AgentTrendBucket(BaseModel):
- """One month of agent-vs-human commit volume."""
+class AttributionShareFields(BaseModel):
+ """Commit counts by attribution label and the honest agent share.
+
+ ``agent_pct_of_covered`` (0-100) is the agent share of commits with a known
+ source (agent or human-attested): at least that share of covered commits
+ came from an agent. It is None, with ``suppressed_reason``, when
+ ``coverage_pct`` (known / all, 0-100) is below the coverage floor. Unknown
+ commits are their own band, never counted as human.
+ """
+
+ total_commits: int = 0
+ agent_commits: int = 0
+ human_attested_commits: int = 0
+ unknown_commits: int = 0
+ coverage_pct: float | None = None
+ agent_pct_of_covered: float | None = None
+ suppressed_reason: str | None = None
+
+
+class AgentTrendBucket(AttributionShareFields):
+ """One month of commits by attribution label."""
month: str # "YYYY-MM"
- total_commits: int
- agent_commits: int
- agent_pct: float # 0-100
tier_counts: dict = {}
-class AgentTrendResponse(BaseModel):
- """Monthly agent-share trend across the indexed commit window."""
+class AgentTrendResponse(AttributionShareFields):
+ """Monthly attribution trend across the indexed commit window.
- buckets: list[AgentTrendBucket]
- total_commits: int
- agent_commits: int
- agent_pct: float # 0-100 across the whole window
+ ``enabled`` is false, with every figure empty, when AI attribution is off
+ for the repository.
+ """
+
+ enabled: bool = True
+ coverage_floor_pct: float
+ buckets: list[AgentTrendBucket] = []
agent_names: list[dict] = [] # [{name, count}] descending
@@ -435,7 +480,12 @@ class CommitStatsResponse(BaseModel):
total_commits: int
high_priority_count: int # commits in the repo-relative top risk tercile
fix_commit_count: int # subjects classified as bug-fixes
- agent_commit_count: int # agent-attributed commits
+ # Agent-attributed commits, and their share of commits with a known source
+ # (0-100, None below the coverage floor) beside that coverage. All None when
+ # attribution is off for the repository.
+ agent_commit_count: int | None = None
+ agent_pct_of_covered: float | None = None
+ attribution_coverage_pct: float | None = None
avg_entropy: float # mean change-diffusion across all commits
# The distribution behind the tercile banding. Binned on the *raw* score
diff --git a/packages/server/src/repowise/server/schemas/ownership.py b/packages/server/src/repowise/server/schemas/ownership.py
index c3e7e2cec..f042e6247 100644
--- a/packages/server/src/repowise/server/schemas/ownership.py
+++ b/packages/server/src/repowise/server/schemas/ownership.py
@@ -74,22 +74,6 @@ class OwnerCoAuthor(BaseModel):
co_change_strength: float # 0-1 fraction
-class OwnerAgentCollab(BaseModel):
- """How much coding-agent activity lands on the files this person owns.
-
- Aggregated from the per-file agent-provenance rollup (GitMetadata) over
- the owner's primary-owned files — agent identity per commit lives on the
- commits surface, the per-file rollup only carries counts and tiers.
- """
-
- files_with_agent_commits: int
- agent_commit_count: int
- # Commit-weighted share of agent-attributed commits across owned files,
- # 0-100. None when no owned file has a provenance-aware rollup yet.
- agent_share_pct: float | None
- tier_counts: dict = {}
-
-
class OwnerProfileResponse(BaseModel):
key: str
name: str
@@ -124,9 +108,6 @@ class OwnerProfileResponse(BaseModel):
# Commit-category mix across files they touch (sum of categories).
commit_categories: dict
- # Agent collaboration on owned files (None when nothing is attributed).
- agent_collab: OwnerAgentCollab | None = None
-
class ModuleHealthOwner(BaseModel):
name: str
diff --git a/packages/types/src/files.ts b/packages/types/src/files.ts
index 7e6128d00..cd505d224 100644
--- a/packages/types/src/files.ts
+++ b/packages/types/src/files.ts
@@ -107,10 +107,15 @@ export interface FileDetailHealth {
signals: FileSignals | null;
}
+/** Agent share (0-1) of the file's commits with a known source, null below
+ * the coverage floor with `agent_share_suppressed` set; coverage is known /
+ * all commits (0-1). Unknown commits are never counted as human. */
export interface FileAgentProvenance {
agent_commit_count: number;
agent_authored_pct: number | null;
tier_counts: Record<string, number>;
+ attribution_coverage: number | null;
+ agent_share_suppressed: string | null;
}
/** Hotspot row + history extras the detail endpoint joins in. */
@@ -118,7 +123,8 @@ export interface FileDetailGit extends Hotspot {
significant_commits: SignificantCommit[];
top_authors: FileAuthor[];
co_change_partners: CoChangePartner[];
- agent: FileAgentProvenance;
+ /** Null when attribution is off for the repository. */
+ agent: FileAgentProvenance | null;
first_commit_at: string | null;
/** The primary (blame) owner's share of current lines, 0-1. Null without
* blame; `primary_owner_commit_pct` is the same person's share of commits. */
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 70855d77b..9a032f5c8 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -105,21 +105,36 @@ export interface AgentPromptResponse {
text: string;
}
-/** One month of agent-vs-human commit volume. */
+/** One month of commits by attribution label. */
export interface AgentTrendBucket {
+ total_commits?: number;
+ agent_commits?: number;
+ human_attested_commits?: number;
+ unknown_commits?: number;
+ coverage_pct?: number | null;
+ agent_pct_of_covered?: number | null;
+ suppressed_reason?: string | null;
month: string;
- total_commits: number;
- agent_commits: number;
- agent_pct: number;
tier_counts?: Record<string, unknown>;
}
-/** Monthly agent-share trend across the indexed commit window. */
+/**
+ * Monthly attribution trend across the indexed commit window.
+ *
+ * ``enabled`` is false, with every figure empty, when AI attribution is off
+ * for the repository.
+ */
export interface AgentTrendResponse {
- buckets: AgentTrendBucket[];
- total_commits: number;
- agent_commits: number;
- agent_pct: number;
+ total_commits?: number;
+ agent_commits?: number;
+ human_attested_commits?: number;
+ unknown_commits?: number;
+ coverage_pct?: number | null;
+ agent_pct_of_covered?: number | null;
+ suppressed_reason?: string | null;
+ enabled?: boolean;
+ coverage_floor_pct: number;
+ buckets?: AgentTrendBucket[];
agent_names?: Record<string, unknown>[];
}
@@ -519,6 +534,7 @@ export interface CommitDetailResponse {
agent_name?: string | null;
agent_autonomy_tier?: number | null;
agent_confidence?: string | null;
+ attribution?: string | null;
drivers?: RiskDriverResponse[];
agent_channel?: string | null;
files?: CommitFileResponse[];
@@ -629,6 +645,7 @@ export interface CommitResponse {
agent_name?: string | null;
agent_autonomy_tier?: number | null;
agent_confidence?: string | null;
+ attribution?: string | null;
}
/**
@@ -643,7 +660,9 @@ export interface CommitStatsResponse {
total_commits: number;
high_priority_count: number;
fix_commit_count: number;
- agent_commit_count: number;
+ agent_commit_count?: number | null;
+ agent_pct_of_covered?: number | null;
+ attribution_coverage_pct?: number | null;
avg_entropy: number;
risk_histogram?: RiskHistogramBucket[];
moderate_cut?: number | null;
@@ -1780,9 +1799,11 @@ export interface GitMetadataResponse {
commit_count_capped?: boolean;
original_path?: string | null;
test_gap?: boolean | null;
- agent_commit_count?: number;
+ agent_commit_count?: number | null;
agent_authored_pct?: number | null;
- agent_tier_counts?: Record<string, unknown>;
+ agent_tier_counts?: Record<string, unknown> | null;
+ attribution_coverage?: number | null;
+ agent_share_suppressed?: string | null;
}
export interface GitSummaryResponse {
@@ -2301,20 +2322,6 @@ export interface OkResponse {
ok?: boolean;
}
-/**
- * How much coding-agent activity lands on the files this person owns.
- *
- * Aggregated from the per-file agent-provenance rollup (GitMetadata) over
- * the owner's primary-owned files — agent identity per commit lives on the
- * commits surface, the per-file rollup only carries counts and tiers.
- */
-export interface OwnerAgentCollab {
- files_with_agent_commits: number;
- agent_commit_count: number;
- agent_share_pct: number | null;
- tier_counts?: Record<string, unknown>;
-}
-
export interface OwnerCoAuthor {
name: string;
email: string | null;
@@ -2375,7 +2382,6 @@ export interface OwnerProfileResponse {
co_authors: OwnerCoAuthor[];
co_authors_total?: number;
commit_categories: Record<string, unknown>;
- agent_collab?: OwnerAgentCollab | null;
}
export interface OwnershipEntry {
diff --git a/packages/types/src/git.ts b/packages/types/src/git.ts
index 1c68bc195..95e690691 100644
--- a/packages/types/src/git.ts
+++ b/packages/types/src/git.ts
@@ -156,14 +156,18 @@ export interface Commit {
author_experience?: number | null;
/** Commits by this author across the indexed history (identities folded). */
author_commit_count?: number | null;
- /** Coding-agent attribution (deterministic local-git channels).
- * Null/undefined for human-authored commits. */
+ /** Coding-agent attribution (deterministic local-git channels). Null for
+ * human-attested and unknown commits alike; read `attribution`. */
agent_name?: string | null;
/** 1 = near-autonomous bot, 2 = human-driven agent, 3 = assisted/co-authored. */
agent_autonomy_tier?: number | null;
agent_confidence?: string | null;
+ /** agent / human_attested / unknown; null when attribution is off. */
+ attribution?: CommitAttribution | null;
}
+export type CommitAttribution = "agent" | "human_attested" | "unknown";
+
/** One feature's signed contribution to a commit's change-risk logit. */
export interface RiskDriver {
feature: string;
@@ -231,21 +235,32 @@ export interface CommitDetail extends Commit {
health?: CommitHealth | null;
}
-/** One month of agent-vs-human commit volume. */
-export interface AgentTrendBucket {
- month: string; // "YYYY-MM"
+/** Commits by attribution label, with the honest agent share. Unknown is
+ * never counted as human: `agent_pct_of_covered` is the agent share of commits
+ * with a known source (agent or human-attested), null below the coverage
+ * floor with `suppressed_reason` set. Percentages are 0-100. */
+export interface AttributionShareFields {
total_commits: number;
agent_commits: number;
- agent_pct: number; // 0-100
+ human_attested_commits: number;
+ unknown_commits: number;
+ coverage_pct: number | null;
+ agent_pct_of_covered: number | null;
+ suppressed_reason: string | null;
+}
+
+/** One month of commits by attribution label. */
+export interface AgentTrendBucket extends AttributionShareFields {
+ month: string; // "YYYY-MM"
tier_counts: Record<string, number>;
}
-/** Monthly agent-share trend across the indexed commit window. */
-export interface AgentTrend {
+/** Monthly attribution trend across the indexed commit window. `enabled` is
+ * false, with every figure empty, when attribution is off for the repo. */
+export interface AgentTrend extends AttributionShareFields {
+ enabled: boolean;
+ coverage_floor_pct: number;
buckets: AgentTrendBucket[];
- total_commits: number;
- agent_commits: number;
- agent_pct: number; // 0-100
agent_names: { name: string; count: number }[];
}
@@ -293,7 +308,13 @@ export interface CommitStats {
total_commits: number;
high_priority_count: number;
fix_commit_count: number;
- agent_commit_count: number;
+ /** Null, like the two figures below, when attribution is off. */
+ agent_commit_count: number | null;
+ /** Agent share of commits with a known source, 0-100; null below the
+ * coverage floor. */
+ agent_pct_of_covered?: number | null;
+ /** Commits with a known source / all commits, 0-100. */
+ attribution_coverage_pct?: number | null;
avg_entropy: number;
/** Binned on the raw score, not the percentile — percentile ranks are
* uniform by construction, so only the raw axis has a shape to draw. */
diff --git a/packages/types/src/owners.ts b/packages/types/src/owners.ts
index b708c29c5..7ac0778ab 100644
--- a/packages/types/src/owners.ts
+++ b/packages/types/src/owners.ts
@@ -71,16 +71,4 @@ export interface OwnerProfile {
/** Uncapped count behind the co_authors slice (for "+N more"). */
co_authors_total?: number;
commit_categories: Record<string, number>;
- /** Agent activity on this person's owned files; null when none attributed. */
- agent_collab?: OwnerAgentCollab | null;
-}
-
-/** How much coding-agent activity lands on the files this person owns. */
-export interface OwnerAgentCollab {
- files_with_agent_commits: number;
- agent_commit_count: number;
- /** Commit-weighted agent share across owned files, 0–100; null when no
- * owned file has a provenance-aware rollup yet. */
- agent_share_pct: number | null;
- tier_counts: Record<string, number>;
}
diff --git a/packages/ui/__tests__/files/file-history-tab.test.tsx b/packages/ui/__tests__/files/file-history-tab.test.tsx
index 8e0ac71e8..c487f840d 100644
--- a/packages/ui/__tests__/files/file-history-tab.test.tsx
+++ b/packages/ui/__tests__/files/file-history-tab.test.tsx
@@ -24,7 +24,13 @@ function makeGit(overrides: Partial<FileDetailGit> = {}): FileDetailGit {
significant_commits: [],
top_authors: [],
co_change_partners: [],
- agent: { agent_commit_count: 0, agent_authored_pct: null, tier_counts: {} },
+ agent: {
+ agent_commit_count: 0,
+ agent_authored_pct: null,
+ tier_counts: {},
+ attribution_coverage: null,
+ agent_share_suppressed: null,
+ },
first_commit_at: null,
...overrides,
};
diff --git a/packages/ui/__tests__/files/file-overview-tab.test.tsx b/packages/ui/__tests__/files/file-overview-tab.test.tsx
index 6956a4747..88fcc49a6 100644
--- a/packages/ui/__tests__/files/file-overview-tab.test.tsx
+++ b/packages/ui/__tests__/files/file-overview-tab.test.tsx
@@ -40,7 +40,13 @@ function makeGit(overrides: Partial<FileDetailGit> = {}): FileDetailGit {
significant_commits: [],
top_authors: [],
co_change_partners: [],
- agent: { agent_commit_count: 0, agent_authored_pct: null, tier_counts: {} },
+ agent: {
+ agent_commit_count: 0,
+ agent_authored_pct: null,
+ tier_counts: {},
+ attribution_coverage: null,
+ agent_share_suppressed: null,
+ },
first_commit_at: null,
...overrides,
};
diff --git a/packages/ui/__tests__/git/contributors-strip.test.tsx b/packages/ui/__tests__/git/contributors-strip.test.tsx
new file mode 100644
index 000000000..4bc115670
--- /dev/null
+++ b/packages/ui/__tests__/git/contributors-strip.test.tsx
@@ -0,0 +1,31 @@
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { ContributorsStrip } from "../../src/git/contributors-strip";
+
+const owners = [{ name: "Ann Lee", pct: 100, file_count: 4 }];
+
+describe("contributors strip authorship", () => {
+ it("shows unknown as its own band and never derives a human share", () => {
+ render(
+ <ContributorsStrip
+ owners={owners}
+ ownersHref="/owners"
+ commitsHref="/commits"
+ provenance={{
+ agentCommits: 2,
+ humanAttestedCommits: 0,
+ unknownCommits: 98,
+ totalCommits: 100,
+ agentPctOfCovered: null,
+ coveragePct: 2,
+ agentNames: [{ name: "claude", count: 2 }],
+ }}
+ />,
+ );
+
+ expect(screen.getAllByText("Unknown").length).toBeGreaterThan(0);
+ expect(screen.queryByText("Human")).not.toBeInTheDocument();
+ expect(screen.getByText(/coverage 2%/)).toBeInTheDocument();
+ expect(screen.queryByText(/of covered/)).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/commits/agent-trend-strip.tsx b/packages/ui/src/commits/agent-trend-strip.tsx
index 82750c7d4..e7198e8e9 100644
--- a/packages/ui/src/commits/agent-trend-strip.tsx
+++ b/packages/ui/src/commits/agent-trend-strip.tsx
@@ -9,15 +9,25 @@ export interface AgentTrendStripProps {
className?: string;
}
+function share(part: number, whole: number): number {
+ return whole > 0 ? (part / whole) * 100 : 0;
+}
+
/**
- * Compact agent-share trend: headline share plus a monthly bar strip.
- * Renders nothing when no commit in the window carries agent attribution.
+ * Compact attribution trend: the headline share plus a monthly bar strip.
+ *
+ * The share is of commits with a known source and always sits beside its
+ * coverage; below the coverage floor only the count is shown. Each bar splits
+ * a month into agent, human-attested and unknown, so unmarked commits read as
+ * unknown rather than human. Renders nothing when attribution is off or no
+ * commit in the window carries agent attribution.
*/
export function AgentTrendStrip({ trend, className }: AgentTrendStripProps) {
- if (trend.agent_commits === 0) return null;
+ if (!trend.enabled || trend.agent_commits === 0) return null;
// Cap the strip at the last 12 months so it stays a glanceable sparkline.
const buckets = trend.buckets.slice(-12);
const topAgents = trend.agent_names.slice(0, 3);
+ const coverage = Math.round(trend.coverage_pct ?? 0);
return (
<div
@@ -28,27 +38,41 @@ export function AgentTrendStrip({ trend, className }: AgentTrendStripProps) {
>
<span className="flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">
<Bot className="h-3.5 w-3.5 text-[var(--color-accent-primary)]" />
- <span className="font-semibold tabular-nums text-[var(--color-text-primary)]">
- {Math.round(trend.agent_pct)}%
- </span>
- of indexed commits are agent-attributed
+ {trend.agent_pct_of_covered != null ? (
+ <>
+ at least
+ <span className="font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {Math.round(trend.agent_pct_of_covered)}%
+ </span>
+ of covered commits are agent-attributed
+ </>
+ ) : (
+ <>
+ <span className="font-semibold tabular-nums text-[var(--color-text-primary)]">
+ {trend.agent_commits}
+ </span>
+ agent-attributed commits; too few have a known source for a share
+ </>
+ )}
<span className="tabular-nums text-[var(--color-text-tertiary)]">
- ({trend.agent_commits} of {trend.total_commits})
+ (coverage {coverage}%, {trend.unknown_commits} unknown)
</span>
</span>
- <div className="flex h-6 items-end gap-0.5" aria-label="Monthly agent share">
+ <div className="flex h-6 items-end gap-0.5" aria-label="Monthly commits by attribution">
{buckets.map((b) => (
<div
key={b.month}
- className="flex h-full w-2 items-end rounded-sm bg-[var(--color-bg-elevated)]"
- title={`${b.month}: ${Math.round(b.agent_pct)}% agent (${b.agent_commits}/${b.total_commits})`}
+ className="flex h-full w-2 flex-col justify-end overflow-hidden rounded-sm bg-[var(--color-bg-elevated)]"
+ title={`${b.month}: ${b.agent_commits} agent, ${b.human_attested_commits} human-attested, ${b.unknown_commits} unknown`}
>
<div
- className="w-full rounded-sm bg-[var(--color-accent-primary)]/70"
- style={{
- height: `${Math.max(b.agent_pct, b.agent_commits > 0 ? 8 : 0)}%`,
- }}
+ className="w-full bg-[var(--color-text-tertiary)]/40"
+ style={{ height: `${share(b.human_attested_commits, b.total_commits)}%` }}
+ />
+ <div
+ className="w-full bg-[var(--color-accent-primary)]/70"
+ style={{ height: `${share(b.agent_commits, b.total_commits)}%` }}
/>
</div>
))}
diff --git a/packages/ui/src/commits/commit-table.tsx b/packages/ui/src/commits/commit-table.tsx
index 11d155efa..5462adb12 100644
--- a/packages/ui/src/commits/commit-table.tsx
+++ b/packages/ui/src/commits/commit-table.tsx
@@ -13,7 +13,7 @@ import { cn } from "../lib/cn";
import type { Commit, ReviewPriority } from "@repowise-dev/types/git";
export type CommitSort = "risk" | "date";
-export type CommitAuthorship = "all" | "human" | "agent";
+export type CommitAuthorship = "all" | "human" | "agent" | "unknown";
export type CommitKind = "all" | "high" | "fixes";
export interface CommitTableProps {
@@ -231,8 +231,9 @@ export function CommitTable({
{(
[
{ key: "all", label: "Everyone" },
- { key: "human", label: "Humans" },
{ key: "agent", label: "Agents" },
+ { key: "human", label: "Human-attested" },
+ { key: "unknown", label: "Unknown" },
] as { key: CommitAuthorship; label: string }[]
).map((a) => (
<button
diff --git a/packages/ui/src/commits/commits-lede.tsx b/packages/ui/src/commits/commits-lede.tsx
index d8d713844..8181994a7 100644
--- a/packages/ui/src/commits/commits-lede.tsx
+++ b/packages/ui/src/commits/commits-lede.tsx
@@ -37,7 +37,6 @@ export function CommitsLede({ stats, base, LinkComponent }: CommitsLedeProps) {
const total = stats.total_commits;
const highPct = pct(stats.high_priority_count, total);
const fixPct = pct(stats.fix_commit_count, total);
- const agentPct = pct(stats.agent_commit_count, total);
const reads: ReadItem[] = [
{
@@ -49,13 +48,19 @@ export function CommitsLede({ stats, base, LinkComponent }: CommitsLedeProps) {
href: `${base}/code-health?tab=triage`,
},
];
- if (stats.agent_commit_count > 0) {
+ if (stats.agent_commit_count != null && stats.agent_commit_count > 0) {
+ // The share is of commits with a known source, never of all commits:
+ // a commit without a marker is unknown, not human.
+ const coverage = Math.round(stats.attribution_coverage_pct ?? 0);
reads.push({
key: "agent",
label: "Written by an agent",
value: stats.agent_commit_count.toLocaleString(),
- unit: `${agentPct}%`,
- why: "Read from commit trailers, so it counts what was declared.",
+ unit:
+ stats.agent_pct_of_covered != null
+ ? `at least ${Math.round(stats.agent_pct_of_covered)}% of covered, coverage ${coverage}%`
+ : `coverage ${coverage}%`,
+ why: "Read from public markers such as bot authors, trailers and notes. Commits without one are unknown, so the share is of covered commits only.",
href: `${base}/commits`,
});
}
diff --git a/packages/ui/src/files/file-history-tab.tsx b/packages/ui/src/files/file-history-tab.tsx
index a1a0d1f6e..9526ef368 100644
--- a/packages/ui/src/files/file-history-tab.tsx
+++ b/packages/ui/src/files/file-history-tab.tsx
@@ -44,8 +44,12 @@ export function FileHistoryTab({
}
const hasCategories = Object.values(git.commit_categories ?? {}).some((v) => v > 0);
+ // Null when attribution is off for the repo. The share is of commits with a
+ // known source and travels with its coverage; unknown is never human.
+ const agent = git.agent;
const agentPct =
- git.agent.agent_authored_pct != null ? Math.round(git.agent.agent_authored_pct * 100) : null;
+ agent?.agent_authored_pct != null ? Math.round(agent.agent_authored_pct * 100) : null;
+ const agentCoverage = Math.round((agent?.attribution_coverage ?? 0) * 100);
// Same helper the wiki sidebar uses, so one file's history reads identically
// on both surfaces. Null means nothing counted: render nothing.
const summary = summarizeFixHistory(git.prior_defect_count, git.last_fix_at, git.bug_magnet);
@@ -152,12 +156,13 @@ export function FileHistoryTab({
description={
<>
Commit share by author across the indexed history
- {git.agent.agent_commit_count > 0 && (
+ {agent && agent.agent_commit_count > 0 && (
<>
, and how much of it came from a coding agent —{" "}
- <Fig>{formatNumber(git.agent.agent_commit_count)}</Fig>{" "}
- {git.agent.agent_commit_count === 1 ? "commit" : "commits"}
- {agentPct != null && <> ({agentPct}%)</>}
+ <Fig>{formatNumber(agent.agent_commit_count)}</Fig>{" "}
+ {agent.agent_commit_count === 1 ? "commit" : "commits"} (
+ {agentPct != null && <>at least {agentPct}% of covered, </>}
+ coverage {agentCoverage}%)
</>
)}
.
@@ -181,22 +186,24 @@ export function FileHistoryTab({
/>
)}
</div>
- <div className="min-w-0">
- <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
- Agent share
- </p>
- {git.agent.agent_commit_count === 0 ? (
- <p className="mt-2 text-sm text-[var(--color-text-tertiary)]">
- No agent-attributed commits on this file.
+ {agent && (
+ <div className="min-w-0">
+ <p className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Agent share
</p>
- ) : (
- Object.keys(git.agent.tier_counts).length > 0 && (
- <div className="mt-3">
- <AgentTierBar tierCounts={git.agent.tier_counts} />
- </div>
- )
- )}
- </div>
+ {agent.agent_commit_count === 0 ? (
+ <p className="mt-2 text-sm text-[var(--color-text-tertiary)]">
+ No agent-attributed commits on this file.
+ </p>
+ ) : (
+ Object.keys(agent.tier_counts).length > 0 && (
+ <div className="mt-3">
+ <AgentTierBar tierCounts={agent.tier_counts} />
+ </div>
+ )
+ )}
+ </div>
+ )}
</div>
</FileSection>
diff --git a/packages/ui/src/git/contributors-strip.tsx b/packages/ui/src/git/contributors-strip.tsx
index 576dd35c0..979230403 100644
--- a/packages/ui/src/git/contributors-strip.tsx
+++ b/packages/ui/src/git/contributors-strip.tsx
@@ -11,11 +11,18 @@ export interface StripOwner {
email?: string | undefined;
}
+/** Commits by attribution label, as `/commits/agent-trend` reports them.
+ * Unknown commits are their own band and are never shown as human. */
export interface StripProvenance {
- /** Share of indexed commits attributed to coding agents, 0–100. */
- agentPct: number;
agentCommits: number;
+ humanAttestedCommits: number;
+ unknownCommits: number;
totalCommits: number;
+ /** Agent share of commits with a known source, 0–100; null below the
+ * coverage floor. */
+ agentPctOfCovered: number | null;
+ /** Commits with a known source / all commits, 0–100. */
+ coveragePct: number | null;
/** Per-agent commit counts, biggest first. */
agentNames: { name: string; count: number }[];
}
@@ -24,12 +31,24 @@ interface ContributorsStripProps {
owners: StripOwner[];
/** Approx number of distinct contributors (defaults to owners.length). */
contributorCount?: number;
- /** Agent-vs-human authorship; omit/null when provenance isn't indexed. */
+ /** Attribution by label; omit/null when attribution is off or not indexed. */
provenance?: StripProvenance | null;
ownersHref: string;
commitsHref: string;
}
+function authorshipSegments(p: StripProvenance) {
+ const share = (n: number) => (n / p.totalCommits) * 100;
+ const shown = p.agentNames.slice(0, 3);
+ const rest = p.agentNames.slice(3).reduce((sum, a) => sum + a.count, 0);
+ return [
+ ...shown.map((a) => ({ key: a.name, label: a.name, value: share(a.count) })),
+ { key: "__other_agents", label: "Other agents", value: share(rest) },
+ { key: "__human_attested", label: "Human-attested", value: share(p.humanAttestedCommits) },
+ { key: "__unknown", label: "Unknown", value: share(p.unknownCommits), tail: true },
+ ];
+}
+
function firstName(name: string): string {
return name.split(/\s+/)[0] ?? name;
}
@@ -102,10 +121,16 @@ export function ContributorsStrip({
href={commitsHref}
className="text-xs tabular-nums text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)] transition-colors"
>
- <span className="font-semibold text-[var(--color-accent-primary)]">
- {Math.round(provenance!.agentPct)}%
- </span>{" "}
- agent-written
+ {provenance!.agentPctOfCovered != null && (
+ <>
+ at least{" "}
+ <span className="font-semibold text-[var(--color-accent-primary)]">
+ {Math.round(provenance!.agentPctOfCovered)}%
+ </span>{" "}
+ of covered,{" "}
+ </>
+ )}
+ coverage {Math.round(provenance!.coveragePct ?? 0)}%
</a>
<InfoTip content={AGENT_PCT_HINT} label="How agent authorship is measured" />
</span>
@@ -113,16 +138,10 @@ export function ContributorsStrip({
<ProportionBar
label="Commits by author"
size="sm"
- segments={[
- { key: "human", label: "Human", value: 100 - provenance!.agentPct },
- ...provenance!.agentNames.map((a) => ({
- key: a.name,
- label: a.name,
- value: (a.count / provenance!.totalCommits) * 100,
- })),
- ]}
- maxSegments={3}
- othersLabel={() => "Other agents"}
+ // Agents first, then the known human band, then unknown, in
+ // that fixed order so unknown never folds into another band.
+ sort={false}
+ segments={authorshipSegments(provenance!)}
/>
</div>
)}
diff --git a/packages/ui/src/owners/owner-profile.tsx b/packages/ui/src/owners/owner-profile.tsx
index 827b87352..f412c88d8 100644
--- a/packages/ui/src/owners/owner-profile.tsx
+++ b/packages/ui/src/owners/owner-profile.tsx
@@ -138,22 +138,6 @@ export function OwnerProfileView({
href: `${base}/owners`,
});
}
- if (owner.agent_collab && owner.agent_collab.agent_commit_count > 0) {
- const a = owner.agent_collab;
- reads.push({
- key: "agent",
- label: "Agent-assisted",
- value: a.agent_commit_count.toLocaleString(),
- unit: "commits",
- why:
- (a.agent_share_pct != null
- ? `${a.agent_share_pct.toFixed(2)}% of the commits on their owned files carry a coding-agent trailer. `
- : "Read from commit trailers, so it counts what was declared. ") +
- `${a.files_with_agent_commits.toLocaleString()} owned ${a.files_with_agent_commits === 1 ? "file has" : "files have"} one.`,
- href: `${base}/commits`,
- });
- }
-
// Volume figures, none of which appear in the lede, the reads column or a
// section below. The two line counts are the payload's `_est` fields, so an
// exact six-digit figure would claim a precision the number does not have.
diff --git a/packages/ui/src/stats/stat-callout.tsx b/packages/ui/src/stats/stat-callout.tsx
index e3912a49d..d7ad05c8b 100644
--- a/packages/ui/src/stats/stat-callout.tsx
+++ b/packages/ui/src/stats/stat-callout.tsx
@@ -8,7 +8,7 @@ export type CalloutTone = "default" | "accent" | "success" | "warning" | "info";
export const NLOC_HINT =
"Lines of code in the repo today: non-blank, non-comment lines, excluding lockfiles, generated and vendored files. Not a historical total: deleted code doesn't count.";
export const AGENT_PCT_HINT =
- "Share of commits with a verifiable agent signature: known bot identities, agent commit footers, or Co-authored-by agent trailers. Squash merges that drop trailers and agents committing under a human git identity can't be detected, so the true share may be higher.";
+ "Agent share of the commits whose source is known: known bot identities, agent commit footers or trailers, git-ai notes and Agent Trace records. Commits without any of these are unknown, never counted as human, so the share is shown beside its coverage and withheld when coverage is below 30%.";
const TONE_VALUE: Record<CalloutTone, string> = {
default: "text-[var(--color-text-primary)]",
diff --git a/packages/web/src/app/repos/[id]/commits/page.tsx b/packages/web/src/app/repos/[id]/commits/page.tsx
index 2fafaa20f..10d800911 100644
--- a/packages/web/src/app/repos/[id]/commits/page.tsx
+++ b/packages/web/src/app/repos/[id]/commits/page.tsx
@@ -104,7 +104,7 @@ export default async function CommitsPage({
</OverviewSection>
)}
- {trend && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
+ {trend && trend.enabled && trend.agent_commits > 0 && <AgentTrendStrip trend={trend} />}
<OverviewSection
title={t("reviewQueueTitle")}
@@ -115,6 +115,7 @@ export default async function CommitsPage({
repoId={id}
initial={firstPage}
total={total}
+ attributionEnabled={trend?.enabled !== false}
counts={
stats
? {
diff --git a/packages/web/src/components/commits/commit-queue.tsx b/packages/web/src/components/commits/commit-queue.tsx
index b53c11fe0..845e7e02d 100644
--- a/packages/web/src/components/commits/commit-queue.tsx
+++ b/packages/web/src/components/commits/commit-queue.tsx
@@ -29,12 +29,15 @@ export function CommitQueue({
initial,
total,
counts,
+ attributionEnabled = true,
}: {
repoId: string;
initial: Paginated<CommitResponse>;
total: number;
/** Repo-wide chip counts, from the stats endpoint the page already fetches. */
counts?: { all: number; high: number; fixes: number } | undefined;
+ /** False when AI attribution is off for the repo: no authorship filter. */
+ attributionEnabled?: boolean;
}) {
const [sort, setSort] = useState<CommitSort>("date");
const [authorship, setAuthorship] = useState<CommitAuthorship>("all");
@@ -90,10 +93,14 @@ export function CommitQueue({
reset();
}}
authorship={authorship}
- onAuthorshipChange={(a) => {
- setAuthorship(a);
- reset();
- }}
+ onAuthorshipChange={
+ attributionEnabled
+ ? (a) => {
+ setAuthorship(a);
+ reset();
+ }
+ : undefined
+ }
kind={kind}
onKindChange={(k) => {
setKind(k);
diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsx
index b252b33a5..188af1e5c 100644
--- a/packages/web/src/components/docs/docs-viewer.tsx
+++ b/packages/web/src/components/docs/docs-viewer.tsx
@@ -262,11 +262,17 @@ function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: string
</span>
<span className="font-mono">{data.contributor_count}</span>
</div>
- {data.agent_authored_pct != null && (data.agent_commit_count ?? 0) > 0 && (
+ {(data.agent_commit_count ?? 0) > 0 && (
+ // Share of commits with a known source, beside that coverage;
+ // withheld below the coverage floor. Unknown is never human.
<div className="flex items-center justify-between gap-2">
<span className="text-[var(--color-text-tertiary)]">Agent-authored</span>
<span className="font-mono">
- {Math.round(data.agent_authored_pct * 100)}% · {data.agent_commit_count}
+ {data.agent_authored_pct != null
+ ? `≥${Math.round(data.agent_authored_pct * 100)}% of covered · `
+ : ""}
+ {data.agent_commit_count} · coverage{" "}
+ {Math.round((data.attribution_coverage ?? 0) * 100)}%
</span>
</div>
)}
diff --git a/tests/unit/cli/test_attribution_cmd.py b/tests/unit/cli/test_attribution_cmd.py
new file mode 100644
index 000000000..c2196efff
--- /dev/null
+++ b/tests/unit/cli/test_attribution_cmd.py
@@ -0,0 +1,164 @@
+"""`repowise attribution status` and `purge` against a real local index."""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.attribution_cmd import attribution_group
+from repowise.cli.helpers import run_async
+
+
+async def _store(repo_path: Path) -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.crud import upsert_git_commits_bulk, upsert_git_metadata
+
+ (repo_path / ".repowise").mkdir(exist_ok=True)
+ engine = create_engine(f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}")
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await upsert_repository(session, name="repo", local_path=str(repo_path))
+ rows = [
+ {
+ "sha": f"{label[0]}{i:09d}",
+ "author_name": "A",
+ "author_email": "[email protected]",
+ "committed_at": datetime.fromtimestamp(1000 + i, tz=UTC),
+ "subject": "x",
+ "attribution": label,
+ "agent_name": "claude" if label == "agent" else None,
+ }
+ for i, label in enumerate(["agent"] * 3 + ["human_attested"] + ["unknown"] * 6)
+ ]
+ await upsert_git_commits_bulk(session, repo.id, rows)
+ await upsert_git_metadata(
+ session,
+ repository_id=repo.id,
+ file_path="a.py",
+ commit_count_total=10,
+ agent_commit_count=3,
+ attribution_known_count=4,
+ agent_authored_pct=0.75,
+ agent_line_count=12,
+ )
+ finally:
+ await engine.dispose()
+
+
+async def _labels(repo_path: Path) -> tuple[list, list]:
+ from sqlalchemy import select
+
+ from repowise.core.persistence import create_engine
+ from repowise.core.persistence.models import GitCommit, GitMetadata
+
+ engine = create_engine(f"sqlite+aiosqlite:///{(repo_path / '.repowise' / 'wiki.db').as_posix()}")
+ try:
+ async with engine.connect() as conn:
+ commits = (await conn.execute(select(GitCommit.agent_name, GitCommit.attribution))).all()
+ meta = (
+ await conn.execute(
+ select(
+ GitMetadata.agent_commit_count,
+ GitMetadata.agent_authored_pct,
+ GitMetadata.agent_line_count,
+ )
+ )
+ ).all()
+ return [tuple(r) for r in commits], [tuple(r) for r in meta]
+ finally:
+ await engine.dispose()
+
+
+def indexed_repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)
+ root = (tmp_path / "repo").resolve()
+ root.mkdir()
+ run_async(_store(root))
+ return root
+
+
+def test_status_reports_settings_layers_and_coverage(indexed_repo: Path) -> None:
+ (indexed_repo / ".repowise" / "config.yaml").write_text(
+ "attribution:\n capture: local\n agents: [codex, nope]\n", encoding="utf-8"
+ )
+ result = CliRunner().invoke(attribution_group, ["status", str(indexed_repo), "--format", "json"])
+ assert result.exit_code == 0, result.output
+ data = json.loads(result.output)
+ assert data["effective"] == {"enabled": True, "capture": "off", "agents": []}
+ assert data["repo"]["capture"] == "local"
+ assert data["repo"]["agents"] == ["codex"]
+ assert data["user"]["capture"] is None
+ assert any("nope" in e for e in data["errors"])
+ assert data["commits"] == {"agent": 3, "human_attested": 1, "unknown": 6}
+ assert data["coverage"] == pytest.approx(0.4)
+ assert data["agent_share_of_covered"] == pytest.approx(0.75)
+
+
+def test_status_text_when_disabled(indexed_repo: Path) -> None:
+ (indexed_repo / ".repowise" / "config.yaml").write_text(
+ "attribution:\n enabled: false\n", encoding="utf-8"
+ )
+ result = CliRunner().invoke(attribution_group, ["status", str(indexed_repo)])
+ assert result.exit_code == 0, result.output
+ assert "Nothing about AI is stored or shown" in result.output
+ assert "commits" not in result.output
+
+
+def test_purge_asks_first_and_clears_derived_rows(indexed_repo: Path) -> None:
+ declined = CliRunner().invoke(attribution_group, ["purge", str(indexed_repo)], input="n\n")
+ assert declined.exit_code == 0
+ commits, _ = run_async(_labels(indexed_repo))
+ assert ("claude", "agent") in commits
+
+ result = CliRunner().invoke(attribution_group, ["purge", str(indexed_repo), "--yes"])
+ assert result.exit_code == 0, result.output
+ commits, meta = run_async(_labels(indexed_repo))
+ assert set(commits) == {(None, None)}
+ assert meta == [(0, None, 0)]
+
+
+def test_purge_leaves_third_party_git_ai_notes(indexed_repo: Path) -> None:
+ import subprocess
+
+ def git(*args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=indexed_repo, check=True, capture_output=True, text=True
+ ).stdout
+
+ git("init", "-q")
+ git("config", "user.email", "[email protected]")
+ git("config", "user.name", "A")
+ (indexed_repo / "a.py").write_text("x = 1\n", encoding="utf-8")
+ git("add", "a.py")
+ git("commit", "-q", "-m", "init")
+ note = 'a.py\n h_0123456789abcd 1\n---\n{"schema_version": "authorship/3.0.0", "prompts": {}}'
+ git("notes", "--ref=ai", "add", "-m", note, "HEAD")
+
+ result = CliRunner().invoke(attribution_group, ["purge", str(indexed_repo), "--yes"])
+ assert result.exit_code == 0, result.output
+ assert "h_0123456789abcd" in git("notes", "--ref=ai", "show", "HEAD")
+
+
+def test_status_explains_a_value_the_other_layer_overrides(indexed_repo: Path) -> None:
+ (indexed_repo / ".repowise" / "config.yaml").write_text(
+ "attribution:\n capture: notes\n", encoding="utf-8"
+ )
+ result = CliRunner().invoke(attribution_group, ["status", str(indexed_repo), "--format", "json"])
+ assert result.exit_code == 0, result.output
+ (reason,) = json.loads(result.output)["explanations"]
+ assert reason.startswith("capture: the repo config sets notes, but off applies")
+ assert "the user config does not set it" in reason
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 650f62b14..6fdb42b57 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -33,8 +33,8 @@ from repowise.core.registry import CLIRegistry, LazyCommand
#: command is meant to require editing it.
_EXPECTED_NAMES = frozenset(
{
- "agents", "ask", "augment", "components", "config", "context", "corrections", "costs",
- "coverage",
+ "agents", "ask", "attribution", "augment", "components", "config", "context", "corrections",
+ "costs", "coverage",
"dead-code", "decision", "delete", "distill", "doc-drift", "doctor",
"expand",
"export", "generate", "generate-claude-md", "health", "hook",
diff --git a/tests/unit/ingestion/test_agent_provenance.py b/tests/unit/ingestion/test_agent_provenance.py
index e6ce04179..567ee952e 100644
--- a/tests/unit/ingestion/test_agent_provenance.py
+++ b/tests/unit/ingestion/test_agent_provenance.py
@@ -20,6 +20,7 @@ from repowise.core.ingestion.git_commit_index import (
from repowise.core.ingestion.git_indexer.agent_provenance import (
AgentProvenanceClassifier,
AgentTraceIndex,
+ GitAiNote,
_agent_from_git_ai_note,
_agent_from_trace_record,
_count_distinct_lines,
@@ -331,7 +332,7 @@ def test_load_git_ai_note_agents_parses_present_ref() -> None:
note = _git_ai_note("cursor")
repo.git.log.return_value = f"\x00sha_agent\x1f{note}\n\x00sha_human\x1f\n"
agents = load_git_ai_note_agents(repo, 100)
- assert agents == {"sha_agent": "cursor"}
+ assert agents == {"sha_agent": GitAiNote(agent="cursor")}
# ---------------------------------------------------------------------------
@@ -416,7 +417,11 @@ def test_walk_carries_provenance_into_sink_rows_and_rollup() -> None:
assert rows["ccc"]["agent_autonomy_tier"] == 1
assert rows["ccc"]["agent_confidence"] == "high"
- # Per-file rollup: 2 of 3 commits agent-attributed, tiers {1: 1, 2: 1}.
+ assert by_sha["aaa"]["attribution"] == "unknown"
+ assert rows["bbb"]["attribution"] == "agent"
+
+ # Per-file rollup: 2 agent commits, 1 unknown. The share is of the known
+ # commits only; the unknown one is never counted as human.
meta = index_file(
repo,
"src/a.py",
@@ -427,11 +432,12 @@ def test_walk_carries_provenance_into_sink_rows_and_rollup() -> None:
precomputed_commits=index["src/a.py"],
)
assert meta["agent_commit_count"] == 2
- assert abs(meta["agent_authored_pct"] - 2 / 3) < 1e-9
+ assert meta["attribution_known_count"] == 2
+ assert meta["agent_authored_pct"] == 1.0
assert json.loads(meta["agent_tier_counts_json"]) == {"1": 1, "2": 1}
-def test_rollup_zero_for_human_only_history() -> None:
+def test_rollup_has_no_share_for_unmarked_history() -> None:
commits = [
_CommitRec(
sha=f"s{i}",
@@ -453,7 +459,8 @@ def test_rollup_zero_for_human_only_history() -> None:
precomputed_commits=commits,
)
assert meta["agent_commit_count"] == 0
- assert meta["agent_authored_pct"] == 0.0
+ assert meta["attribution_known_count"] == 0
+ assert meta["agent_authored_pct"] is None
assert json.loads(meta["agent_tier_counts_json"]) == {}
diff --git a/tests/unit/ingestion/test_git_update_equivalence.py b/tests/unit/ingestion/test_git_update_equivalence.py
index cba7784bf..e848d1ac1 100644
--- a/tests/unit/ingestion/test_git_update_equivalence.py
+++ b/tests/unit/ingestion/test_git_update_equivalence.py
@@ -37,6 +37,7 @@ _COMPARED_FIELDS = [
"bus_factor",
"prior_defect_count",
"agent_commit_count",
+ "attribution_known_count",
"agent_authored_pct",
"agent_tier_counts_json",
]
@@ -104,7 +105,9 @@ async def test_update_path_classifies_agent_provenance(tmp_path) -> None:
(meta,) = upd_meta
assert meta["agent_commit_count"] == 1
- assert meta["agent_authored_pct"] == pytest.approx(0.5)
+ # One agent commit and one unmarked: the share is of the known commit only.
+ assert meta["attribution_known_count"] == 1
+ assert meta["agent_authored_pct"] == pytest.approx(1.0)
assert meta["agent_tier_counts_json"] != "{}"
diff --git a/tests/unit/server/golden/ownership_rollups.json b/tests/unit/server/golden/ownership_rollups.json
index ce9e6d185..42b2c6990 100644
--- a/tests/unit/server/golden/ownership_rollups.json
+++ b/tests/unit/server/golden/ownership_rollups.json
@@ -169,15 +169,6 @@
"commit_categories": {
"fix": 2,
"feature": 4
- },
- "agent_collab": {
- "files_with_agent_commits": 1,
- "agent_commit_count": 10,
- "agent_share_pct": 20.0,
- "tier_counts": {
- "confirmed": 6,
- "likely": 4
- }
}
},
@@ -257,12 +248,6 @@
"commit_categories": {
"fix": 0,
"feature": 1
- },
- "agent_collab": {
- "files_with_agent_commits": 0,
- "agent_commit_count": 0,
- "agent_share_pct": 0.0,
- "tier_counts": {}
}
},
"name:Carol": {
@@ -327,8 +312,7 @@
"commit_categories": {
"fix": 0,
"feature": 0
- },
- "agent_collab": null
+ }
}
},
"modules": {
diff --git a/tests/unit/server/mcp/test_context_attribution.py b/tests/unit/server/mcp/test_context_attribution.py
new file mode 100644
index 000000000..a3b221fd3
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_attribution.py
@@ -0,0 +1,49 @@
+"""get_context ownership: the agent figure is an honest share, and absent when off."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from sqlalchemy import update
+
+from repowise.core import attribution
+from repowise.core.persistence.models import GitMetadata
+
+
[email protected](autouse=True)
+def _private_user_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ user_file = tmp_path / "home" / ".repowise" / "config.yaml"
+ monkeypatch.setattr(attribution, "user_config_path", lambda: user_file)
+
+
+async def _ownership(setup_mcp, factory) -> dict:
+ from repowise.server.mcp_server import get_context
+
+ async with factory() as s:
+ await s.execute(
+ update(GitMetadata)
+ .where(GitMetadata.id == "gm1")
+ .values(commit_count_total=10, agent_commit_count=2, attribution_known_count=2)
+ )
+ await s.commit()
+ result = await get_context(["src/auth/service.py"], include=["ownership"], compact=False)
+ return result["targets"]["src/auth/service.py"]["ownership"]
+
+
+async def test_agent_share_replaces_the_raw_percentage(setup_mcp, factory) -> None:
+ ownership = await _ownership(setup_mcp, factory)
+ assert "agent_authored_pct" not in ownership
+ # 2 of 10 commits have a known source: below the floor, so no share.
+ assert ownership["agent_share"] == "withheld: coverage 20% is below 30%"
+ assert ownership["agent_commit_count"] == 2
+
+
+async def test_no_agent_fields_when_attribution_is_off(setup_mcp, factory, tmp_path) -> None:
+ config = tmp_path / ".repowise" / "config.yaml"
+ config.parent.mkdir(parents=True, exist_ok=True)
+ config.write_text("attribution:\n enabled: false\n", encoding="utf-8")
+ ownership = await _ownership(setup_mcp, factory)
+ assert not any(key.startswith("agent") for key in ownership)
diff --git a/tests/unit/server/test_attribution_surfaces.py b/tests/unit/server/test_attribution_surfaces.py
new file mode 100644
index 000000000..5d8ff1062
--- /dev/null
+++ b/tests/unit/server/test_attribution_surfaces.py
@@ -0,0 +1,176 @@
+"""AI attribution on the HTTP surfaces: honest shares, and nothing when it is off.
+
+With attribution on, every share is of commits with a known source and travels
+with its coverage; unknown commits are never counted as human. With
+``attribution.enabled: false`` in the repo config, no endpoint carries an AI
+field, even when an earlier index stored some.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+from pathlib import Path
+from urllib.parse import quote
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core import attribution
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
[email protected](autouse=True)
+def _private_user_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ user_file = tmp_path / "home" / ".repowise" / "config.yaml"
+ monkeypatch.setattr(attribution, "user_config_path", lambda: user_file)
+
+
+def _commit(sha: str, ts: int, **over) -> dict:
+ row = {
+ "sha": sha,
+ "author_name": "Ann",
+ "author_email": "[email protected]",
+ "committed_at": datetime.fromtimestamp(ts, tz=UTC),
+ "subject": f"commit {sha}",
+ "change_risk_score": 2.0,
+ "change_risk_level": "low",
+ }
+ row.update(over)
+ return row
+
+
+async def _seed(app, repo_id: str) -> None:
+ """Ten commits: 3 agent, 2 human-attested, 5 unknown (coverage 50%)."""
+ agent = {
+ "agent_name": "claude",
+ "agent_autonomy_tier": 2,
+ "agent_channel": "message_footer",
+ "agent_confidence": "high",
+ "attribution": "agent",
+ }
+ rows = [_commit(f"a{i:09d}", 1000 + i, **agent) for i in range(3)]
+ rows += [
+ _commit(f"h{i:09d}", 2000 + i, attribution="human_attested", agent_channel="git_ai_note")
+ for i in range(2)
+ ]
+ rows += [_commit(f"u{i:09d}", 3000 + i, attribution="unknown") for i in range(5)]
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_git_commits_bulk(session, repo_id, rows)
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo_id,
+ file_path="src/main.py",
+ commit_count_total=10,
+ commit_count_90d=10,
+ commit_count_30d=0,
+ primary_owner_name="Ann",
+ primary_owner_email="[email protected]",
+ primary_owner_commit_pct=1.0,
+ top_authors_json=json.dumps([{"name": "Ann", "commit_count": 10}]),
+ agent_commit_count=3,
+ attribution_known_count=5,
+ agent_authored_pct=0.6,
+ agent_tier_counts_json=json.dumps({"2": 3}),
+ )
+
+
+def _disable(repo: dict) -> None:
+ config = Path(repo["local_path"]) / ".repowise" / "config.yaml"
+ config.parent.mkdir(parents=True, exist_ok=True)
+ config.write_text("attribution:\n enabled: false\n", encoding="utf-8")
+
+
+async def test_agent_trend_reports_coverage_and_share_of_covered(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+
+ data = (await client.get(f"/api/repos/{repo['id']}/commits/agent-trend")).json()
+ assert data["enabled"] is True
+ assert data["coverage_floor_pct"] == 30.0
+ assert (data["agent_commits"], data["human_attested_commits"], data["unknown_commits"]) == (
+ 3,
+ 2,
+ 5,
+ )
+ assert data["coverage_pct"] == 50.0
+ assert data["agent_pct_of_covered"] == 60.0 # 3 of 5 known, never 3 of 10
+ assert data["suppressed_reason"] is None
+ assert sum(b["unknown_commits"] for b in data["buckets"]) == 5
+
+
+async def test_commit_filters_use_the_three_states(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ url = f"/api/repos/{repo['id']}/commits"
+
+ for authorship, expected in (("agent", 3), ("human", 2), ("unknown", 5), ("all", 10)):
+ page = (await client.get(url, params={"authorship": authorship, "limit": 50})).json()
+ assert page["total"] == expected, authorship
+ human = (await client.get(url, params={"authorship": "human"})).json()["items"]
+ assert {c["attribution"] for c in human} == {"human_attested"}
+
+
+async def test_stats_and_file_shares_are_of_covered(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ rid = repo["id"]
+
+ stats = (await client.get(f"/api/repos/{rid}/commits/stats")).json()
+ assert stats["agent_commit_count"] == 3
+ assert stats["agent_pct_of_covered"] == 60.0
+ assert stats["attribution_coverage_pct"] == 50.0
+
+ meta = (
+ await client.get(f"/api/repos/{rid}/git-metadata", params={"file_path": "src/main.py"})
+ ).json()
+ assert meta["agent_authored_pct"] == pytest.approx(0.6)
+ assert meta["attribution_coverage"] == pytest.approx(0.5)
+ assert meta["agent_share_suppressed"] is None
+
+ detail = (await client.get(f"/api/repos/{rid}/files/src/main.py")).json()
+ assert detail["git"]["agent"]["agent_authored_pct"] == pytest.approx(0.6)
+
+ # Never per person: the owner profile carries no AI figure.
+ owner = (await client.get(f"/api/repos/{rid}/owners/{quote('[email protected]', safe='')}")).json()
+ assert "agent_collab" not in owner
+
+
+async def test_disabled_attribution_shows_nothing_about_ai(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app, repo["id"])
+ _disable(repo)
+ rid = repo["id"]
+
+ trend = (await client.get(f"/api/repos/{rid}/commits/agent-trend")).json()
+ assert trend["enabled"] is False
+ assert trend["buckets"] == [] and trend["agent_names"] == []
+ assert trend["agent_commits"] == 0 and trend["agent_pct_of_covered"] is None
+
+ # The filter is ignored rather than revealing which commits were labelled.
+ page = (await client.get(f"/api/repos/{rid}/commits", params={"authorship": "agent"})).json()
+ assert page["total"] == 10
+ for c in page["items"]:
+ assert c["agent_name"] is None and c["attribution"] is None
+
+ detail = (await client.get(f"/api/repos/{rid}/commits/a000000000")).json()
+ assert detail["agent_name"] is None and detail["agent_channel"] is None
+
+ stats = (await client.get(f"/api/repos/{rid}/commits/stats")).json()
+ assert stats["agent_commit_count"] is None
+ assert stats["agent_pct_of_covered"] is None
+
+ meta = (
+ await client.get(f"/api/repos/{rid}/git-metadata", params={"file_path": "src/main.py"})
+ ).json()
+ for key in ("agent_commit_count", "agent_authored_pct", "agent_tier_counts"):
+ assert meta[key] is None
+
+ file_detail = (await client.get(f"/api/repos/{rid}/files/src/main.py")).json()
+ assert file_detail["git"]["agent"] is None
diff --git a/tests/unit/server/test_git.py b/tests/unit/server/test_git.py
index dd258fe17..562c543b6 100644
--- a/tests/unit/server/test_git.py
+++ b/tests/unit/server/test_git.py
@@ -599,9 +599,14 @@ async def test_commits_authorship_filter(client: AsyncClient, app) -> None:
assert agents.json()["total"] == 1
assert agents.json()["items"][0]["agent_name"] == "claude-code"
+ # No commit carries a human attestation: unmarked commits are unknown, never human.
humans = await client.get(f"/api/repos/{repo['id']}/commits", params={"authorship": "human"})
- assert humans.json()["total"] == 3
- assert all(c["agent_name"] is None for c in humans.json()["items"])
+ assert humans.json()["total"] == 0
+ unknown = await client.get(
+ f"/api/repos/{repo['id']}/commits", params={"authorship": "unknown"}
+ )
+ assert unknown.json()["total"] == 3
+ assert all(c["attribution"] == "unknown" for c in unknown.json()["items"])
@pytest.mark.asyncio
@@ -647,9 +652,15 @@ async def test_agent_trend(client: AsyncClient, app) -> None:
resp = await client.get(f"/api/repos/{repo['id']}/commits/agent-trend")
assert resp.status_code == 200
data = resp.json()
+ assert data["enabled"] is True
assert data["total_commits"] == 4
assert data["agent_commits"] == 1
- assert data["agent_pct"] == 25.0
+ assert data["unknown_commits"] == 3
+ assert data["human_attested_commits"] == 0
+ # 1 of 4 commits has a known source: below the floor, so no share is shown.
+ assert data["coverage_pct"] == 25.0
+ assert data["agent_pct_of_covered"] is None
+ assert data["suppressed_reason"] == "coverage_below_floor"
assert data["agent_names"] == [{"name": "claude-code", "count": 1}]
# All four fixture commits share the epoch-1970 month bucket.
assert len(data["buckets"]) == 1
diff --git a/tests/unit/server/test_git_schema_partners.py b/tests/unit/server/test_git_schema_partners.py
index cd1dec69c..0242fb2a1 100644
--- a/tests/unit/server/test_git_schema_partners.py
+++ b/tests/unit/server/test_git_schema_partners.py
@@ -58,14 +58,14 @@ def _row(co_change_partners_json: str) -> SimpleNamespace:
def test_well_formed_partners_pass_through() -> None:
raw = json.dumps([{"file_path": "b.py", "co_change_count": 4.25}])
- out = GitMetadataResponse.from_orm(_row(raw))
+ out = GitMetadataResponse.from_orm(_row(raw), attribution_on=True)
assert out.co_change_partners == [{"file_path": "b.py", "co_change_count": 4.25}]
def test_malformed_partners_yield_an_empty_list_not_an_error() -> None:
- assert GitMetadataResponse.from_orm(_row("not json")).co_change_partners == []
+ assert GitMetadataResponse.from_orm(_row("not json"), attribution_on=True).co_change_partners == []
def test_non_record_elements_are_dropped() -> None:
raw = json.dumps(["b.py", {"file_path": "c.py"}])
- assert GitMetadataResponse.from_orm(_row(raw)).co_change_partners == [{"file_path": "c.py"}]
+ assert GitMetadataResponse.from_orm(_row(raw), attribution_on=True).co_change_partners == [{"file_path": "c.py"}]
diff --git a/tests/unit/server/test_owners.py b/tests/unit/server/test_owners.py
index 775ceb300..98fb2fd4a 100644
--- a/tests/unit/server/test_owners.py
+++ b/tests/unit/server/test_owners.py
@@ -106,17 +106,20 @@ async def test_get_owner_profile(client: AsyncClient, app) -> None:
@pytest.mark.asyncio
-async def test_owner_profile_agent_collab_and_totals(client: AsyncClient, app) -> None:
+async def test_owner_profile_has_no_ai_figures_and_matches_totals(
+ client: AsyncClient, app
+) -> None:
+ """AI attribution is reported per file, component and repo, never per person."""
repo = await create_test_repo(client)
await _seed(app.state.session_factory, repo["id"])
- # Give Alice's owned file an agent-provenance rollup.
async with get_session(app.state.session_factory) as session:
await crud.upsert_git_metadata(
session,
repository_id=repo["id"],
file_path="src/main.py",
agent_commit_count=10,
- agent_authored_pct=0.2,
+ attribution_known_count=20,
+ agent_authored_pct=0.5,
agent_tier_counts_json=json.dumps({"2": 7, "3": 3}),
)
@@ -124,22 +127,11 @@ async def test_owner_profile_agent_collab_and_totals(client: AsyncClient, app) -
resp = await client.get(f"/api/repos/{repo['id']}/owners/{key}")
assert resp.status_code == 200
data = resp.json()
- collab = data["agent_collab"]
- assert collab is not None
- assert collab["files_with_agent_commits"] == 1
- assert collab["agent_commit_count"] == 10
- assert collab["agent_share_pct"] == 20.0 # 10 of 50 commits on main.py
- assert collab["tier_counts"] == {"2": 7, "3": 3}
+ assert not any(k.startswith("agent") for k in data)
# Truncation totals match the (small) fixture exactly.
assert data["files_touched_total"] == len(data["top_files"])
assert data["co_authors_total"] == len(data["co_authors"])
- # Bob owns only utils.py, which has no provenance rollup -> null.
- bob = await client.get(
- f"/api/repos/{repo['id']}/owners/{quote('[email protected]', safe='')}"
- )
- assert bob.json()["agent_collab"] is None
-
@pytest.mark.asyncio
async def test_last_commit_uses_authors_own_timestamp(client: AsyncClient, app) -> None:
diff --git a/tests/unit/test_attribution.py b/tests/unit/test_attribution.py
new file mode 100644
index 000000000..058b60ec7
--- /dev/null
+++ b/tests/unit/test_attribution.py
@@ -0,0 +1,575 @@
+"""AI attribution consent settings, three-state labels and the honest share.
+
+Covers the stricter-wins precedence between repo and user config, the
+``DO_NOT_TRACK`` override, value validation, the coverage and suppression
+arithmetic, git-ai v3 notes with ``h_`` human keys, Agent Trace human records,
+and that ``attribution.enabled: false`` stops detection at index time.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from unittest.mock import MagicMock
+
+import pytest
+
+from repowise.core import attribution
+from repowise.core.attribution import (
+ COVERAGE_FLOOR,
+ SUPPRESSED_LOW_COVERAGE,
+ SUPPRESSED_NO_COMMITS,
+ attribution_enabled,
+ attribution_share,
+ commit_label,
+ file_share,
+ load_attribution_settings,
+)
+from repowise.core.ingestion.git_commit_index import load_commit_index, load_git_ai_note_agents
+from repowise.core.ingestion.git_indexer.agent_provenance import (
+ AgentProvenanceClassifier,
+ AgentTraceIndex,
+ classifier_from_repo_config,
+ parse_git_ai_note,
+)
+
+
+def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ """A private user config location, and no DO_NOT_TRACK from the shell."""
+ user_home = tmp_path / "home"
+ (user_home / ".repowise").mkdir(parents=True)
+ user_file = user_home / ".repowise" / "config.yaml"
+ monkeypatch.setattr(attribution, "user_config_path", lambda: user_file)
+ monkeypatch.delenv("DO_NOT_TRACK", raising=False)
+ return user_home
+
+
+def _write(path: Path, text: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+def _repo(tmp_path: Path, config: str | None = None) -> Path:
+ repo = tmp_path / "repo"
+ repo.mkdir(parents=True, exist_ok=True)
+ if config is not None:
+ _write(repo / ".repowise" / "config.yaml", config)
+ return repo
+
+
+# ---------------------------------------------------------------------------
+# Settings precedence
+# ---------------------------------------------------------------------------
+
+
+def test_defaults_read_markers_and_capture_nothing(home: Path, tmp_path: Path) -> None:
+ settings = load_attribution_settings(_repo(tmp_path))
+ assert settings.enabled is True
+ assert settings.capture == "off"
+ assert settings.agents == ()
+ assert settings.errors == ()
+
+
+ ("repo_value", "user_value"), [("false", None), (None, "false"), ("false", "true")]
+)
+def test_enabled_false_in_either_file_wins(
+ home: Path, tmp_path: Path, repo_value: str | None, user_value: str | None
+) -> None:
+ if user_value is not None:
+ _write(home / ".repowise" / "config.yaml", f"attribution:\n enabled: {user_value}\n")
+ repo_cfg = f"attribution:\n enabled: {repo_value}\n" if repo_value is not None else None
+ settings = load_attribution_settings(_repo(tmp_path, repo_cfg))
+ assert settings.enabled is False
+ assert settings.capture == "off"
+
+
+ ("repo_level", "user_level", "effective"),
+ [
+ ("notes", "local", "local"),
+ ("local", "notes", "local"),
+ ("notes", "notes", "notes"),
+ ("notes", None, "off"), # the user never opted in
+ (None, "notes", "off"), # the repo never opted in
+ ],
+)
+def test_capture_takes_the_lower_level(
+ home: Path, tmp_path: Path, repo_level: str | None, user_level: str | None, effective: str
+) -> None:
+ if user_level:
+ _write(home / ".repowise" / "config.yaml", f"attribution:\n capture: {user_level}\n")
+ repo_cfg = f"attribution:\n capture: {repo_level}\n" if repo_level else None
+ settings = load_attribution_settings(_repo(tmp_path, repo_cfg))
+ assert settings.capture == effective
+
+
+def test_agents_are_the_intersection(home: Path, tmp_path: Path) -> None:
+ _write(
+ home / ".repowise" / "config.yaml",
+ "attribution:\n capture: local\n agents: [claude-code, codex]\n",
+ )
+ repo = _repo(tmp_path, "attribution:\n capture: local\n agents: [codex, cursor]\n")
+ settings = load_attribution_settings(repo)
+ assert settings.agents == ("codex",)
+ assert settings.repo.agents == ("codex", "cursor")
+ assert settings.user.agents == ("claude-code", "codex")
+
+
+def test_do_not_track_forces_capture_off(
+ home: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _write(home / ".repowise" / "config.yaml", "attribution:\n capture: notes\n agents: [codex]\n")
+ repo = _repo(tmp_path, "attribution:\n capture: notes\n agents: [codex]\n")
+ monkeypatch.setenv("DO_NOT_TRACK", "1")
+ settings = load_attribution_settings(repo)
+ assert settings.do_not_track is True
+ assert settings.capture == "off"
+ assert settings.agents == ()
+ # Reading public markers is not tracking; only capture is switched off.
+ assert settings.enabled is True
+
+
+def test_invalid_values_fall_to_the_strictest(home: Path, tmp_path: Path) -> None:
+ repo = _repo(
+ tmp_path,
+ "attribution:\n enabled: maybe\n capture: everything\n agents: [codex, not-an-agent]\n",
+ )
+ settings = load_attribution_settings(repo, known_agents=["codex", "claude-code"])
+ assert settings.enabled is False
+ assert settings.capture == "off"
+ assert settings.repo.agents == ("codex",)
+ assert len(settings.errors) == 3
+ assert any("not-an-agent" in e for e in settings.errors)
+
+
+def test_unreadable_repo_config_disables_attribution(home: Path, tmp_path: Path) -> None:
+ repo = _repo(tmp_path, "attribution: [unclosed\n")
+ settings = load_attribution_settings(repo)
+ assert settings.enabled is False
+ assert settings.errors
+
+
+def test_attribution_enabled_follows_config_edits(home: Path, tmp_path: Path) -> None:
+ repo = _repo(tmp_path)
+ assert attribution_enabled(repo) is True
+ _write(repo / ".repowise" / "config.yaml", "attribution:\n enabled: false\n")
+ assert attribution_enabled(repo) is False
+ assert attribution_enabled(None) is True
+ assert attribution_enabled(MagicMock()) is True # not a path: user file only
+
+
+# ---------------------------------------------------------------------------
+# Three-state labels and coverage math
+# ---------------------------------------------------------------------------
+
+
+def test_commit_label_never_reads_absence_as_human() -> None:
+ assert commit_label(None, None) == "unknown"
+ assert commit_label(None, "claude") == "agent"
+ assert commit_label("human_attested", None) == "human_attested"
+ assert commit_label("unknown", None) == "unknown"
+
+
+def test_share_is_of_covered_commits_with_its_coverage() -> None:
+ share = attribution_share(agent=30, human_attested=10, total=100)
+ assert share.coverage == pytest.approx(0.4)
+ assert share.agent_share == pytest.approx(0.75)
+ assert share.unknown == 60
+ assert share.suppressed_reason is None
+ assert share.summary() == "at least 75% of covered commits, coverage 40%"
+
+
+def test_share_is_withheld_below_the_floor() -> None:
+ share = attribution_share(agent=2, human_attested=0, total=1000)
+ assert share.coverage == pytest.approx(0.002)
+ assert share.agent_share is None
+ assert share.suppressed_reason == SUPPRESSED_LOW_COVERAGE
+ assert share.summary().startswith("withheld")
+
+
+def test_share_at_the_floor_is_shown() -> None:
+ share = attribution_share(agent=3, human_attested=0, total=10)
+ assert share.coverage == pytest.approx(COVERAGE_FLOOR)
+ assert share.agent_share == 1.0
+
+
+def test_share_without_commits() -> None:
+ share = attribution_share(0, 0, 0)
+ assert share.coverage is None
+ assert share.suppressed_reason == SUPPRESSED_NO_COMMITS
+
+
+def test_file_share_reads_rows_written_before_the_known_count() -> None:
+ # An older row has the agent count but a zero known count.
+ share = file_share(agent_commit_count=4, known_count=0, total=10)
+ assert share.agent == 4
+ assert share.human_attested == 0
+ assert share.coverage == pytest.approx(0.4)
+
+
+# ---------------------------------------------------------------------------
+# git-ai v3 notes
+# ---------------------------------------------------------------------------
+
+_HUMAN_ONLY_NOTE = """src/app.py
+ h_0123456789abcd 1-12,20
+ h_fedcba98765432 30
+---
+{"schema_version": "authorship/3.0.0", "git_ai_version": "1.7.5",
+ "base_commit_sha": "deadbeef", "prompts": {},
+ "humans": {"h_0123456789abcd": {"author": "Jane Doe <[email protected]>"}}}"""
+
+_MIXED_NOTE = """src/app.py
+ h_0123456789abcd 1-4
+ s_0011223344aabb::t_99887766554433 5-30
+---
+{"schema_version": "authorship/3.0.0", "base_commit_sha": "deadbeef", "prompts": {},
+ "sessions": {"s_0011223344aabb": {"agent_id": {"tool": "claude-code", "id": "x", "model": "m"}}}}"""
+
+_LEGACY_PROMPT_NOTE = """src/app.py
+ 0123456789abcdef 1-9
+---
+{"schema_version": "authorship/3.0.0", "base_commit_sha": "deadbeef",
+ "prompts": {"0123456789abcdef": {"agent_id": {"tool": "cursor", "id": "y", "model": "m"}}}}"""
+
+_UNRESOLVED_AI_NOTE = """src/app.py
+ h_0123456789abcd 1-4
+ 0123456789abcdef 5-9
+---
+{"schema_version": "authorship/3.0.0", "base_commit_sha": "deadbeef", "prompts": {}}"""
+
+
+def test_git_ai_note_with_only_human_keys_attests_human() -> None:
+ note = parse_git_ai_note(_HUMAN_ONLY_NOTE)
+ assert note.agent is None
+ assert note.human is True
+
+
+def test_git_ai_note_with_ai_session_is_agent() -> None:
+ note = parse_git_ai_note(_MIXED_NOTE)
+ assert note.agent == "claude"
+ assert note.human is False
+
+
+def test_git_ai_legacy_prompt_note_is_agent() -> None:
+ assert parse_git_ai_note(_LEGACY_PROMPT_NOTE).agent == "cursor"
+
+
+def test_git_ai_note_with_an_unresolved_ai_key_is_not_human() -> None:
+ note = parse_git_ai_note(_UNRESOLVED_AI_NOTE)
+ assert note.agent is None
+ assert note.human is False
+
+
[email protected]("raw", ["", "no divider", "x\n---\nnot json", "x\n---\n[1, 2]"])
+def test_malformed_git_ai_note_is_no_signal(raw: str) -> None:
+ note = parse_git_ai_note(raw)
+ assert (note.agent, note.human) == (None, False)
+
+
+def test_notes_loader_keeps_human_attestations(tmp_path: Path, home: Path) -> None:
+ repo = MagicMock()
+ repo.working_tree_dir = str(_repo(tmp_path))
+ repo.git.for_each_ref.return_value = "abc commit\trefs/notes/ai"
+ repo.git.log.return_value = (
+ f"\x00sha_h\x1f{_HUMAN_ONLY_NOTE}\n\x00sha_a\x1f{_MIXED_NOTE}\n\x00sha_none\x1f\n"
+ )
+ notes = load_git_ai_note_agents(repo, 50)
+ assert notes["sha_h"].human is True
+ assert notes["sha_a"].agent == "claude"
+ assert "sha_none" not in notes
+
+
+def test_notes_loader_reads_nothing_when_disabled(tmp_path: Path, home: Path) -> None:
+ repo = MagicMock()
+ repo.working_tree_dir = str(_repo(tmp_path, "attribution:\n enabled: false\n"))
+ assert load_git_ai_note_agents(repo, 50) == {}
+ repo.git.for_each_ref.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# Classifier: three states and the off switch
+# ---------------------------------------------------------------------------
+
+CLF = AgentProvenanceClassifier()
+
+
+def test_unmarked_commit_is_unknown_not_human() -> None:
+ prov = CLF.classify("Dev", "[email protected]", "Dev", "[email protected]", "feat: x")
+ assert prov.agent is None
+ assert prov.attribution == "unknown"
+
+
+def test_human_note_attests_human() -> None:
+ prov = CLF.classify("Dev", "[email protected]", "Dev", "[email protected]", "feat: x", note_human=True)
+ assert (prov.attribution, prov.channel) == ("human_attested", "git_ai_note")
+
+
+def test_agent_channel_beats_a_human_record() -> None:
+ prov = CLF.classify(
+ "Dev", "[email protected]", "Dev", "[email protected]", "x\n\nGenerated with Claude Code", trace_human=True
+ )
+ assert (prov.agent, prov.attribution) == ("claude", "agent")
+
+
+def test_disabled_classifier_labels_nothing() -> None:
+ off = AgentProvenanceClassifier(enabled=False)
+ prov = off.classify("Dev", "[email protected]", "Dev", "[email protected]", "x\n\nGenerated with Claude Code")
+ assert (prov.agent, prov.attribution) == (None, None)
+
+
+def test_repo_config_off_yields_disabled_classifier(tmp_path: Path, home: Path) -> None:
+ repo = _repo(tmp_path, "attribution:\n enabled: false\n")
+ assert classifier_from_repo_config(repo).enabled is False
+ assert classifier_from_repo_config(_repo(tmp_path / "other")).enabled is True
+
+
+def test_disabled_walk_stores_no_labels_or_rollup(tmp_path: Path, home: Path) -> None:
+ import time
+ from datetime import UTC, datetime
+
+ from repowise.core.ingestion.git_indexer.file_history import index_file
+
+ ts = int(time.time())
+ iso = datetime.fromtimestamp(ts, UTC).isoformat()
+ raw = (
+ f"\x00aaa\x1fDev\[email protected]\x1fDev\[email protected]\x1f{ts}\x1f{iso}\x1f\x1ffix: x"
+ f"\x1fGenerated with Claude Code\n1\t0\tsrc/a.py"
+ )
+ repo = MagicMock()
+ repo.git.log.return_value = raw
+ sink: list[dict] = []
+ index = load_commit_index(
+ repo,
+ 100,
+ {"src/a.py"},
+ commit_sink=sink,
+ provenance_classifier=AgentProvenanceClassifier(enabled=False),
+ )
+ assert sink[0]["agent_name"] is None
+ assert sink[0]["attribution"] is None
+ meta = index_file(
+ repo,
+ "src/a.py",
+ repo_path=MagicMock(),
+ commit_limit=100,
+ follow_renames=False,
+ include_blame=False,
+ precomputed_commits=index["src/a.py"],
+ )
+ assert meta["agent_commit_count"] == 0
+ assert meta["attribution_known_count"] == 0
+ assert meta["agent_authored_pct"] is None
+
+
+# ---------------------------------------------------------------------------
+# Agent Trace human records
+# ---------------------------------------------------------------------------
+
+
+def _trace(revision: str, kind: str, path: str = "src/a.py") -> str:
+ return json.dumps(
+ {
+ "version": "0.1.0",
+ "id": f"t-{revision}-{kind}",
+ "timestamp": "2026-10-01T00:00:00Z",
+ "vcs": {"type": "git", "revision": revision},
+ "files": [
+ {"path": path, "conversations": [{"contributor": {"type": kind}, "ranges": []}]}
+ ],
+ }
+ )
+
+
+def test_trace_human_record_attests_its_commit(tmp_path: Path, home: Path) -> None:
+ repo_dir = _repo(tmp_path)
+ _write(
+ repo_dir / ".agent-trace" / "traces.jsonl",
+ "\n".join([_trace("aaa", "human"), _trace("bbb", "unknown"), _trace("ccc", "ai")]),
+ )
+ repo = MagicMock()
+ repo.working_tree_dir = str(repo_dir)
+ index = AgentTraceIndex.load(repo)
+ assert index.resolve_human("aaa", (), {"src/a.py"}) is True
+ assert index.resolve_human("aaa", (), {"src/other.py"}) is False # no path overlap
+ assert index.resolve_human("bbb", (), {"src/a.py"}) is False # unknown is not human
+ assert index.resolve_human("ccc", (), {"src/a.py"}) is False
+
+
+def test_trace_file_is_not_read_when_disabled(tmp_path: Path, home: Path) -> None:
+ repo_dir = _repo(tmp_path, "attribution:\n enabled: false\n")
+ _write(repo_dir / ".agent-trace" / "traces.jsonl", _trace("ccc", "ai"))
+ repo = MagicMock()
+ repo.working_tree_dir = str(repo_dir)
+ assert not AgentTraceIndex.load(repo)
+
+
+# ---------------------------------------------------------------------------
+# Human attestation must cover every changed path
+# ---------------------------------------------------------------------------
+
+
+def test_trace_human_needs_every_changed_path(tmp_path: Path, home: Path) -> None:
+ repo_dir = _repo(tmp_path)
+ _write(repo_dir / ".agent-trace" / "traces.jsonl", _trace("aaa", "human"))
+ repo = MagicMock()
+ repo.working_tree_dir = str(repo_dir)
+ index = AgentTraceIndex.load(repo)
+ assert index.resolve_human("aaa", (), {"src/a.py"}) is True
+ # Partial overlap stays unknown: a false human is the worse error.
+ assert index.resolve_human("aaa", (), {"src/a.py", "src/b.py"}) is False
+ assert index.resolve_human("aaa", (), set()) is False
+
+
+def _header(sha: str = "sha1") -> dict:
+ return {
+ "sha": sha,
+ "parents": (),
+ "author_name": "Dev",
+ "author_email": "[email protected]",
+ "committer_name": "Dev",
+ "committer_email": "[email protected]",
+ "subject": "feat: x",
+ "body": "",
+ }
+
+
+def test_git_ai_human_note_needs_every_changed_path() -> None:
+ from repowise.core.ingestion.git_indexer.agent_provenance import classify_commit
+
+ notes = {"sha1": parse_git_ai_note(_HUMAN_ONLY_NOTE)}
+ assert notes["sha1"].paths == frozenset({"src/app.py"})
+ full, _ = classify_commit(CLF, _header(), {"src/app.py"}, notes, None)
+ partial, _ = classify_commit(CLF, _header(), {"src/app.py", "src/other.py"}, notes, None)
+ assert full.attribution == "human_attested"
+ assert partial.attribution == "unknown"
+
+
+def test_git_ai_divider_is_the_first_column_zero_rule() -> None:
+ # A later "---" line after the metadata must not move the split.
+ note = _HUMAN_ONLY_NOTE + "\n---\nnot json"
+ assert parse_git_ai_note(note).human is True
+
+
+def test_oversized_git_ai_note_is_ignored() -> None:
+ padding = "".join(f"\n h_{i:014x} 1" for i in range(60_000))
+ note = "src/app.py" + padding + "\n---\n" + '{"prompts": {}}'
+ assert len(note) > 1_000_000
+ assert parse_git_ai_note(note) == parse_git_ai_note("")
+
+
+# ---------------------------------------------------------------------------
+# attribution.enabled: false clears what an earlier index stored
+# ---------------------------------------------------------------------------
+
+
+async def _seed_labelled_index(repo_dir: Path):
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+ from repowise.core.persistence import crud
+ from repowise.core.persistence.database import init_db
+
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ repo = await crud.upsert_repository(session, name="r", local_path=str(repo_dir))
+ await crud.upsert_git_commits_bulk(
+ session,
+ repo.id,
+ [
+ {
+ "sha": "a" * 10,
+ "author_name": "A",
+ "author_email": "[email protected]",
+ "subject": "x",
+ "agent_name": "claude",
+ "agent_autonomy_tier": 2,
+ "attribution": "agent",
+ }
+ ],
+ )
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo.id,
+ file_path="a.py",
+ commit_count_total=1,
+ agent_commit_count=1,
+ attribution_known_count=1,
+ agent_authored_pct=1.0,
+ agent_line_count=7,
+ )
+ await session.commit()
+ return engine, factory, repo.id
+
+
+async def _ai_rows(factory, repo_id: str) -> tuple[list, list]:
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import GitCommit, GitMetadata
+
+ async with factory() as session:
+ commits = (
+ await session.execute(
+ select(GitCommit.agent_name, GitCommit.attribution).where(
+ GitCommit.repository_id == repo_id
+ )
+ )
+ ).all()
+ meta = (
+ await session.execute(
+ select(
+ GitMetadata.agent_commit_count,
+ GitMetadata.agent_authored_pct,
+ GitMetadata.agent_line_count,
+ ).where(GitMetadata.repository_id == repo_id)
+ )
+ ).all()
+ return [tuple(r) for r in commits], [tuple(r) for r in meta]
+
+
+async def test_update_after_switching_off_leaves_no_ai_rows(tmp_path: Path, home: Path) -> None:
+ from repowise.core.pipeline.persist import persist_git_refresh
+
+ repo_dir = _repo(tmp_path)
+ engine, factory, repo_id = await _seed_labelled_index(repo_dir)
+ try:
+ # Still enabled: an update keeps what was derived.
+ async with factory() as session:
+ await persist_git_refresh(session, repo_id, {}, None, None)
+ await session.commit()
+ assert (await _ai_rows(factory, repo_id))[0] == [("claude", "agent")]
+
+ _write(repo_dir / ".repowise" / "config.yaml", "attribution:\n enabled: false\n")
+ async with factory() as session:
+ await persist_git_refresh(session, repo_id, {}, None, None)
+ await session.commit()
+ commits, meta = await _ai_rows(factory, repo_id)
+ assert commits == [(None, None)]
+ assert meta == [(0, None, 0)]
+ finally:
+ await engine.dispose()
+
+
+async def test_full_index_with_attribution_off_stores_nothing(tmp_path: Path, home: Path) -> None:
+ from types import SimpleNamespace
+
+ from repowise.core.pipeline.persist import persist_git
+
+ repo_dir = _repo(tmp_path, "attribution:\n enabled: false\n")
+ engine, factory, repo_id = await _seed_labelled_index(repo_dir)
+ try:
+ async with factory() as session:
+ await persist_git(
+ SimpleNamespace(git_metadata_list=[], git_summary=None), session, repo_id
+ )
+ await session.commit()
+ commits, meta = await _ai_rows(factory, repo_id)
+ assert commits == [(None, None)]
+ assert meta == [(0, None, 0)]
+ finally:
+ await engine.dispose()