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(git): attribute commits from agent-trace records (#861)

Raghav Chamadiya26911df5ee5a
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 d5cc1b57b..cbcc2fae9 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -132,7 +132,7 @@ def load_commit_index(
_extract_rename_paths,
_parse_commit_record,
)
- from .git_indexer.agent_provenance import AgentProvenanceClassifier
+ from .git_indexer.agent_provenance import AgentProvenanceClassifier, AgentTraceIndex
if provenance_classifier is None:
provenance_classifier = AgentProvenanceClassifier()
@@ -153,6 +153,8 @@ def load_commit_index(
# git-ai authorship notes for this window (``{}`` unless the repo uses them).
note_agents = load_git_ai_note_agents(repo, commit_limit)
+ # Agent-trace records (empty after one stat call unless the repo has them).
+ trace_index = AgentTraceIndex.load(repo)
bucket: dict[str, list[_CommitRec]] = {}
commits_parsed = 0
@@ -175,21 +177,11 @@ def load_commit_index(
continue
commits_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']}",
- note_agent=note_agents.get(header["sha"]),
- )
-
# 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.
- commit_changes: list[tuple[str, int, int]] = [] if commit_sink is not None else None # type: ignore[assignment]
+ # indexable subset). Parsed before classification because the
+ # agent-trace channel needs the changed-path set for its file-overlap
+ # check; the same list feeds the commit sink.
+ commit_changes: list[tuple[str, int, int]] = []
for line in numstat_lines:
cols = line.split("\t")
@@ -215,9 +207,27 @@ def load_commit_index(
added = 0
deleted = 0
- if commit_changes is not None:
- commit_changes.append((target, added, deleted))
+ commit_changes.append((target, added, deleted))
+
+ # Agent provenance — classified ONCE per commit here (not per touched
+ # file): the per-file records below share the result by reference.
+ trace_hit = (
+ trace_index.resolve(header["sha"], header["parents"], {t for t, _, _ in commit_changes})
+ if trace_index
+ else None
+ )
+ 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']}",
+ note_agent=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",
+ )
+ for target, added, deleted in commit_changes:
if target not in indexable_files:
continue
@@ -308,7 +318,7 @@ def load_deep_commit_index(
_extract_rename_paths,
_parse_commit_record,
)
- from .git_indexer.agent_provenance import AgentProvenanceClassifier
+ from .git_indexer.agent_provenance import AgentProvenanceClassifier, AgentTraceIndex
if not wanted_files:
return {}
@@ -332,6 +342,8 @@ def load_deep_commit_index(
# git-ai notes across the deep region (``{}`` unless the repo uses them).
note_agents = load_git_ai_note_agents(repo, skip + deep_limit)
+ # Agent-trace records (empty after one stat call unless the repo has them).
+ trace_index = AgentTraceIndex.load(repo)
bucket: dict[str, list[_CommitRec]] = {}
commits_parsed = 0
@@ -345,10 +357,13 @@ def load_deep_commit_index(
header, numstat_lines = parsed
commits_parsed += 1
- # Classified lazily — only commits that actually touch a wanted
- # file pay the provenance regexes (the window walk classifies
- # every commit because the commit sink needs the labels).
- prov = None
+ # Numstat parsed first so classification (below) can see the commit's
+ # full changed-path set, which the agent-trace channel's file-overlap
+ # check needs. Only commits that actually touch a wanted file pay the
+ # provenance work (the window walk classifies every commit because
+ # the commit sink needs the labels).
+ changes: list[tuple[str, int, int]] = []
+ touches_wanted = False
for line in numstat_lines:
cols = line.split("\t")
@@ -362,12 +377,6 @@ def load_deep_commit_index(
else:
target = stat_path
- if target not in wanted_files:
- continue
- records = bucket.setdefault(target, [])
- if len(records) >= per_file_limit:
- continue
-
try:
added = int(cols[0]) if cols[0] != "-" else 0
deleted = int(cols[1]) if cols[1] != "-" else 0
@@ -375,15 +384,35 @@ def load_deep_commit_index(
added = 0
deleted = 0
- if prov is None:
- 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']}",
- note_agent=note_agents.get(header["sha"]),
- )
+ changes.append((target, added, deleted))
+ if target in wanted_files:
+ touches_wanted = True
+
+ if not touches_wanted:
+ continue
+
+ trace_hit = (
+ trace_index.resolve(header["sha"], header["parents"], {t for t, _, _ in changes})
+ if trace_index
+ else None
+ )
+ 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']}",
+ note_agent=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",
+ )
+
+ for target, added, deleted in changes:
+ if target not in wanted_files:
+ continue
+ records = bucket.setdefault(target, [])
+ if len(records) >= per_file_limit:
+ continue
records.append(
_CommitRec(
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 775a9604a..1e5fb4e30 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/README.md
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/README.md
@@ -102,10 +102,19 @@ rename-tracking mode (which uses the per-file walk, not the batched index).
`{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).
+opencode, aider), `Co-authored-by:` trailers anchored to service
+identities, git-ai authorship notes (`refs/notes/ai`), and agent-trace
+records (the vendor-neutral [agent-trace](https://github.com/cursor/agent-trace)
+standard, read from `.agent-trace/traces.jsonl`). Tiers: **1** near-autonomous
+(an agent service account authored the commit) · **2** human-driven agent
+(footer, note, trace record, or a service identity as *committer* over a human
+author) · **3** assisted (co-author trailer only).
+
+Agent-trace records name a `vcs.revision` captured at edit or commit time, so
+`AgentTraceIndex` attributes a record to a commit when the revision matches
+the commit itself (confidence `high`) or one of its parents (the traced change
+landed in the child; confidence `medium`), and only when the record's file
+set overlaps the commit's changed paths.
Design rules:
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 67c0dc6dc..4589cbf6c 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
@@ -19,11 +19,15 @@ LLM), in strip-resistance order:
* an ``Assisted-by:`` trailer naming a recognized agent (the Fedora /
OpenInfra AI-attribution standard)
-Two cross-cutting channels ride the same rule set:
+Three cross-cutting channels ride the same rule set:
* a **git-ai authorship note** (``refs/notes/ai``, the git-ai standard) —
an explicit, line-level attestation attached to the commit. Read out of
band (see :mod:`git_commit_index`) and passed in pre-resolved as
``note_agent``; classified Tier 2 (``git_ai_note`` channel).
+ * an **agent-trace record** (the vendor-neutral agent-trace standard,
+ ``.agent-trace/traces.jsonl``) resolved to the commit by
+ :class:`AgentTraceIndex` and passed in as ``trace_agent``; classified
+ Tier 2 (``agent_trace`` channel).
* a ``Generated-by:`` trailer (Apache's AI-attribution footer) naming a
recognized agent — Tier 2 (``generated_by_trailer`` channel).
@@ -61,6 +65,7 @@ from __future__ import annotations
import json
import re
from dataclasses import dataclass
+from pathlib import Path
import structlog
@@ -69,6 +74,7 @@ logger = structlog.get_logger(__name__)
__all__ = [
"AgentProvenance",
"AgentProvenanceClassifier",
+ "AgentTraceIndex",
"_agent_from_git_ai_note",
"classifier_from_repo_config",
]
@@ -239,6 +245,156 @@ def _agent_from_git_ai_note(note: str) -> str | None:
return None
+# Agent-trace records (the vendor-neutral agent-trace standard, v0.1.x): JSONL
+# at ``.agent-trace/traces.jsonl``, the spec's reference-implementation storage
+# location. The spec itself is storage-agnostic; revisit when the ecosystem
+# settles on a git-notes ref.
+_TRACE_FILE = ".agent-trace/traces.jsonl"
+# A trace log is append-only and unbounded; past this size, skip it whole
+# rather than stall the git index parsing it.
+_TRACE_MAX_BYTES = 50 * 1024 * 1024
+_TRACE_AI_CONTRIBUTORS = frozenset({"ai", "mixed"})
+
+
+def _agent_from_trace_record(rec: object) -> tuple[str, str, frozenset[str]] | None:
+ """Resolve one agent-trace record to ``(revision, agent, ai_paths)``.
+
+ A record carries ``vcs.revision`` (the git sha at capture time), a
+ record-level ``tool``, and per-file ``conversations`` whose ``contributor``
+ says who wrote the ranges. Only ``ai`` / ``mixed`` contributors count.
+ The agent label prefers ``tool.name`` (matching the tool-level labels the
+ other channels produce) and falls back to the conversation's ``model_id``;
+ both resolve with ``allow_slug=True`` because the ``.agent-trace/`` log is
+ AI-specific by construction, same rationale as ``refs/notes/ai``. Multiple
+ distinct agents in one record: the one touching the most files wins, a tie
+ returns ``None`` (ambiguous, precision-first). Any malformed shape returns
+ ``None``: a broken record is never a signal.
+ """
+ if not isinstance(rec, dict):
+ return None
+ try:
+ revision = str((rec.get("vcs") or {}).get("revision") or "").strip().lower()
+ if not revision:
+ return None
+ tool_agent = _normalize_agent_token(
+ str((rec.get("tool") or {}).get("name") or ""), allow_slug=True
+ )
+ paths_by_agent: dict[str, set[str]] = {}
+ for f in rec.get("files") or []:
+ if not isinstance(f, dict):
+ continue
+ path = str(f.get("path") or "").strip().lstrip("/")
+ if not path:
+ continue
+ for conv in f.get("conversations") or []:
+ if not isinstance(conv, dict):
+ continue
+ contributor = conv.get("contributor") or {}
+ if str(contributor.get("type") or "").lower() not in _TRACE_AI_CONTRIBUTORS:
+ continue
+ agent = tool_agent or _normalize_agent_token(
+ str(contributor.get("model_id") or ""), allow_slug=True
+ )
+ if agent:
+ paths_by_agent.setdefault(agent, set()).add(path)
+ if not paths_by_agent:
+ return None
+ top = max(len(paths) for paths in paths_by_agent.values())
+ leaders = [a for a, paths in paths_by_agent.items() if len(paths) == top]
+ if len(leaders) != 1:
+ return None
+ return revision, leaders[0], frozenset(paths_by_agent[leaders[0]])
+ except Exception:
+ return None
+
+
+class AgentTraceIndex:
+ """Commit attribution from agent-trace records, loaded once per walk.
+
+ ``resolve`` maps a commit to an agent when a record's ``vcs.revision``
+ matches the commit itself (the record was written at or after the commit:
+ confidence ``"high"``) or one of its parents (the record was written at
+ edit time and the traced change landed in the child: confidence
+ ``"medium"``). Both cases additionally require the record's file set to
+ intersect the commit's changed paths; a revision match alone must not
+ attribute an unrelated commit.
+ """
+
+ def __init__(self, records: list[tuple[str, str, frozenset[str]]] | None = None) -> None:
+ self._by_revision: dict[str, list[tuple[str, frozenset[str]]]] = {}
+ for revision, agent, paths in records or []:
+ self._by_revision.setdefault(revision, []).append((agent, paths))
+
+ def __bool__(self) -> bool:
+ return bool(self._by_revision)
+
+ @classmethod
+ def load(cls, repo: object) -> AgentTraceIndex:
+ """Read ``.agent-trace/traces.jsonl`` from *repo*'s working tree.
+
+ 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.
+ """
+ try:
+ root = getattr(repo, "working_tree_dir", None)
+ if not root or not isinstance(root, (str, Path)):
+ return cls()
+ path = Path(root) / _TRACE_FILE
+ if not path.is_file():
+ return cls()
+ if path.stat().st_size > _TRACE_MAX_BYTES:
+ logger.warning("agent_trace_file_too_large", path=str(path))
+ return cls()
+ text = path.read_text(encoding="utf-8", errors="replace")
+ except Exception as exc: # a trace read must never break the git index
+ logger.warning("agent_trace_read_failed", error=str(exc))
+ return cls()
+ records: list[tuple[str, str, frozenset[str]]] = []
+ for line in text.splitlines():
+ if not line.strip():
+ continue
+ try:
+ rec = json.loads(line)
+ except ValueError:
+ continue
+ parsed = _agent_from_trace_record(rec)
+ if parsed:
+ records.append(parsed)
+ return cls(records)
+
+ def resolve(
+ self, sha: str, parents: tuple[str, ...], changed_paths: set[str]
+ ) -> tuple[str, str] | None:
+ """Attribute one commit: ``(agent, confidence)`` or ``None``."""
+ agent = self._match(sha, changed_paths)
+ if agent:
+ return agent, "high"
+ for parent in parents:
+ agent = self._match(parent, changed_paths)
+ if agent:
+ return agent, "medium"
+ return None
+
+ def _match(self, revision: str, changed_paths: set[str]) -> str | None:
+ candidates = self._by_revision.get((revision or "").lower())
+ if not candidates:
+ return None
+ # Weight each agent by how many of its traced files this commit
+ # actually changed; the dominant agent wins, a tie is ambiguous.
+ counts: dict[str, int] = {}
+ for agent, paths in candidates:
+ overlap = len(paths & changed_paths)
+ if overlap:
+ counts[agent] = counts.get(agent, 0) + overlap
+ 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
+
+
@dataclass(frozen=True)
class AgentProvenance:
"""One commit's agent attribution. ``agent is None`` means human."""
@@ -312,13 +468,17 @@ class AgentProvenanceClassifier:
committer_email: str,
message: str,
note_agent: str | None = None,
+ trace_agent: str | None = None,
+ trace_confidence: str = "high",
) -> 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 several channels.
*note_agent* is the pre-resolved agent from this commit's git-ai
authorship note (``refs/notes/ai``), or ``None`` when absent — read out
- of band by the caller so classification stays a pure function."""
+ 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."""
# T1 — agent service identity AUTHORED the commit.
hit = self._identity_match(author_email)
if hit:
@@ -328,6 +488,11 @@ class AgentProvenanceClassifier:
# above the message-derived channels.
if note_agent:
return AgentProvenance(note_agent, 2, "git_ai_note", "high")
+ # 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)
# T2 — message footer / aider author-name suffix.
for pat, agent in self._footers:
if pat.search(message):
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 0ad5f6094..f5ca87851 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/records.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/records.py
@@ -83,7 +83,8 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
by the first line matching :data:`_NUMSTAT_RE`; everything before it is
body. Returns ``(header, numstat_lines)`` or ``None`` if the record is
malformed (too few fields). ``header`` keys mirror :class:`_CommitRec`
- fields except ``added``/``deleted`` (the caller attributes churn).
+ fields except ``added``/``deleted`` (the caller attributes churn), plus
+ ``parents`` (the commit's parent shas).
"""
parts = record.split(_FIELD_SEP)
if len(parts) < 9:
@@ -109,6 +110,7 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
except ValueError:
ts = 0
+ parent_shas = tuple(p for p in parents.split() if p)
header = {
"sha": sha,
"author_name": an or "unknown",
@@ -116,7 +118,11 @@ def _parse_commit_record(record: str) -> tuple[dict, list[str]] | None:
"committer_name": cn or "",
"committer_email": ce or "",
"ts": ts,
- "is_merge": len(parents.split()) > 1,
+ "is_merge": len(parent_shas) > 1,
+ # Parent shas ride along for the agent-trace channel, whose records
+ # capture the pre-commit HEAD (i.e. a parent of the commit that
+ # contains the traced change).
+ "parents": parent_shas,
"subject": subject,
"body": "\n".join(body_lines).strip(),
}
diff --git a/tests/unit/ingestion/test_agent_provenance.py b/tests/unit/ingestion/test_agent_provenance.py
index 5e2c0b12d..186d2ccd8 100644
--- a/tests/unit/ingestion/test_agent_provenance.py
+++ b/tests/unit/ingestion/test_agent_provenance.py
@@ -18,7 +18,9 @@ from repowise.core.ingestion.git_commit_index import (
)
from repowise.core.ingestion.git_indexer.agent_provenance import (
AgentProvenanceClassifier,
+ AgentTraceIndex,
_agent_from_git_ai_note,
+ _agent_from_trace_record,
)
from repowise.core.ingestion.git_indexer.commit_rows import build_commit_rows
from repowise.core.ingestion.git_indexer.file_history import index_file
@@ -346,9 +348,11 @@ def test_extra_patterns_extend_the_registry() -> None:
# ---------------------------------------------------------------------------
-def _log_record(sha, an, ae, subj, body="", files=((1, 0, "src/a.py"),), ts=None) -> str:
+def _log_record(
+ sha, an, ae, subj, body="", files=((1, 0, "src/a.py"),), ts=None, parents=""
+) -> 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}"]
+ lines = [f"\x00{sha}\x1f{an}\x1f{ae}\x1f{an}\x1f{ae}\x1f{ts}\x1f{parents}\x1f{subj}\x1f{body}"]
for a, d, p in files:
lines.append(f"{a}\t{d}\t{p}")
return "\n".join(lines)
@@ -438,3 +442,168 @@ def test_rollup_zero_for_human_only_history() -> None:
assert meta["agent_commit_count"] == 0
assert meta["agent_authored_pct"] == 0.0
assert json.loads(meta["agent_tier_counts_json"]) == {}
+
+
+# ---------------------------------------------------------------------------
+# Agent-trace channel (.agent-trace/traces.jsonl)
+# ---------------------------------------------------------------------------
+
+
+def _trace_record(
+ revision, tool="cursor", files=("src/a.py",), contributor_type="ai", model_id=None
+) -> str:
+ contributor = {"type": contributor_type}
+ if model_id:
+ contributor["model_id"] = model_id
+ return json.dumps(
+ {
+ "version": "0.1.0",
+ "id": "550e8400-e29b-41d4-a716-446655440000",
+ "timestamp": "2026-01-25T10:00:00Z",
+ "vcs": {"type": "git", "revision": revision},
+ "tool": {"name": tool} if tool else None,
+ "files": [
+ {
+ "path": p,
+ "conversations": [
+ {"contributor": contributor, "ranges": [{"start_line": 1, "end_line": 5}]}
+ ],
+ }
+ for p in files
+ ],
+ }
+ )
+
+
+def test_trace_record_resolves_tool_name_first() -> None:
+ rec = json.loads(_trace_record("abc", tool="Cursor", model_id="anthropic/claude-opus-4-5"))
+ assert _agent_from_trace_record(rec) == ("abc", "cursor", frozenset({"src/a.py"}))
+
+
+def test_trace_record_falls_back_to_model_id() -> None:
+ rec = json.loads(_trace_record("abc", tool=None, model_id="anthropic/claude-opus-4-5"))
+ assert _agent_from_trace_record(rec) == ("abc", "claude", frozenset({"src/a.py"}))
+
+
+def test_trace_record_human_only_is_not_a_signal() -> None:
+ rec = json.loads(_trace_record("abc", contributor_type="human"))
+ assert _agent_from_trace_record(rec) is None
+
+
+def test_trace_record_mixed_counts_as_agent() -> None:
+ rec = json.loads(_trace_record("abc", contributor_type="mixed"))
+ assert _agent_from_trace_record(rec) is not None
+
+
+def test_trace_record_without_revision_is_skipped() -> None:
+ rec = json.loads(_trace_record("abc"))
+ del rec["vcs"]
+ assert _agent_from_trace_record(rec) is None
+
+
+def test_trace_index_resolves_exact_and_parent_matches() -> None:
+ idx = AgentTraceIndex(
+ [
+ ("sha_exact", "cursor", frozenset({"src/a.py"})),
+ ("sha_parent", "claude", frozenset({"src/b.py"})),
+ ]
+ )
+ # Revision IS the commit: high confidence.
+ assert idx.resolve("sha_exact", (), {"src/a.py"}) == ("cursor", "high")
+ # Revision is the commit's parent (trace captured pre-commit): medium.
+ assert idx.resolve("sha_child", ("sha_parent",), {"src/b.py"}) == ("claude", "medium")
+ # A revision match without file overlap must not attribute the commit.
+ assert idx.resolve("sha_exact", (), {"other.py"}) is None
+ assert idx.resolve("sha_unknown", ("sha_unrelated",), {"src/a.py"}) is None
+
+
+def test_trace_index_agent_tie_is_ambiguous() -> None:
+ idx = AgentTraceIndex(
+ [
+ ("rev", "cursor", frozenset({"src/a.py"})),
+ ("rev", "claude", frozenset({"src/b.py"})),
+ ]
+ )
+ assert idx.resolve("rev", (), {"src/a.py", "src/b.py"}) is None
+ # An unambiguous overlap still resolves.
+ assert idx.resolve("rev", (), {"src/a.py"}) == ("cursor", "high")
+
+
+def test_trace_agent_precedence_in_classify() -> None:
+ # Trace beats the message-derived channels...
+ prov = CLF.classify(
+ "Dev",
+ "",
+ "",
+ "x\n\nGenerated with Claude Code",
+ trace_agent="cursor",
+ trace_confidence="medium",
+ )
+ assert (prov.agent, prov.autonomy_tier, prov.channel) == ("cursor", 2, "agent_trace")
+ assert prov.confidence == "medium"
+ # ...but loses to the commit-attached git-ai note and to a T1 identity.
+ prov = CLF.classify("Dev", "[email protected]", "", "", "x", note_agent="claude", trace_agent="cursor")
+ assert prov.channel == "git_ai_note"
+ prov = CLF.classify("Cursor Agent", "[email protected]", "", "", "x", trace_agent="claude")
+ assert prov.channel == "service_email"
+
+
+def test_trace_index_load_missing_file_is_empty(tmp_path) -> None:
+ repo = MagicMock()
+ repo.working_tree_dir = str(tmp_path)
+ assert not AgentTraceIndex.load(repo)
+
+
+def test_trace_index_load_skips_malformed_lines(tmp_path) -> None:
+ trace_dir = tmp_path / ".agent-trace"
+ trace_dir.mkdir()
+ (trace_dir / "traces.jsonl").write_text(
+ "not json\n" + _trace_record("rev_a") + "\n{}\n", encoding="utf-8"
+ )
+ idx = AgentTraceIndex.load(MagicMock(working_tree_dir=str(tmp_path)))
+ assert idx.resolve("rev_a", (), {"src/a.py"}) == ("cursor", "high")
+
+
+def test_trace_index_load_never_raises_on_mock_repo() -> None:
+ # The walks pass whatever repo object they hold; a non-path working tree
+ # (or a bare repo's None) must degrade to an empty index, not an error.
+ assert not AgentTraceIndex.load(MagicMock())
+ assert not AgentTraceIndex.load(MagicMock(working_tree_dir=None))
+
+
+def test_walk_attributes_commits_from_trace_file(tmp_path) -> None:
+ trace_dir = tmp_path / ".agent-trace"
+ trace_dir.mkdir()
+ (trace_dir / "traces.jsonl").write_text(
+ _trace_record("bbb", tool="cursor") # captured at commit bbb itself
+ + "\n"
+ + _trace_record("aaa", tool="opencode", files=("src/b.py",)) # pre-commit HEAD
+ + "\n",
+ encoding="utf-8",
+ )
+ raw = "\n".join(
+ [
+ _log_record("aaa", "Dev", "[email protected]", "feat: base"),
+ _log_record("bbb", "Dev", "[email protected]", "feat: traced", parents="aaa"),
+ # Child of aaa touching src/b.py: attributed via the parent match.
+ _log_record(
+ "ccc", "Dev", "[email protected]", "feat: edit", files=((2, 0, "src/b.py"),), parents="aaa"
+ ),
+ ]
+ )
+ repo = MagicMock()
+ repo.working_tree_dir = str(tmp_path)
+ repo.git.for_each_ref.return_value = ""
+ repo.git.log.return_value = raw
+
+ sink: list[dict] = []
+ load_commit_index(repo, 100, {"src/a.py", "src/b.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"] == "cursor"
+ assert by_sha["bbb"]["agent_channel"] == "agent_trace"
+ assert by_sha["bbb"]["agent_confidence"] == "high"
+ assert by_sha["ccc"]["agent_name"] == "opencode"
+ assert by_sha["ccc"]["agent_confidence"] == "medium"