#!/usr/bin/env python3 """Reproduce the v1.10 attribution review; requires git, gh and Python 3. Usage: python3 analyse.py /path/to/kubevirt > results.json Reads the checkout without modifying it. GitHub PR data reflects query time. """ import collections import concurrent.futures import datetime import json import re import statistics import subprocess import sys REPO = sys.argv[1] RANGE = 'v1.9.0..v1.10.0' TOOLS = { 'Claude': r'claude|\bopus\b|\bsonnet\b', 'Cursor': r'cursor', 'GPT / Codex': r'\bgpt\b|codex', 'Composer': r'composer|anysphere', 'Copilot': r'copilot', 'Grok': r'grok', 'Gemini': r'gemini', 'Antigravity': r'antigravity', 'GLM': r'\bglm\b', 'IBM Bob': r'\bbob\b', } def git(*args): return subprocess.check_output(['git', '-C', REPO, *args], text=True) commits = {} formats = collections.Counter() tool_commits = collections.defaultdict(set) tool_authors = collections.defaultdict(set) for record in git('log', '--no-merges', '--format=%H%x1f%aE%x1f%B%x00', RANGE).split('\0'): if not record.strip(): continue sha, author, body = record.strip().split('\x1f', 2) # Parse the actual terminal trailer block using Git's own parser. trailers = subprocess.check_output( ['git', 'interpret-trailers', '--parse'], input=body, text=True) matched = [] for key, value in re.findall(r'^(assisted-by|co-authored-by|generated-by):\s*(.+)$', trailers, re.I | re.M): tools = [name for name, pattern in TOOLS.items() if re.search(pattern, value, re.I)] # Human co-authors are not AI attribution. Unknown disclosure values fail # explicitly so new tools cannot silently disappear from the results. if not tools and key.lower() != 'co-authored-by': raise ValueError(f'Unclassified disclosure: {key}: {value}') if tools: matched.append((key.lower(), value)) formats[f'{key.lower()}: {value}'] += 1 for tool in tools: tool_commits[tool].add(sha) tool_authors[tool].add(author.lower()) commits[sha] = {'author': author.lower(), 'ai': bool(matched), 'signed_off': bool(re.search(r'^Signed-off-by:\s*.+<[^<>]+>', body, re.I | re.M)), 'terminal_signoff': bool(re.search(r'^Signed-off-by:\s*.+<[^<>]+>', trailers, re.I | re.M))} ai = {sha for sha, c in commits.items() if c['ai']} merges = git('log', '--merges', '--format=%H %s', RANGE).splitlines() pr_groups = {} for line in merges: match = re.match(r'(\w+) Merge pull request #(\d+) ', line) if not match: continue merge, number = match.groups() members = set(git('rev-list', '--no-merges', f'{merge}^1..{merge}^2').splitlines()) & commits.keys() pr_groups[int(number)] = bool(members & ai) def fetch_batch(numbers): fields = 'number url baseRefName createdAt mergedAt additions deletions changedFiles' query = '{repository(owner:"kubevirt",name:"kubevirt"){' + ''.join( f'p{n}:pullRequest(number:{n}){{{fields}}}' for n in numbers) + '}}' result = json.loads(subprocess.check_output(['gh', 'api', 'graphql', '-f', f'query={query}'], text=True)) if result.get('errors'): raise RuntimeError(result['errors']) return list(result['data']['repository'].values()) numbers = sorted(pr_groups) batches = [numbers[i:i + 30] for i in range(0, len(numbers), 30)] with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: prs = [p for batch in executor.map(fetch_batch, batches) for p in batch] for p in prs: if not p or not p['mergedAt']: raise ValueError('Missing or unmerged PR') p['ai_attributed'] = pr_groups[p['number']] p['lines'] = p['additions'] + p['deletions'] p['days'] = (datetime.datetime.fromisoformat(p['mergedAt'].replace('Z', '+00:00')) - datetime.datetime.fromisoformat(p['createdAt'].replace('Z', '+00:00'))).total_seconds() / 86400 def summary(rows): return {'count': len(rows), **{f'median_{key}': statistics.median(p[key] for p in rows) for key in ['days', 'lines', 'additions', 'deletions', 'changedFiles']}} result = { 'range': RANGE, 'tag_commits': {tag: git('rev-parse', f'{tag}^{{commit}}').strip() for tag in ['v1.9.0', 'v1.10.0']}, 'queried_at': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'total_commits': len(commits) + len(merges), 'merges': len(merges), 'non_merge_commits': len(commits), 'ai_commits': len(ai), 'ai_authors_by_email': len({commits[s]['author'] for s in ai}), 'all_authors_by_email': len({c['author'] for c in commits.values()}), 'ai_with_signoff': sum(commits[s]['signed_off'] for s in ai), 'ai_with_terminal_signoff': sum(commits[s]['terminal_signoff'] for s in ai), 'tools': {tool: {'commits': len(shas), 'authors_by_email': len(tool_authors[tool])} for tool, shas in tool_commits.items()}, 'trailer_formats_casefolded_keys': dict(formats.most_common()), 'unmapped_non_merge_commits': len(commits.keys() - set().union(*[ set(git('rev-list', '--no-merges', f'{line.split()[0]}^1..{line.split()[0]}^2').splitlines()) for line in merges if re.match(r'\w+ Merge pull request #\d+ ', line)])), 'pr_summary': {label: summary([p for p in prs if p['ai_attributed'] == flag]) for flag, label in [(True, 'attributed'), (False, 'no_attribution')]}, 'main_pr_summary': {label: summary([p for p in prs if p['ai_attributed'] == flag and p['baseRefName'] == 'main']) for flag, label in [(True, 'attributed'), (False, 'no_attribution')]}, 'pr_by_size': {size: {label: summary([p for p in prs if p['ai_attributed'] == flag and low <= p['lines'] < high]) for flag, label in [(True, 'attributed'), (False, 'no_attribution')]} for size, low, high in [('small', 0, 50), ('medium', 50, 200), ('large', 200, float('inf'))]}, 'prs': sorted(prs, key=lambda p: p['number']), 'ai_commit_shas': sorted(ai), } print(json.dumps(result, indent=2))