Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(git): deterministic agent-provenance layer in the git indexer (#366)
Raghav Chamadiyabd1f1f1d3f27
diff --git a/docs/COMPUTED_GLOSSARY.md b/docs/COMPUTED_GLOSSARY.mdindex d80eef799..45b93a8f8 100644--- a/docs/COMPUTED_GLOSSARY.md+++ b/docs/COMPUTED_GLOSSARY.md@@ -137,6 +137,8 @@ workspace overlays, MCP responses, and CLI output.| Hotspot flag | Top churn file: percentile >= 0.75 and has recent commits. | `_compute_percentiles()` | `is_hotspot: true` || 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()` | `{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}}` || Git index summary | Repo-level indexing result. | `GitIndexSummary` | `{files_indexed: 420, hotspots: 38, stable_files: 71, duration_seconds: 12.4}` |## Generated Wiki Pagesdiff --git a/packages/core/alembic/versions/0030_agent_provenance.py b/packages/core/alembic/versions/0030_agent_provenance.pynew file mode 100644index 000000000..a11e79e96--- /dev/null+++ b/packages/core/alembic/versions/0030_agent_provenance.py@@ -0,0 +1,55 @@+"""Agent-provenance columns on git_commits + git_metadata.++Per-commit: which coding agent (if any) authored the commit, its autonomy tier+(1 near-autonomous bot account · 2 human-driven agent · 3 assisted), the+attribution channel, and a confidence band. Per-file: the rollup share of+agent-attributed commits and the tier breakdown. Classification is+deterministic local-git pattern matching (identity fields, message footers,+co-author trailers) riding the existing commit-index walk — no extra git pass,+no network. All columns are nullable / defaulted and back-populated on the+next index.++Revision ID: 0030+Revises: 0029+Create Date: 2026-06-04+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0030"+down_revision: str | None = "0029"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column("git_commits", sa.Column("agent_name", sa.String(32), nullable=True))+ op.add_column("git_commits", sa.Column("agent_autonomy_tier", sa.Integer, nullable=True))+ op.add_column("git_commits", sa.Column("agent_channel", sa.String(32), nullable=True))+ op.add_column("git_commits", sa.Column("agent_confidence", sa.String(8), nullable=True))++ op.add_column(+ "git_metadata",+ sa.Column("agent_commit_count", sa.Integer, nullable=False, server_default="0"),+ )+ op.add_column("git_metadata", sa.Column("agent_authored_pct", sa.Float, nullable=True))+ op.add_column(+ "git_metadata",+ sa.Column("agent_tier_counts_json", sa.Text, nullable=False, server_default="{}"),+ )+++def downgrade() -> None:+ op.drop_column("git_metadata", "agent_tier_counts_json")+ op.drop_column("git_metadata", "agent_authored_pct")+ op.drop_column("git_metadata", "agent_commit_count")+ op.drop_column("git_commits", "agent_confidence")+ op.drop_column("git_commits", "agent_channel")+ op.drop_column("git_commits", "agent_autonomy_tier")+ op.drop_column("git_commits", "agent_name")diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.pyindex 01719a3f0..5fb248abb 100644--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py@@ -36,6 +36,7 @@ def load_commit_index(*,commit_sink: list[dict] | None = None,since_ts: int | None = None,+ provenance_classifier: object | None = None,) -> dict[str, list[_CommitRec]]:"""Bucket every commit in the recent history by the files it touched.@@ -66,6 +67,13 @@ def load_commit_index(without re-walking the full window. Default (``None``) processes the wholedepth.+ *provenance_classifier* (an+ :class:`~.git_indexer.agent_provenance.AgentProvenanceClassifier`) labels+ each commit's agent provenance once per commit — pure in-memory regex on+ the already-parsed record, no extra git pass. ``None`` uses the built-in+ pattern registry; callers with repo-local pattern extensions pass the+ config-aware instance instead.+Failures (git unavailable, corrupt log output, etc.) return anempty dict so the caller can fall back to per-file indexing."""@@ -78,6 +86,10 @@ def load_commit_index(_extract_rename_paths,_parse_commit_record,)+ from .git_indexer.agent_provenance import AgentProvenanceClassifier++ if provenance_classifier is None:+ provenance_classifier = AgentProvenanceClassifier()try:raw = repo.git.log( # type: ignore[attr-defined]@@ -114,6 +126,16 @@ def load_commit_index(continuecommits_parsed += 1+ # Agent provenance — classified ONCE per commit here (not per touched+ # file): the per-file records below share the result by reference.+ prov = provenance_classifier.classify( # type: ignore[attr-defined]+ header["author_name"],+ header["author_email"],+ header["committer_name"],+ header["committer_email"],+ f"{header['subject']}\n{header['body']}",+ )+# Full change footprint of this commit (every file, not just the# indexable subset) — only accumulated when a sink is requested so the# default path pays nothing.@@ -162,6 +184,8 @@ def load_commit_index(body=header["body"],added=added,deleted=deleted,+ agent=prov.agent,+ agent_tier=prov.autonomy_tier,))@@ -174,6 +198,10 @@ def load_commit_index("ts": header["ts"],"subject": header["subject"],"changes": commit_changes,+ "agent_name": prov.agent,+ "agent_autonomy_tier": prov.autonomy_tier,+ "agent_channel": prov.channel,+ "agent_confidence": prov.confidence,})diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/README.md b/packages/core/src/repowise/core/ingestion/git_indexer/README.mdindex c9fefa602..775a9604a 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md+++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md@@ -17,7 +17,9 @@ layers consume:- co-change partners and Hassan **change entropy** (History Complexity Metric);- per-function blame (modification counts, line age) for function-level health;- **prior-defect history** — bug-fix commits touching each file in the trailing- window, the most cost-effective defect predictor.+ window, the most cost-effective defect predictor;+- **agent provenance** — which coding agent (if any) authored each commit, at+ what autonomy tier, plus per-file `agent_authored_pct` rollups.## Window anchoring (`REPOWISE_GIT_WINDOW_ANCHOR`)@@ -94,6 +96,41 @@ live `repowise risk` path) is reconstructed **in memory** here: walking commitsoldest→newest, each author's prior-commit count is the running tally. Empty inrename-tracking mode (which uses the per-file walk, not the batched index).+## Agent provenance++`agent_provenance.py` labels every walked commit+`{agent, autonomy_tier, channel, confidence}` from the attribution channels+present in **local git history** — identity fields (bot accounts / service+e-mails), exact message footers ("Generated with Claude Code", Codex,+opencode, aider), and `Co-authored-by:` trailers anchored to service+identities. Tiers: **1** near-autonomous (an agent service account authored+the commit) · **2** human-driven agent (footer, or a service identity as+*committer* over a human author) · **3** assisted (co-author trailer only).++Design rules:++- **Precision-first.** Every pattern is anchored to a service identity; a bare+ name never matches (a human contributor named "Devin" must not become the+ Devin agent). A false "agent-authored" label on a human commit is worse+ than a miss.+- **Local channels only.** PR-level evidence (bot PR authors, agent branch+ prefixes, PR-body footers) needs the forge API and is out of scope — squash+ merges that strip trailers are a known *recall* loss, stated rather than+ patched with network calls at index time.+- **Zero extra cost.** Classification rides the existing commit-index walk —+ pure in-memory regex on already-parsed records, ~20 µs/commit (≈10 ms at the+ default commit depth), no additional `git` pass.+- **Config-driven.** Repos can extend the registry from+ `.repowise/config.yaml` under an `agent_provenance:` block+ (`service_emails`, `footer_patterns`, `coauthor_patterns`) — additive on top+ of the built-ins, malformed entries skipped with a warning.++Persisted as four nullable columns on `git_commits`+(`agent_name`/`agent_autonomy_tier`/`agent_channel`/`agent_confidence`) and a+per-file rollup on `git_metadata` (`agent_commit_count`, `agent_authored_pct`,+`agent_tier_counts_json`), surfaced in the `/git-metadata` file view and the+MCP `get_context` ownership block.+## Internal layout| Module | Contents |@@ -102,6 +139,7 @@ rename-tracking mode (which uses the per-file walk, not the batched index).| `_constants.py` | commit-depth defaults, decay half-lives, the bug-fix keyword classifier (`is_fix_commit`, mirrors the benchmark) + `PRIOR_DEFECT_WINDOW_DAYS`, skip heuristics, GitPython noise patch || `records.py` | `_CommitRec`, `GitIndexSummary` (carries `commit_rows`), the `git log` record format + rename/skip path helpers || `commit_rows.py` | `build_commit_rows` — per-commit Kamei features + change-risk from the walk's sunk commits (pure, in-memory author experience) |+| `agent_provenance.py` | `AgentProvenanceClassifier` — deterministic per-commit agent attribution (local channels, config-extensible) || `file_history.py` | `index_file` — per-file parse + base metrics (blame gated by tier) || `enrich.py` | blame ownership, commit significance, rename detection, percentiles || `function_blame.py` | per-line blame index → per-function modification counts + line age (FULL tier; feeds `function_hotspot` / `code_age_volatility`) |diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.pyindex 3a361f9a5..2546ec4e6 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/__init__.py@@ -20,6 +20,11 @@ This package was split out of a single 1k-line module; the public import pathfrom __future__ import annotationsfrom ._constants import HOTSPOT_HALFLIFE_DAYS, is_fix_commit+from .agent_provenance import (+ AgentProvenance,+ AgentProvenanceClassifier,+ classifier_from_repo_config,+)from .backfill import BACKFILL_PHASE, backfill_full_tierfrom .co_change import compute_co_changes, compute_co_changes_and_entropyfrom .enrich import (@@ -52,6 +57,8 @@ __all__ = ["_FIELD_SEP","_LOG_FORMAT","_RECORD_SEP",+ "AgentProvenance",+ "AgentProvenanceClassifier","GitIndexSummary","GitIndexTier","GitIndexer",@@ -60,6 +67,7 @@ __all__ = ["_parse_commit_record","_should_skip_index","backfill_full_tier",+ "classifier_from_repo_config","compute_co_changes","compute_co_changes_and_entropy","compute_percentiles",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.pynew file mode 100644index 000000000..1286985ca--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/git_indexer/agent_provenance.py@@ -0,0 +1,255 @@+"""Per-commit agent-provenance classification — deterministic, precision-first.++Labels a commit ``{agent, autonomy_tier, channel, confidence}`` from the+attribution channels available in **local git history** (identity fields,+message footers, ``Co-authored-by:`` trailers — no network, no API calls, no+LLM), in strip-resistance order:++ Tier 1 (near-autonomous — an agent service account authored the commit):+ * commit AUTHOR is a known agent bot account / service e-mail+ (``copilot-swe-agent[bot]``, ``devin-ai-integration[bot]``,+ ``[email protected]``, ...)+ Tier 2 (human-driven agent — the agent wrote the change):+ * commit-message footer (exact service phrases: "Generated with Claude+ Code", opencode, Codex) or the aider author-name suffix ``... (aider)``+ * a service identity as COMMITTER over a human author (the agent+ pushed/amended a human-driven change — deliberately NOT tier 1)+ Tier 3 (assisted — an agent contributed, a human authored):+ * ``Co-authored-by:`` trailer naming a known agent service identity++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*+(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+than a miss.++PR-level channels (bot PR author, agent branch prefixes, PR-body footers)+require the forge API and are intentionally out of scope here: squash merges+that strip commit trailers are therefore a known recall loss, not a precision+loss. ``confidence`` is carried per channel so future, weaker channels can be+filtered by consumers; every local channel is ``"high"``.++The default registry below is data, not code: repos can extend it from+``.repowise/config.yaml`` (see :func:`classifier_from_repo_config`) without+touching this module, e.g.::++ agent_provenance:+ service_emails:+ [email protected]: {agent: mybot, tier: 1}+ footer_patterns:+ - {pattern: "Generated by MyBot", agent: mybot}+ coauthor_patterns:+ - {pattern: "^co-authored-by: mybot <[^>]*@example\\.com>", agent: mybot}++Classification is pure in-memory regex over already-parsed commit records and+rides the existing commit-index walk — it adds no git subprocess and no I/O.+"""++from __future__ import annotations++import re+from dataclasses import dataclass++import structlog++logger = structlog.get_logger(__name__)++__all__ = [+ "AgentProvenance",+ "AgentProvenanceClassifier",+ "classifier_from_repo_config",+]+++# ------------------------------------------------------------------ registry --++# Bot login (lowercase, without the ``[bot]`` suffix) → agent name, for+# ``<login>[bot]@users.noreply.github.com`` author/committer e-mails (GitHub's+# canonical bot identity, also re-injected on squash merges).+_BOT_LOGINS: dict[str, str] = {+ "copilot-swe-agent": "copilot",+ "copilot": "copilot",+ "devin-ai-integration": "devin",+ "cursor": "cursor",+ "cursoragent": "cursor",+ "google-labs-jules": "jules",+ "codegen-sh": "codegen",+ "openhands-ai": "openhands",+ "sweep-ai": "sweep",+ "claude": "claude",+}++# Exact service e-mails → (agent, tier) for commit identity fields.+_SERVICE_EMAILS: dict[str, tuple[str, int]] = {+ "[email protected]": ("cursor", 1),+ "devin-ai-integration[bot]@users.noreply.github.com": ("devin", 1),+}++# Commit-message footers → agent (exact service phrases only).+_FOOTER_PATTERNS: list[tuple[str, str]] = [+ (r"generated with \[?claude code\]?", "claude"),+ (r"generated with \[?opencode\]?", "opencode"),+ (r"generated with \[?(?:openai )?codex\]?", "codex"),+ (r"^\s*aider wrote this", "aider"),+]++# ``Co-authored-by:`` trailers → agent. Anchored to the trailer position AND+# the agent's service identity — a name alone is not enough (see module doc).+_COAUTHOR_PATTERNS: list[tuple[str, str]] = [+ (+ r"^co-authored-by:\s*claude(?:\s+(?:opus|sonnet|haiku)[^<]*)?\s*<[^>]*@anthropic\.com>",+ "claude",+ ),+ (r"^co-authored-by:\s*copilot\s*<\d+\+copilot@users\.noreply\.github\.com>", "copilot"),+ (+ r"^co-authored-by:\s*cursor(?:\s*agent)?\s*<(?:cursoragent@cursor\.com|[^>]*cursor[^>]*)>",+ "cursor",+ ),+ (r"^co-authored-by:\s*opencode\s*<", "opencode"),+ (r"^co-authored-by:\s*devin[^<]*<[^>]*devin-ai-integration[^>]*>", "devin"),+ (r"^co-authored-by:\s*aider[^<]*<[^>]*aider[^>]*>", "aider"),+]++_AIDER_NAME_RE = re.compile(r"\(aider\)\s*$")+++@dataclass(frozen=True)+class AgentProvenance:+ """One commit's agent attribution. ``agent is None`` means human."""++ 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)+++_HUMAN = AgentProvenance()+++class AgentProvenanceClassifier:+ """Compiled pattern registry + the classification rule.++ Construct once per index run (compilation is the only non-trivial cost);+ :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).+ """++ def __init__(+ self,+ *,+ 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,+ ) -> None:+ self._service_emails = {**_SERVICE_EMAILS, **(extra_service_emails or {})}+ # ``[bot]`` is optional: GitHub squash-merges authored by the Copilot+ # coding agent use ``<id>[email protected]`` (no+ # suffix). Safe because each login is a unique, vendor-owned GitHub+ # account — no human can register them.+ self._bot_email_re = re.compile(+ r"^(?:\d+\+)?("+ + "|".join(re.escape(b) for b in _BOT_LOGINS)+ + r")(?:\[bot\])?@users\.noreply\.github\.com$",+ re.IGNORECASE,+ )+ self._footers = [+ (re.compile(p, re.IGNORECASE | re.MULTILINE), agent)+ for p, agent in [*_FOOTER_PATTERNS, *(extra_footer_patterns or [])]+ ]+ self._coauthors = [+ (re.compile(p, re.IGNORECASE | re.MULTILINE), agent)+ for p, agent in [*_COAUTHOR_PATTERNS, *(extra_coauthor_patterns or [])]+ ]++ def _identity_match(self, email: str) -> tuple[str, int] | None:+ e = (email or "").strip().lower()+ if not e:+ return None+ hit = self._service_emails.get(e)+ if hit:+ return hit+ m = self._bot_email_re.match(e)+ if m:+ return (_BOT_LOGINS[m.group(1).lower()], 1)+ return None++ def classify(+ self,+ author_name: str,+ author_email: str,+ committer_name: str,+ committer_email: str,+ message: str,+ ) -> AgentProvenance:+ """Classify one commit from local metadata. *message* is the full+ commit message (subject + body) — trailers and footers live in the+ body, so passing the subject alone silently disables two channels."""+ # T1 — agent service identity AUTHORED the commit.+ hit = self._identity_match(author_email)+ if hit:+ return AgentProvenance(hit[0], hit[1], "service_email", "high")+ # T2 — message footer / aider author-name suffix.+ for pat, agent in self._footers:+ if pat.search(message):+ return AgentProvenance(agent, 2, "message_footer", "high")+ if _AIDER_NAME_RE.search(author_name or ""):+ return AgentProvenance("aider", 2, "author_name_aider", "high")+ # 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")+ # 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 _HUMAN+++def classifier_from_repo_config(repo_path: object) -> AgentProvenanceClassifier:+ """Build a classifier with any repo-local pattern extensions.++ 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.+ """+ extra_emails: dict[str, tuple[str, int]] = {}+ extra_footers: list[tuple[str, str]] = []+ extra_coauthors: list[tuple[str, str]] = []+ try:+ from ...repo_config import load_repo_config++ block = load_repo_config(repo_path).get("agent_provenance") or {} # type: ignore[arg-type]+ if isinstance(block, dict):+ for email, spec in (block.get("service_emails") or {}).items():+ if isinstance(spec, dict) and spec.get("agent"):+ tier = max(1, min(3, int(spec.get("tier", 1))))+ extra_emails[str(email).lower()] = (str(spec["agent"]), tier)+ for key, sink in (+ ("footer_patterns", extra_footers),+ ("coauthor_patterns", extra_coauthors),+ ):+ for entry in block.get(key) or []:+ if not (+ isinstance(entry, dict) and entry.get("pattern") and entry.get("agent")+ ):+ continue+ try:+ re.compile(entry["pattern"])+ except re.error as exc:+ logger.warning(+ "agent_provenance_pattern_invalid",+ pattern=entry["pattern"],+ error=str(exc),+ )+ continue+ sink.append((entry["pattern"], str(entry["agent"])))+ except Exception as exc: # config parsing must never break indexing+ logger.warning("agent_provenance_config_failed", error=str(exc))+ return AgentProvenanceClassifier(+ extra_service_emails=extra_emails,+ extra_footer_patterns=extra_footers,+ extra_coauthor_patterns=extra_coauthors,+ )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.pyindex d49a2b7d3..1ce3cedbd 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@@ -98,6 +98,12 @@ def build_commit_rows(parsed_commits: list[dict]) -> list[dict]:"author_experience": exp,"change_risk_score": risk.score,"change_risk_level": risk.level,+ # Agent provenance — classified during the walk (commit-index+ # sink); pure passthrough here so this transform stays git-free.+ "agent_name": c.get("agent_name"),+ "agent_autonomy_tier": c.get("agent_autonomy_tier"),+ "agent_channel": c.get("agent_channel"),+ "agent_confidence": c.get("agent_confidence"),})return rowsdiff --git a/packages/core/src/repowise/core/ingestion/git_indexer/file_history.py b/packages/core/src/repowise/core/ingestion/git_indexer/file_history.pyindex 9f50dd7f6..3fe4c8ca1 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@@ -110,6 +110,12 @@ def new_meta(file_path: str) -> dict[str, Any]:# ``prior_defect`` health biomarker; mirrors the benchmark's# prior-defects baseline definition (product == benchmark)."prior_defect_count": 0,+ # Agent provenance rollup: how much of this file's indexed history is+ # agent-attributed (local channels only — see agent_provenance module).+ # agent_authored_pct stays None when the file has no commits at all.+ "agent_commit_count": 0,+ "agent_authored_pct": None,+ "agent_tier_counts_json": "{}",# Temporal hotspot score (exponentially decayed churn)"temporal_hotspot_score": 0.0,# Change entropy (Hassan HCM) — populated repo-wide by the co-change@@ -126,6 +132,7 @@ def _parse_per_file_log(*,commit_limit: int,follow_renames: bool,+ provenance_classifier: Any | None = None,) -> tuple[list[_CommitRec], str | None]:"""Run a per-file ``git log --numstat`` and parse it into commit records.@@ -176,6 +183,16 @@ def _parse_per_file_log(subject=header["subject"],body=header["body"],)+ if provenance_classifier is not None:+ prov = provenance_classifier.classify(+ header["author_name"],+ header["author_email"],+ header["committer_name"],+ header["committer_email"],+ f"{header['subject']}\n{header['body']}",+ )+ current.agent = prov.agent+ current.agent_tier = prov.autonomy_tiercommits.append(current)for line in numstat_lines:numstat_parts = line.split("\t")@@ -205,6 +222,7 @@ def index_file(include_blame: bool = True,precomputed_commits: list[_CommitRec] | None = None,as_of_ts: float | None = None,+ provenance_classifier: Any | None = None,) -> dict:"""Index a single file's git history. Runs in executor.@@ -239,6 +257,7 @@ def index_file(file_path,commit_limit=commit_limit,follow_renames=follow_renames,+ provenance_classifier=provenance_classifier,)if not commits:@@ -291,6 +310,18 @@ def index_file(total_churn = meta["lines_added_90d"] + meta["lines_deleted_90d"]meta["avg_commit_size"] = total_churn / c90 if c90 > 0 else 0.0+ # Agent-provenance rollup: share of this file's indexed commits that+ # are agent-attributed, plus the per-autonomy-tier breakdown. The+ # per-commit labels were classified once during the walk; this is a+ # pure count over the already-carried records.+ agent_commits = [c for c in commits if getattr(c, "agent", None)]+ meta["agent_commit_count"] = len(agent_commits)+ meta["agent_authored_pct"] = len(agent_commits) / len(commits)+ 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))+# Temporal hotspot score: exponentially decayed per-commit churn._ln2 = math.log(2)temporal_score = 0.0diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.pyindex 0cd84ed19..389f1f790 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py@@ -120,6 +120,7 @@ class GitIndexer:# ``git log -- <file>`` — turning O(files) process spawns into O(1).commit_index: dict[str, list[_CommitRec]] = {}commit_sink: list[dict] = []+ prov_clf = self._provenance_classifier()if not self.follow_renames:from ..git_commit_index import load_commit_index@@ -128,6 +129,7 @@ class GitIndexer:self.commit_limit,set(indexable_files),commit_sink=commit_sink,+ provenance_classifier=prov_clf,)include_blame = self.tier.includes_blame@@ -150,6 +152,7 @@ class GitIndexer:include_blame=include_blame,precomputed_commits=precomputed,as_of_ts=as_of_ts,+ provenance_classifier=prov_clf,)finally:thread_repo.close()@@ -373,7 +376,12 @@ class GitIndexer:# Empty indexable set: we only want the full-footprint sink, not the# per-file bucket (which the incremental file pass already rebuilt).load_commit_index(- repo, self.commit_limit, set(), commit_sink=sink, since_ts=since_ts+ repo,+ self.commit_limit,+ set(),+ commit_sink=sink,+ since_ts=since_ts,+ provenance_classifier=self._provenance_classifier(),)return build_commit_rows(sink)except Exception as exc:@@ -386,6 +394,22 @@ class GitIndexer:# Internal methods# ------------------------------------------------------------------+ def _provenance_classifier(self) -> Any:+ """Config-aware agent-provenance classifier, built once per index run.++ Failure-isolated: a malformed repo config falls back to the built-in+ pattern registry rather than breaking the git phase.+ """+ try:+ from .agent_provenance import classifier_from_repo_config++ return classifier_from_repo_config(self.repo_path)+ except Exception as exc:+ logger.debug("agent_provenance_classifier_failed", error=str(exc))+ from .agent_provenance import AgentProvenanceClassifier++ return AgentProvenanceClassifier()+def _resolve_as_of_ts(self, repo: Any, commit_index: dict[str, list[_CommitRec]] | None = None) -> float | None:diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/records.py b/packages/core/src/repowise/core/ingestion/git_indexer/records.pyindex 420d3fda4..b6050f70c 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py@@ -38,8 +38,10 @@ _FIELD_SEP = "\x1f"# ``%an``/``%ae``) so a repo's ``.mailmap`` folds a contributor's multiple# names/emails — personal vs. GitHub ``noreply``, a second machine's git config —# into one identity. Without this, ownership and "last touched" split one human-# across several contributor buckets.-_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%ct%x1f%P%x1f%s%x1f%b"+# across several contributor buckets. Committer name/email (``%cN``/``%cE``)+# ride the same record for agent-provenance classification: a service identity+# as committer over a human author means an agent pushed/amended the change.+_LOG_FORMAT = "%x00%H%x1f%aN%x1f%aE%x1f%cN%x1f%cE%x1f%ct%x1f%P%x1f%s%x1f%b"# A git ``--numstat`` line: ``<added>\t<deleted>\t<path>`` where added/deleted# are decimal counts or ``-`` for binary files. Used to split the trailing@@ -60,6 +62,10 @@ class _CommitRec:body: str = ""added: int = 0deleted: int = 0+ # Agent provenance (classified once per commit during the walk; carried on+ # the record so per-file rollups don't re-run the regex per touched file).+ agent: str | None = None+ agent_tier: int | None = Nonedef _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:@@ -67,7 +73,7 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:A record (after the leading record separator is stripped) looks like::- <sha>\\x1f<an>\\x1f<ae>\\x1f<ct>\\x1f<parents>\\x1f<subject>\\x1f<body>\\n<numstat...>+ <sha>\\x1f<an>\\x1f<ae>\\x1f<cn>\\x1f<ce>\\x1f<ct>\\x1f<parents>\\x1f<subject>\\x1f<body>\\n<numstat...>The body is multi-line, so the trailing ``--numstat`` block is identifiedby the first line matching :data:`_NUMSTAT_RE`; everything before it is@@ -76,12 +82,12 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:fields except ``added``/``deleted`` (the caller attributes churn)."""parts = record.split(_FIELD_SEP)- if len(parts) < 7:+ if len(parts) < 9:return None- sha, an, ae, ct, parents, subject = parts[:6]+ sha, an, ae, cn, ce, ct, parents, subject = parts[:8]# %b cannot contain the field separator, so the body + numstat tail is the- # 7th field exactly (join is defensive against an unexpected stray sep).- body_and_numstat = _FIELD_SEP.join(parts[6:])+ # 9th field exactly (join is defensive against an unexpected stray sep).+ body_and_numstat = _FIELD_SEP.join(parts[8:])body_lines: list[str] = []numstat_lines: list[str] = []@@ -103,6 +109,8 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:"sha": sha,"author_name": an or "unknown","author_email": ae,+ "committer_name": cn or "",+ "committer_email": ce or "","ts": ts,"is_merge": len(parents.split()) > 1,"subject": subject,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 69edaeceb..82dc01900 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -403,6 +403,16 @@ class GitMetadata(Base):change_entropy: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)change_entropy_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+ # autonomy tier ("1" near-autonomous / "2" human-driven / "3" assisted)+ # to commit counts. agent_authored_pct stays NULL until the next reindex.+ agent_commit_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="{}")+created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)@@ -463,6 +473,16 @@ class GitCommit(Base):change_risk_score: Mapped[float | None] = mapped_column(Float, nullable=True)change_risk_level: Mapped[str | None] = mapped_column(String(16), nullable=True)+ # 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.+ 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)+ agent_confidence: Mapped[str | None] = mapped_column(String(8), nullable=True)+created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)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.pyindex be70eda8a..17901ea70 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@@ -8,6 +8,7 @@ blocks delegated to ``enrichment``).from __future__ import annotations+import contextlibimport jsonfrom typing import Any@@ -502,6 +503,15 @@ async def _resolve_one_target(if recent and recent != meta.primary_owner_name:ownership["recent_owner"] = recentownership["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)+ ownership["agent_commit_count"] = meta.agent_commit_count+ with contextlib.suppress(TypeError, ValueError):+ ownership["agent_tier_counts"] = json.loads(+ getattr(meta, "agent_tier_counts_json", None) or "{}"+ )else:ownership["primary_owner"] = Noneownership["owner_pct"] = Nonediff --git a/packages/server/src/repowise/server/schemas/git.py b/packages/server/src/repowise/server/schemas/git.pyindex 0637dfc12..9fe96eabb 100644--- a/packages/server/src/repowise/server/schemas/git.py+++ b/packages/server/src/repowise/server/schemas/git.py@@ -44,6 +44,13 @@ class GitMetadataResponse(BaseModel):# Rename lineage: the file's path before its most recent move, if any.original_path: str | None = Nonetest_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_authored_pct: float | None = None+ agent_tier_counts: dict = {}@classmethoddef from_orm(cls, obj: object) -> GitMetadataResponse:@@ -83,6 +90,9 @@ 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 "{}"),)diff --git a/packages/web/src/components/docs/docs-viewer.tsx b/packages/web/src/components/docs/docs-viewer.tsxindex d355edb79..8d24b2547 100644--- a/packages/web/src/components/docs/docs-viewer.tsx+++ b/packages/web/src/components/docs/docs-viewer.tsx@@ -241,6 +241,14 @@ function AtAGlance({ repoId, targetPath }: { repoId: string; targetPath: string<span className="text-[var(--color-text-tertiary)]">Contributors</span><span className="font-mono">{data.contributor_count}</span></div>+ {data.agent_authored_pct != null && (data.agent_commit_count ?? 0) > 0 && (+ <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}+ </span>+ </div>+ )}</div></div>);diff --git a/packages/web/src/lib/api/types/git.ts b/packages/web/src/lib/api/types/git.tsindex 9a851286c..b4f4038c2 100644--- a/packages/web/src/lib/api/types/git.ts+++ b/packages/web/src/lib/api/types/git.ts@@ -35,6 +35,11 @@ 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_authored_pct?: number | null;+ agent_tier_counts?: Record<string, number>;}export interface HotspotResponse {diff --git a/tests/unit/ingestion/test_agent_provenance.py b/tests/unit/ingestion/test_agent_provenance.pynew file mode 100644index 000000000..e9424164c--- /dev/null+++ b/tests/unit/ingestion/test_agent_provenance.py@@ -0,0 +1,232 @@+"""Unit tests for deterministic agent-provenance classification.++Covers the channel/tier rules, the precision-first anchoring (service+identities, never bare names), the committer-over-author tier demotion, the+config-driven pattern extension, and the end-to-end flow through the+commit-index walk into commit rows and per-file rollups.+"""++from __future__ import annotations++import json+import time+from unittest.mock import MagicMock++from repowise.core.ingestion.git_commit_index import load_commit_index+from repowise.core.ingestion.git_indexer.agent_provenance import (+ AgentProvenanceClassifier,+)+from repowise.core.ingestion.git_indexer.commit_rows import build_commit_rows+from repowise.core.ingestion.git_indexer.file_history import index_file+from repowise.core.ingestion.git_indexer.records import _CommitRec++CLF = AgentProvenanceClassifier()+++def _classify(an="Dev", ae="[email protected]", cn="Dev", ce="[email protected]", msg="feat: thing"):+ return CLF.classify(an, ae, cn, ce, msg)+++# ---------------------------------------------------------------------------+# Channel / tier rules+# ---------------------------------------------------------------------------+++def test_human_commit_is_unlabelled() -> None:+ prov = _classify()+ assert prov.agent is None+ assert prov.autonomy_tier is None+++def test_bot_author_email_is_tier1() -> None:+ prov = _classify(+ an="copilot-swe-agent[bot]",+ ae="[email protected]",+ msg="fix: adjust workflow",+ )+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("copilot", 1, "service_email")+ assert prov.confidence == "high"+++def test_service_email_author_is_tier1() -> None:+ prov = _classify(an="Cursor Agent", ae="[email protected]")+ assert (prov.agent, prov.autonomy_tier) == ("cursor", 1)+++def test_service_committer_over_human_author_is_tier2_not_tier1() -> None:+ """An agent pushing/amending a human-authored commit is human-driven (T2):+ the committer field alone must never claim full autonomy."""+ prov = _classify(cn="Cursor Agent", ce="[email protected]")+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("cursor", 2, "service_committer")+++def test_claude_footer_is_tier2() -> None:+ msg = "feat: add parser\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)"+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 2, "message_footer")+++def test_aider_author_name_suffix_is_tier2() -> None:+ prov = _classify(an="Jane Doe (aider)")+ assert (prov.agent, prov.autonomy_tier) == ("aider", 2)+++def test_coauthor_trailer_is_tier3() -> None:+ msg = "fix: handle null\n\nCo-authored-by: Claude Opus 4.5 <[email protected]>"+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("claude", 3, "coauthor_trailer")+++def test_tier_precedence_footer_beats_trailer() -> None:+ """A commit carrying both a T2 footer and a T3 trailer is T2 — first match+ in tier order wins."""+ msg = (+ "feat: thing\n\nGenerated with Claude Code\nCo-authored-by: Claude <[email protected]>"+ )+ prov = _classify(msg=msg)+ assert prov.autonomy_tier == 2+++# ---------------------------------------------------------------------------+# Precision-first anchoring (the false-positive modes that must stay dead)+# ---------------------------------------------------------------------------+++def test_human_named_devin_is_not_the_devin_agent() -> None:+ """Co-author patterns are anchored to service e-mails — a human+ contributor named Devin must never match."""+ msg = "feat: routes\n\nCo-authored-by: Devin Ivy <[email protected]>"+ prov = _classify(msg=msg)+ assert prov.agent is None+++def test_mentioning_claude_in_prose_is_not_a_footer() -> None:+ prov = _classify(msg="docs: explain how we generated docs with an LLM, not Claude Code")+ assert prov.agent is None+++def test_devin_service_trailer_matches() -> None:+ msg = (+ "feat: connector\n\n"+ "Co-authored-by: devin-ai-integration[bot] "+ "<158243242+devin-ai-integration[bot]@users.noreply.github.com>"+ )+ prov = _classify(msg=msg)+ assert (prov.agent, prov.autonomy_tier) == ("devin", 3)+++# ---------------------------------------------------------------------------+# Config-driven extension+# ---------------------------------------------------------------------------+++def test_extra_patterns_extend_the_registry() -> None:+ clf = AgentProvenanceClassifier(+ extra_service_emails={"[email protected]": ("mybot", 1)},+ extra_footer_patterns=[(r"generated by mybot", "mybot")],+ )+ assert clf.classify("MyBot", "[email protected]", "", "", "feat: x").agent == "mybot"+ assert clf.classify("Dev", "[email protected]", "", "", "fix: y\n\nGenerated by MyBot").autonomy_tier == 2+ # Built-ins still work — extras are additive, not a replacement.+ assert (+ clf.classify("Dev", "[email protected]", "", "", "x\n\nGenerated with Claude Code").agent == "claude"+ )+++# ---------------------------------------------------------------------------+# End-to-end: walk → sink/bucket → commit rows → per-file rollup+# ---------------------------------------------------------------------------+++def _log_record(sha, an, ae, subj, body="", files=((1, 0, "src/a.py"),), ts=None) -> str:+ ts = ts or int(time.time())+ lines = [f"\x00{sha}\x1f{an}\x1f{ae}\x1f{an}\x1f{ae}\x1f{ts}\x1f\x1f{subj}\x1f{body}"]+ for a, d, p in files:+ lines.append(f"{a}\t{d}\t{p}")+ return "\n".join(lines)+++def test_walk_carries_provenance_into_sink_rows_and_rollup() -> None:+ raw = "\n".join(+ [+ _log_record(+ "aaa",+ "Dev",+ "[email protected]",+ "feat: human work",+ ),+ _log_record(+ "bbb",+ "Dev",+ "[email protected]",+ "fix: agent work",+ body="Generated with Claude Code",+ ),+ _log_record(+ "ccc",+ "copilot-swe-agent[bot]",+ "12345+copilot-swe-agent[bot]@users.noreply.github.com",+ "fix: bot work",+ ),+ ]+ )+ repo = MagicMock()+ repo.git.log.return_value = raw++ sink: list[dict] = []+ index = load_commit_index(repo, 100, {"src/a.py"}, commit_sink=sink)++ by_sha = {c["sha"]: c for c in sink}+ assert by_sha["aaa"]["agent_name"] is None+ assert by_sha["bbb"]["agent_name"] == "claude"+ assert by_sha["bbb"]["agent_autonomy_tier"] == 2+ assert by_sha["ccc"]["agent_name"] == "copilot"+ assert by_sha["ccc"]["agent_autonomy_tier"] == 1++ # Commit rows carry the provenance columns straight through.+ rows = {r["sha"]: r for r in build_commit_rows(sink)}+ assert rows["aaa"]["agent_name"] is None+ assert rows["bbb"]["agent_name"] == "claude"+ assert rows["bbb"]["agent_channel"] == "message_footer"+ 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}.+ 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"] == 2+ assert abs(meta["agent_authored_pct"] - 2 / 3) < 1e-9+ assert json.loads(meta["agent_tier_counts_json"]) == {"1": 1, "2": 1}+++def test_rollup_zero_for_human_only_history() -> None:+ commits = [+ _CommitRec(+ sha=f"s{i}",+ author_name="Dev",+ author_email="[email protected]",+ ts=int(time.time()) - i,+ is_merge=False,+ subject=f"feat: {i}",+ )+ for i in range(3)+ ]+ meta = index_file(+ MagicMock(),+ "src/a.py",+ repo_path=MagicMock(),+ commit_limit=100,+ follow_renames=False,+ include_blame=False,+ precomputed_commits=commits,+ )+ assert meta["agent_commit_count"] == 0+ assert meta["agent_authored_pct"] == 0.0+ assert json.loads(meta["agent_tier_counts_json"]) == {}diff --git a/tests/unit/test_git_commit_index.py b/tests/unit/test_git_commit_index.pyindex 793b62353..c5bc6f592 100644--- a/tests/unit/test_git_commit_index.py+++ b/tests/unit/test_git_commit_index.py@@ -23,6 +23,10 @@ def _build_log(commits: list[dict]) -> str:+ "\x1f"+ c["ae"]+ "\x1f"+ + c.get("cn", c["an"])+ + "\x1f"+ + c.get("ce", c["ae"])+ + "\x1f"+ str(c["ct"])+ "\x1f"+ c.get("parents", "")diff --git a/tests/unit/test_git_commit_rows.py b/tests/unit/test_git_commit_rows.pyindex f8d0b5ed5..9f1f0a535 100644--- a/tests/unit/test_git_commit_rows.py+++ b/tests/unit/test_git_commit_rows.py@@ -25,6 +25,10 @@ def _build_log(commits: list[dict]) -> str:+ "\x1f"+ c["ae"]+ "\x1f"+ + c.get("cn", c["an"])+ + "\x1f"+ + c.get("ce", c["ae"])+ + "\x1f"+ str(c["ct"])+ "\x1f"+ c.get("parents", "")diff --git a/tests/unit/test_git_indexer.py b/tests/unit/test_git_indexer.pyindex 6f2454067..a74dea505 100644--- a/tests/unit/test_git_indexer.py+++ b/tests/unit/test_git_indexer.py@@ -385,13 +385,13 @@ class TestStableClassification:# Build 15 commits all older than 90 days.# _index_file now uses repo.git.log with NUL-delimited format:- # \x00<sha>\x1f<author>\x1f<email>\x1f<unix_ts>\x1f<parents>\x1f<subject>\x1f<body>+ # \x00<sha>\x1f<author>\x1f<email>\x1f<committer>\x1f<committer_email>\x1f<unix_ts>\x1f<parents>\x1f<subject>\x1f<body>old_date = datetime.now(UTC) - timedelta(days=180)log_lines = []for i in range(15):ts = int((old_date - timedelta(days=i)).timestamp())log_lines.append(- f"\x00sha{i:04d}\x1fAlice\[email protected]\x1f{ts}\x1f\x1ffeat: old commit {i}\x1f"+ f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f\x1ffeat: old commit {i}\x1f")mock_repo.git.log.return_value = "\n".join(log_lines)@@ -420,7 +420,7 @@ class TestStableClassification:for i, (name, email, when) in enumerate(specs):ts = int(when.timestamp())log_lines.append(- f"\x00sha{i:04d}\x1f{name}\x1f{email}\x1f{ts}\x1f\x1ffeat: c{i}\x1f"+ f"\x00sha{i:04d}\x1f{name}\x1f{email}\x1f{name}\x1f{email}\x1f{ts}\x1f\x1ffeat: c{i}\x1f")mock_repo.git.log.return_value = "\n".join(log_lines)@@ -448,7 +448,7 @@ class TestGitWindowAnchor:for i in range(15):ts = int((old_date - timedelta(days=i)).timestamp())log_lines.append(- f"\x00sha{i:04d}\x1fAlice\[email protected]\x1f{ts}\x1f\x1ffeat: old {i}\x1f"+ f"\x00sha{i:04d}\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{ts}\x1f\x1ffeat: old {i}\x1f")mock_repo.git.log.return_value = "\n".join(log_lines)# HEAD tip = the newest of the (old) batch.@@ -600,6 +600,8 @@ class TestNumstatParsing:header = (f"\x00{e['sha']}\x1f{e.get('author', 'Dev')}"f"\x1f{e.get('email', '[email protected]')}"+ f"\x1f{e.get('committer', e.get('author', 'Dev'))}"+ f"\x1f{e.get('committer_email', e.get('email', '[email protected]'))}"f"\x1f{e['ts']}\x1f{e.get('parents', '')}"f"\x1f{e.get('subject', 'some commit')}"f"\x1f{e.get('body', '')}"@@ -688,7 +690,7 @@ class TestNumstatParsing:# First record is malformed (only 3 fields), second is validraw = (f"\x00badsha\x1fAlice\[email protected]\n" # only 3 fields- f"\x00goodsha\x1fBob\[email protected]\x1f{recent_ts}\x1f\x1ffeat: valid commit\x1f\n"+ f"\x00goodsha\x1fBob\[email protected]\x1fBob\[email protected]\x1f{recent_ts}\x1f\x1ffeat: valid commit\x1f\n"f"10\t5\ttest.py\n")mock_repo.git.log.return_value = raw@@ -705,7 +707,7 @@ class TestNumstatParsing:recent_ts = int((datetime.now(UTC) - timedelta(days=5)).timestamp())raw = (- f"\x00sha1\x1fAlice\[email protected]\x1f{recent_ts}"+ f"\x00sha1\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{recent_ts}"f"\x1fparent1 parent2\x1fMerge branch main\x1f\n"f"5\t2\tmerged.py\n")@@ -726,13 +728,13 @@ class TestNumstatParsing:# Simulates --follow output: recent commit uses new name,# older commit uses rename notation, oldest uses old name.raw = (- f"\x00sha1\x1fAlice\[email protected]\x1f{recent_ts}\x1f\x1ffeat: update\x1f\n"+ f"\x00sha1\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{recent_ts}\x1f\x1ffeat: update\x1f\n"f"10\t3\tsrc/new_name.py\n"f"\n"- f"\x00sha2\x1fAlice\[email protected]\x1f{old_ts}\x1f\x1frename file\x1f\n"+ f"\x00sha2\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{old_ts}\x1f\x1frename file\x1f\n"f"0\t0\t{{src/old_name.py => src/new_name.py}}\n"f"\n"- f"\x00sha3\x1fAlice\[email protected]\x1f{old_ts - 86400}\x1f\x1ffeat: old work\x1f\n"+ f"\x00sha3\x1fAlice\[email protected]\x1fAlice\[email protected]\x1f{old_ts - 86400}\x1f\x1ffeat: old work\x1f\n"f"20\t5\tsrc/old_name.py\n")mock_repo.git.log.return_value = raw