Skip to content

Commit bc010dc

Browse files
codeprakhar25claude
andcommitted
feat: attribution accuracy fixes, remote-status command, README overhaul (v0.1.19)
- fix: exclude copilot from winning per-file attribution — Copilot fires onDidChangeTextDocument on all VS Code changes (including other agents' terminal edits and human keystrokes); events still captured for stats but never credited as the author of a file - fix: codex pre-task snapshot — snapshot dirty files at task_started, subtract at task_complete to isolate only files codex changed during its task; prevents cross-contamination from other agents' pending edits - fix: write local ref before GitHub API push in push.rs — local ref is now always written first so consolidate never finds an empty ref; GitHub push is best-effort and non-fatal - fix: consolidate GitHub push is non-fatal for non-GitHub remotes - fix: finalize-ledger.py writes AgentTrace format to local buffer so agentdiff list is populated after every commit - fix: remove .agentdiff/ dir creation from agentdiff init (only .git/agentdiff is needed) - feat: agentdiff remote-status — shows refs/agentdiff/* on origin with trace counts and local sync state; works with any git remote via git ls-remote - docs: README overhaul — agentdiff list promoted to hero example with correct column format (COMMIT/TIME/AGENT/MODEL/FILE(S)/LINES/TRUST/PROMPT); added agentdiff stats, remote-status, and list flags examples; attribution accuracy section in architecture overview Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent b9595cf commit bc010dc

13 files changed

Lines changed: 501 additions & 59 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "agentdiff"
3-
version = "0.1.18"
3+
version = "0.1.19"
44
edition = "2024"
55
rust-version = "1.85"
66
description = "Audit and trace autonomous AI code contributions in git repositories"

‎README.md‎

Lines changed: 77 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,17 @@
1717
agentdiff hooks into every major AI coding agent — Claude Code, Cursor, Codex, Copilot, Windsurf, OpenCode, Gemini — and writes a permanent, commit-scoped attribution record to your repository. Each record captures the agent name, model, prompt excerpt, and exact line ranges. All of it queryable from the CLI, no server required.
1818

1919
```
20-
agentdiff stats
20+
agentdiff list
2121
22-
Total lines tracked: 4,231
22+
agentdiff list — 5 entries
2323
24-
By Agent:
25-
claude-code 2,741 (65%) ████████████████████
26-
cursor 973 (23%) ███████
27-
copilot 353 (8%) ███
28-
human 164 (4%) █
24+
# COMMIT TIME AGENT MODEL FILE(S) LINES TRUST PROMPT
25+
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
26+
1 a1b2c3d4 Apr 14 09:12 claude-code claude-sonnet-4-6 src/commands/push.rs 1-47 92 "fix ordering: write local ref before…"
27+
2 b2c3d4e5 Apr 14 09:44 codex o4-mini src/store.rs +2 112-198, 201-230 — "add fetch_ref_content helper"
28+
3 c3d4e5f6 Apr 13 18:01 cursor cursor-fast src/cli.rs 305-381 — "add remote-status args struct"
29+
4 d4e5f6a7 Apr 13 17:30 opencode claude-sonnet-4-6 src/main.rs 80-94 88 "wire remote_status dispatch"
30+
5 e5f6a7b8 Apr 13 14:22 human — README.md — — —
2931
```
3032

3133
---
@@ -98,6 +100,7 @@ That's it. From here every commit is attributed to whichever agent (or human) wr
98100
| `agentdiff keys rotate` | Rotate your keypair and register the new key |
99101
| `agentdiff policy check` | Enforce AI attribution policy rules |
100102
| `agentdiff export` | Export traces in Agent Trace JSONL format |
103+
| `agentdiff remote-status` | Show remote trace ref state (`refs/agentdiff/*` on origin) |
101104
| `agentdiff migrate` | Import legacy ledger.jsonl into new storage |
102105
| `agentdiff config` | Manage global configuration |
103106

@@ -144,6 +147,10 @@ agentdiff configure --no-copilot --no-antigravity
144147

145148
# Skip git hook install during init
146149
agentdiff init --no-git-hook
150+
151+
# Check remote trace ref state after pushing
152+
agentdiff remote-status
153+
agentdiff remote-status --no-fetch # fast: show refs + SHAs only, skip trace counts
147154
```
148155

149156
</details>
@@ -168,19 +175,73 @@ Agent hooks for Claude, Cursor, Codex, Windsurf, OpenCode, and Gemini are all in
168175

169176
## Example Output
170177

178+
```
179+
agentdiff list
180+
181+
agentdiff list — 6 entries
182+
183+
# COMMIT TIME AGENT MODEL FILE(S) LINES TRUST PROMPT
184+
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
185+
1 a1b2c3d4 Apr 14 09:12 claude-code claude-sonnet-4-6 src/commands/push.rs 1-47 92 "fix ordering: write local ref befor…"
186+
2 b2c3d4e5 Apr 14 09:44 codex o4-mini src/store.rs +2 112-198, 201-230 — "add fetch_ref_content helper"
187+
3 c3d4e5f6 Apr 13 18:01 cursor cursor-fast src/cli.rs 305-381 — "add remote-status args struct"
188+
4 d4e5f6a7 Apr 13 17:30 opencode claude-sonnet-4-6 src/main.rs 80-94 88 "wire remote_status dispatch"
189+
5 e5f6a7b8 Apr 12 11:04 windsurf claude-sonnet-4-6 src/init.rs 44-68 — "remove legacy .agentdiff dir creat…"
190+
6 f6a7b8c9 Apr 11 16:22 human — README.md — — —
191+
```
192+
171193
<details>
172-
<summary>agentdiff list</summary>
194+
<summary>agentdiff list flags</summary>
195+
196+
```bash
197+
# Filter to a specific agent
198+
agentdiff list --agent claude-code
199+
200+
# Filter to files matching a path substring
201+
agentdiff list --file src/commands
173202

203+
# Show the 10 most recent entries
204+
agentdiff list -n 10
205+
206+
# Show only uncommitted (in-progress session) entries
207+
agentdiff list --uncommitted
174208
```
175-
agentdiff list — 5 entries
176209

177-
# COMMIT TIME AGENT MODEL FILES LINES PROMPT
178-
──────────────────────────────────────────────────────────────────────────────────────────────────
179-
1 a1b2c3d4 Mar 20 17:52 claude-code sonnet-4-6 1 17-24 "add auth middleware"
180-
2 b2c3d4e5 Mar 20 18:10 cursor cursor-fast 2 1, 44 "refactor utils module"
181-
3 c3d4e5f6 Mar 20 18:45 copilot gpt-4o 1 10-12 —
182-
4 d4e5f6a7 Mar 20 19:01 codex o4-mini 3 1-89 "migrate to new API"
183-
* (pending) Mar 20 19:14 claude-code sonnet-4-6 1 5-31 "add tests" (uncommitted)
210+
</details>
211+
212+
<details>
213+
<summary>agentdiff stats</summary>
214+
215+
```
216+
agentdiff stats — 4,231 lines tracked
217+
218+
By Agent:
219+
claude-code 2,741 (65%) ████████████████████
220+
codex 892 (21%) ███████
221+
opencode 282 (7%) ██
222+
cursor 148 (3%) █
223+
human 168 (4%) █
224+
225+
By Model:
226+
claude-sonnet-4-6 3,023 (72%)
227+
o4-mini 892 (21%)
228+
cursor-fast 148 (3%)
229+
— 168 (4%)
230+
```
231+
232+
</details>
233+
234+
<details>
235+
<summary>agentdiff remote-status</summary>
236+
237+
```
238+
agentdiff remote-status — github.com/org/repo
239+
240+
REF TRACES LOCAL
241+
────────────────────────────────────────────────────────────────────────────
242+
refs/agentdiff/meta 18 synced
243+
refs/agentdiff/traces/main 6 synced
244+
refs/agentdiff/traces/feature%2Fauth-rewrite 3 synced
184245
```
185246

186247
</details>

‎scripts/capture-codex.py‎

Lines changed: 82 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,57 @@ def collect_changed_lines(repo_root: str) -> Dict[str, List[int]]:
137137
return {k: sorted(set(v)) for k, v in result.items() if v}
138138

139139

140+
def get_dirty_file_names(repo_root: str) -> List[str]:
141+
"""Return repo-relative paths of all files currently differing from HEAD."""
142+
try:
143+
out = subprocess.run(
144+
["git", "diff", "HEAD", "--name-only"],
145+
capture_output=True, text=True, cwd=repo_root,
146+
)
147+
if out.returncode != 0:
148+
return []
149+
return [line.strip() for line in out.stdout.splitlines() if line.strip()]
150+
except Exception:
151+
return []
152+
153+
154+
def pre_task_state_path(repo_root: str) -> str:
155+
return os.path.join(repo_root, ".git", "agentdiff", "codex-pre-task.json")
156+
157+
158+
def save_pre_task_state(repo_root: str) -> None:
159+
"""Snapshot current dirty-file list so task_complete can isolate codex's changes."""
160+
dirty = get_dirty_file_names(repo_root)
161+
state_path = pre_task_state_path(repo_root)
162+
try:
163+
os.makedirs(os.path.dirname(state_path), exist_ok=True)
164+
with open(state_path, "w", encoding="utf-8") as f:
165+
json.dump({"files": sorted(dirty)}, f)
166+
debug_log(f"pre-task snapshot: {len(dirty)} dirty files → {state_path}")
167+
except Exception as e:
168+
debug_log(f"pre-task snapshot failed: {e}")
169+
170+
171+
def load_and_consume_pre_task_state(repo_root: str) -> set:
172+
"""Load and delete the pre-task snapshot; returns set of pre-existing dirty files."""
173+
state_path = pre_task_state_path(repo_root)
174+
pre_dirty: set = set()
175+
if not os.path.exists(state_path):
176+
return pre_dirty
177+
try:
178+
with open(state_path, "r", encoding="utf-8") as f:
179+
data = json.load(f)
180+
pre_dirty = set(data.get("files", []))
181+
debug_log(f"pre-task loaded: {len(pre_dirty)} pre-existing dirty files")
182+
except Exception as e:
183+
debug_log(f"pre-task load failed: {e}")
184+
try:
185+
os.unlink(state_path)
186+
except Exception:
187+
pass
188+
return pre_dirty
189+
190+
140191
def is_git_repo(path: str) -> bool:
141192
return bool(path) and os.path.exists(os.path.join(path, ".git"))
142193

@@ -499,10 +550,24 @@ def main() -> int:
499550
cwd, model, session_id, turn_id, prompt, event_name = extract_codex_context(events)
500551
debug_log(f"event_name={event_name!r} turn_id={turn_id!r} cwd_from_events={cwd!r}")
501552

502-
# Skip events that definitely aren't edits.
553+
# task_started: snapshot dirty files so task_complete can isolate what codex changed.
554+
task_started_events = {"task_started", "TaskStarted"}
555+
if event_name and event_name in task_started_events:
556+
debug_log(f"task_started: saving pre-task state")
557+
# Resolve repo root for snapshot (best-effort — use event cwd or process cwd).
558+
snap_candidates: List[str] = []
559+
append_unique(snap_candidates, cwd if isinstance(cwd, str) else "")
560+
append_unique(snap_candidates, os.getcwd())
561+
for candidate in snap_candidates:
562+
snap_root = find_repo_root(candidate)
563+
if is_git_repo(snap_root):
564+
save_pre_task_state(snap_root)
565+
break
566+
run_forward(forward_cmd, input_data)
567+
return 0
568+
569+
# Skip other non-edit events.
503570
known_skip_events = {
504-
"task_started",
505-
"TaskStarted",
506571
"turn_aborted",
507572
"TurnAborted",
508573
"agent-turn-start",
@@ -536,6 +601,20 @@ def main() -> int:
536601
run_forward(forward_cmd, input_data)
537602
return 0
538603

604+
# Filter out files that were already dirty before this codex task started.
605+
# This prevents codex from claiming attribution for changes made by other
606+
# agents (claude-code, opencode, etc.) that were pending at task_started.
607+
pre_task_files = load_and_consume_pre_task_state(repo_root) if repo_root else set()
608+
if pre_task_files:
609+
changed = {f: lines for f, lines in changed.items() if f not in pre_task_files}
610+
debug_log(
611+
f"post-filter: {len(changed)} files after excluding {len(pre_task_files)} pre-task dirty files"
612+
)
613+
if not changed:
614+
debug_log("skip: all changed files were pre-existing dirty (not codex's work)")
615+
run_forward(forward_cmd, input_data)
616+
return 0
617+
539618
if not chosen_cwd:
540619
chosen_cwd = cwd or os.getcwd()
541620
if not model:

‎scripts/finalize-ledger.py‎

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,19 @@
66
pollution) via git plumbing. Falls back to appending to ledger.jsonl on disk
77
if the git plumbing fails (e.g. first-time setup, no git binary on PATH).
88
9+
Also writes an AgentTrace record to the local per-branch trace buffer at
10+
.git/agentdiff/traces/{branch}.jsonl so that `agentdiff list` works without
11+
needing a push/consolidate first.
12+
913
Usage:
10-
finalize-ledger.py <repo_root> <pending_ledger> <pending_context> <ledger_path>
14+
finalize-ledger.py <repo_root> <pending_ledger> <pending_context> [<ledger_path>]
1115
"""
1216
import json
1317
import os
1418
import subprocess
1519
import sys
1620
import tempfile
21+
import uuid as uuid_mod
1722
from typing import List, Optional
1823

1924

@@ -139,6 +144,98 @@ def write_to_meta_branch(repo_root: str, new_content: str) -> bool:
139144
pass
140145

141146

147+
def write_agent_trace(repo_root: str, pending: dict, sha: str, ts: str) -> bool:
148+
"""Append an AgentTrace record to .git/agentdiff/traces/{branch}.jsonl.
149+
150+
This populates the local trace buffer so `agentdiff list` works immediately
151+
after a commit, without needing a push/consolidate first.
152+
"""
153+
# Get current branch name.
154+
branch_res = run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_root)
155+
if branch_res.returncode != 0:
156+
return False
157+
branch = branch_res.stdout.strip()
158+
if not branch or branch == "HEAD":
159+
return False
160+
161+
# Sanitize branch name to match store.rs: replace / with %2F.
162+
sanitized = branch.replace("/", "%2F")
163+
164+
# Ensure traces directory exists.
165+
traces_dir = os.path.join(repo_root, ".git", "agentdiff", "traces")
166+
os.makedirs(traces_dir, exist_ok=True)
167+
traces_path = os.path.join(traces_dir, f"{sanitized}.jsonl")
168+
169+
# Build per-file trace entries from pending payload.
170+
agent = str(pending.get("agent") or "human")
171+
model = str(pending.get("model") or "human")
172+
attribution = pending.get("attribution") or {}
173+
lines_map = pending.get("lines") or {}
174+
175+
files = []
176+
for file_path, ranges in lines_map.items():
177+
file_attr = attribution.get(file_path, {})
178+
file_agent = str(file_attr.get("agent") or agent)
179+
file_model = str(file_attr.get("model") or model)
180+
181+
contributor_type = "human" if file_agent == "human" else "ai"
182+
contributor: dict = {"type": contributor_type}
183+
if file_model and file_model != "human":
184+
contributor["model_id"] = file_model
185+
186+
trace_ranges = []
187+
for r in ranges:
188+
if isinstance(r, (list, tuple)) and len(r) == 2:
189+
trace_ranges.append({
190+
"start_line": int(min(r[0], r[1])),
191+
"end_line": int(max(r[0], r[1])),
192+
})
193+
194+
if trace_ranges:
195+
files.append({
196+
"path": file_path,
197+
"conversations": [{
198+
"contributor": contributor,
199+
"ranges": trace_ranges,
200+
}],
201+
})
202+
203+
if not files:
204+
return True # Nothing to record, not an error.
205+
206+
# Build metadata extension block.
207+
metadata: dict = {}
208+
if pending.get("prompt_excerpt"):
209+
metadata["prompt_excerpt"] = str(pending["prompt_excerpt"])
210+
if pending.get("prompt_hash"):
211+
metadata["prompt_hash"] = str(pending["prompt_hash"])
212+
if isinstance(pending.get("trust"), int):
213+
metadata["trust"] = pending["trust"]
214+
if isinstance(pending.get("flags"), list) and pending["flags"]:
215+
metadata["flags"] = pending["flags"]
216+
if pending.get("session_id"):
217+
metadata["session_id"] = str(pending["session_id"])
218+
219+
trace: dict = {
220+
"version": "0.1.0",
221+
"id": str(uuid_mod.uuid4()),
222+
"timestamp": ts,
223+
"vcs": {"type": "git", "revision": sha},
224+
"tool": {"name": agent},
225+
"files": files,
226+
}
227+
if metadata:
228+
trace["metadata"] = metadata
229+
230+
line = json.dumps(trace, separators=(",", ":")) + "\n"
231+
try:
232+
with open(traces_path, "a", encoding="utf-8") as f:
233+
f.write(line)
234+
return True
235+
except Exception:
236+
return False
237+
238+
142239
def sha_exists_on_disk(ledger_path: str, sha: str) -> bool:
143240
if not os.path.exists(ledger_path):
144241
return False
@@ -224,6 +321,10 @@ def main() -> int:
224321
entry = {k: v for (k, v) in entry.items() if v is not None}
225322
entry_line = json.dumps(entry, separators=(",", ":")) + "\n"
226323

324+
# Write AgentTrace format to the local per-branch buffer so that
325+
# `agentdiff list` works immediately (no push/consolidate required).
326+
write_agent_trace(repo_root, pending, sha, ts)
327+
227328
# Try writing to agentdiff-meta branch (enterprise storage).
228329
existing = meta_content if meta_content is not None else ""
229330
if write_to_meta_branch(repo_root, existing + entry_line):

0 commit comments

Comments
 (0)