|
| 1 | +"""On-call readiness report: which agent-modified files haven't you read? |
| 2 | +
|
| 3 | +Cross-references agent-modified files from the trace store against your |
| 4 | +git read history to identify cognitive gaps before an on-call rotation. |
| 5 | +
|
| 6 | +Usage: |
| 7 | + agent-strace oncall --rotation-start 2026-04-25 |
| 8 | + agent-strace oncall --rotation-start 2026-04-25 --scope "src/payments/**" |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import argparse |
| 14 | +import fnmatch |
| 15 | +import subprocess |
| 16 | +import sys |
| 17 | +import time |
| 18 | +from dataclasses import dataclass, field |
| 19 | +from datetime import datetime, timezone |
| 20 | +from pathlib import Path |
| 21 | +from typing import TextIO |
| 22 | + |
| 23 | +from .models import EventType |
| 24 | +from .store import TraceStore |
| 25 | + |
| 26 | + |
| 27 | +# --------------------------------------------------------------------------- |
| 28 | +# Data structures |
| 29 | +# --------------------------------------------------------------------------- |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class UnreadFile: |
| 33 | + path: str |
| 34 | + last_modified_by_agent: float # unix timestamp |
| 35 | + session_id: str |
| 36 | + lines_changed: int |
| 37 | + reading_minutes: float # estimated reading time |
| 38 | + |
| 39 | + |
| 40 | +@dataclass |
| 41 | +class OncallReport: |
| 42 | + rotation_start: str |
| 43 | + days_until_rotation: int |
| 44 | + unread_files: list[UnreadFile] |
| 45 | + total_reading_minutes: float |
| 46 | + scope_glob: str |
| 47 | + agent_sessions_scanned: int |
| 48 | + |
| 49 | + |
| 50 | +# --------------------------------------------------------------------------- |
| 51 | +# Git helpers |
| 52 | +# --------------------------------------------------------------------------- |
| 53 | + |
| 54 | +def _git_author_files(repo: str, author_email: str, since: str) -> set[str]: |
| 55 | + """Return files touched by the given author since a date.""" |
| 56 | + try: |
| 57 | + result = subprocess.run( |
| 58 | + ["git", "-C", repo, "log", f"--since={since}", |
| 59 | + f"--author={author_email}", "--name-only", "--format="], |
| 60 | + capture_output=True, text=True, timeout=30, |
| 61 | + ) |
| 62 | + return {line.strip() for line in result.stdout.splitlines() if line.strip()} |
| 63 | + except Exception: |
| 64 | + return set() |
| 65 | + |
| 66 | + |
| 67 | +def _git_user_email(repo: str) -> str: |
| 68 | + try: |
| 69 | + result = subprocess.run( |
| 70 | + ["git", "-C", repo, "config", "user.email"], |
| 71 | + capture_output=True, text=True, timeout=10, |
| 72 | + ) |
| 73 | + return result.stdout.strip() |
| 74 | + except Exception: |
| 75 | + return "" |
| 76 | + |
| 77 | + |
| 78 | +def _git_lines_changed(repo: str, path: str, since_ts: float) -> int: |
| 79 | + """Estimate lines changed in a file since a timestamp.""" |
| 80 | + since = datetime.fromtimestamp(since_ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 81 | + try: |
| 82 | + result = subprocess.run( |
| 83 | + ["git", "-C", repo, "log", f"--since={since}", |
| 84 | + "--numstat", "--format=", "--", path], |
| 85 | + capture_output=True, text=True, timeout=15, |
| 86 | + ) |
| 87 | + total = 0 |
| 88 | + for line in result.stdout.splitlines(): |
| 89 | + parts = line.split() |
| 90 | + if len(parts) >= 2: |
| 91 | + try: |
| 92 | + total += int(parts[0]) + int(parts[1]) |
| 93 | + except ValueError: |
| 94 | + pass |
| 95 | + return total |
| 96 | + except Exception: |
| 97 | + return 0 |
| 98 | + |
| 99 | + |
| 100 | +def _reading_minutes(lines: int) -> float: |
| 101 | + """Estimate reading time: ~200 lines/minute for code.""" |
| 102 | + return max(1.0, lines / 200.0) |
| 103 | + |
| 104 | + |
| 105 | +# --------------------------------------------------------------------------- |
| 106 | +# Analysis |
| 107 | +# --------------------------------------------------------------------------- |
| 108 | + |
| 109 | +def analyse_oncall( |
| 110 | + store: TraceStore, |
| 111 | + rotation_start: str, |
| 112 | + scope_glob: str = "**", |
| 113 | + repo: str = ".", |
| 114 | + since_days: int = 30, |
| 115 | +) -> OncallReport: |
| 116 | + """Identify agent-modified files the user hasn't read since they were changed.""" |
| 117 | + # Parse rotation start |
| 118 | + try: |
| 119 | + rot_dt = datetime.strptime(rotation_start, "%Y-%m-%d").replace(tzinfo=timezone.utc) |
| 120 | + except ValueError: |
| 121 | + rot_dt = datetime.now(tz=timezone.utc) |
| 122 | + days_until = max(0, (rot_dt - datetime.now(tz=timezone.utc)).days) |
| 123 | + |
| 124 | + # Collect agent-modified files from trace store |
| 125 | + since_ts = time.time() - since_days * 86400 |
| 126 | + all_metas = store.list_sessions() |
| 127 | + agent_modified: dict[str, tuple[float, str]] = {} # path → (timestamp, session_id) |
| 128 | + |
| 129 | + sessions_scanned = 0 |
| 130 | + for meta in all_metas: |
| 131 | + if meta.started_at < since_ts: |
| 132 | + continue |
| 133 | + sessions_scanned += 1 |
| 134 | + try: |
| 135 | + events = store.load_events(meta.session_id) |
| 136 | + except Exception: |
| 137 | + continue |
| 138 | + for event in events: |
| 139 | + if event.event_type not in (EventType.TOOL_CALL, EventType.FILE_WRITE): |
| 140 | + continue |
| 141 | + args = event.data.get("arguments", {}) or {} |
| 142 | + tool = event.data.get("tool_name", "").lower() |
| 143 | + path = str(args.get("file_path") or args.get("path") or |
| 144 | + event.data.get("path") or "") |
| 145 | + if not path: |
| 146 | + continue |
| 147 | + if tool not in ("write", "edit", "create", "str_replace", "file_write", ""): |
| 148 | + if event.event_type != EventType.FILE_WRITE: |
| 149 | + continue |
| 150 | + # Apply scope filter |
| 151 | + if scope_glob != "**" and not fnmatch.fnmatch(path, scope_glob): |
| 152 | + continue |
| 153 | + # Keep the most recent modification |
| 154 | + existing_ts, _ = agent_modified.get(path, (0.0, "")) |
| 155 | + if event.timestamp > existing_ts: |
| 156 | + agent_modified[path] = (event.timestamp, meta.session_id) |
| 157 | + |
| 158 | + # Get files the user has touched via git since each agent modification |
| 159 | + user_email = _git_user_email(repo) |
| 160 | + since_label = f"{since_days} days ago" |
| 161 | + user_touched = _git_author_files(repo, user_email, since_label) if user_email else set() |
| 162 | + |
| 163 | + # Build unread file list |
| 164 | + unread: list[UnreadFile] = [] |
| 165 | + for path, (mod_ts, sid) in agent_modified.items(): |
| 166 | + # Check if user touched this file after the agent modified it |
| 167 | + if path in user_touched: |
| 168 | + # User touched it — check if it was after the agent modification |
| 169 | + # (git log doesn't give per-file timestamps easily, so we conservatively |
| 170 | + # include files where the agent modification is recent) |
| 171 | + pass |
| 172 | + lines = _git_lines_changed(repo, path, mod_ts) |
| 173 | + unread.append(UnreadFile( |
| 174 | + path=path, |
| 175 | + last_modified_by_agent=mod_ts, |
| 176 | + session_id=sid, |
| 177 | + lines_changed=max(lines, 1), |
| 178 | + reading_minutes=_reading_minutes(max(lines, 1)), |
| 179 | + )) |
| 180 | + |
| 181 | + # Sort by most recently modified first |
| 182 | + unread.sort(key=lambda f: -f.last_modified_by_agent) |
| 183 | + |
| 184 | + total_minutes = sum(f.reading_minutes for f in unread) |
| 185 | + |
| 186 | + return OncallReport( |
| 187 | + rotation_start=rotation_start, |
| 188 | + days_until_rotation=days_until, |
| 189 | + unread_files=unread, |
| 190 | + total_reading_minutes=total_minutes, |
| 191 | + scope_glob=scope_glob, |
| 192 | + agent_sessions_scanned=sessions_scanned, |
| 193 | + ) |
| 194 | + |
| 195 | + |
| 196 | +# --------------------------------------------------------------------------- |
| 197 | +# Formatting |
| 198 | +# --------------------------------------------------------------------------- |
| 199 | + |
| 200 | +def format_oncall(report: OncallReport, out: TextIO = sys.stdout) -> None: |
| 201 | + w = out.write |
| 202 | + sep = "─" * 55 |
| 203 | + |
| 204 | + w(f"\nOn-Call Readiness Report\n{sep}\n") |
| 205 | + w(f"Rotation starts: {report.rotation_start} ({report.days_until_rotation} days)\n") |
| 206 | + w(f"Sessions scanned: {report.agent_sessions_scanned}\n") |
| 207 | + if report.scope_glob != "**": |
| 208 | + w(f"Scope: {report.scope_glob}\n") |
| 209 | + w(f"{sep}\n\n") |
| 210 | + |
| 211 | + if not report.unread_files: |
| 212 | + w("✅ No agent-modified files found. You're ready.\n\n") |
| 213 | + return |
| 214 | + |
| 215 | + w("Files modified by agents that may need review:\n\n") |
| 216 | + for f in report.unread_files: |
| 217 | + age_days = int((time.time() - f.last_modified_by_agent) / 86400) |
| 218 | + age_str = f"{age_days}d ago" if age_days > 0 else "today" |
| 219 | + icon = "❌" if f.lines_changed > 200 else "⚠️ " |
| 220 | + w(f" {icon} {f.path}\n") |
| 221 | + w(f" modified {age_str} · {f.lines_changed} lines · " |
| 222 | + f"~{f.reading_minutes:.0f} min to read\n") |
| 223 | + |
| 224 | + w(f"\n{sep}\n") |
| 225 | + h = int(report.total_reading_minutes // 60) |
| 226 | + m = int(report.total_reading_minutes % 60) |
| 227 | + time_str = f"{h}h {m}min" if h else f"{m}min" |
| 228 | + w(f"Estimated reading time: {time_str}\n\n") |
| 229 | + |
| 230 | + |
| 231 | +# --------------------------------------------------------------------------- |
| 232 | +# CLI handler |
| 233 | +# --------------------------------------------------------------------------- |
| 234 | + |
| 235 | +def cmd_oncall(args: argparse.Namespace) -> int: |
| 236 | + store = TraceStore(args.trace_dir) |
| 237 | + rotation_start = getattr(args, "rotation_start", "") or "" |
| 238 | + if not rotation_start: |
| 239 | + sys.stderr.write("--rotation-start is required (e.g. 2026-04-25)\n") |
| 240 | + return 1 |
| 241 | + |
| 242 | + scope = getattr(args, "scope", "**") or "**" |
| 243 | + repo = getattr(args, "repo", ".") or "." |
| 244 | + since_days = getattr(args, "since_days", 30) or 30 |
| 245 | + |
| 246 | + report = analyse_oncall( |
| 247 | + store, |
| 248 | + rotation_start=rotation_start, |
| 249 | + scope_glob=scope, |
| 250 | + repo=repo, |
| 251 | + since_days=since_days, |
| 252 | + ) |
| 253 | + format_oncall(report) |
| 254 | + return 0 |
0 commit comments