grokmap 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
grokmap/detect.py ADDED
@@ -0,0 +1,74 @@
1
+ """Decide whether a commit was written (or co-written) by an AI coding agent.
2
+
3
+ Detection is evidence-based: we only flag a commit when its metadata carries a
4
+ marker the tools themselves leave behind (co-author trailers, bot authors,
5
+ "Generated with" footers). Teams can add their own patterns in config.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import dataclass
12
+
13
+ from grokmap.gitutil import CommitInfo
14
+
15
+ # (tool, where, pattern). where: "message" | "author"
16
+ BUILTIN_SIGNATURES: list[tuple[str, str, str]] = [
17
+ # Anthropic Claude / Claude Code
18
+ ("claude", "message", r"^co-authored-by:.*\b(claude|anthropic)\b"),
19
+ ("claude", "message", r"generated with \[?claude code"),
20
+ ("claude", "message", r"^claude-session:"),
21
+ ("claude", "author", r"\bclaude\[bot\]|noreply@anthropic\.com"),
22
+ # GitHub Copilot (agent mode, coding agent, co-author trailer)
23
+ ("copilot", "message", r"^co-authored-by:.*\b(copilot|github copilot)\b"),
24
+ ("copilot", "author", r"copilot-swe-agent|^copilot\b|copilot@github\.com|\bcopilot\[bot\]"),
25
+ # Cursor
26
+ ("cursor", "message", r"^co-authored-by:.*\bcursor(agent)?\b"),
27
+ ("cursor", "author", r"cursoragent@cursor\.com|\bcursor agent\b"),
28
+ # OpenAI Codex / ChatGPT
29
+ ("codex", "message", r"^co-authored-by:.*\b(codex|chatgpt|openai)\b"),
30
+ ("codex", "author", r"\bchatgpt-codex|codex\[bot\]"),
31
+ # Aider
32
+ ("aider", "message", r"^aider:"),
33
+ ("aider", "message", r"^co-authored-by:.*\baider\b"),
34
+ ("aider", "author", r"\(aider\)"),
35
+ # Devin
36
+ ("devin", "author", r"devin-ai-integration|\bdevin\b.*\[bot\]"),
37
+ ("devin", "message", r"^co-authored-by:.*\bdevin\b"),
38
+ # Google Gemini / Jules
39
+ ("gemini", "message", r"^co-authored-by:.*\b(gemini|jules)\b"),
40
+ ("gemini", "author", r"gemini-code-assist|google-labs-jules|\bjules\[bot\]"),
41
+ # Amazon Q / Kiro
42
+ ("amazon-q", "message", r"^co-authored-by:.*\b(amazon q|kiro)\b"),
43
+ # Windsurf / Codeium
44
+ ("windsurf", "message", r"^co-authored-by:.*\b(windsurf|codeium|cascade)\b"),
45
+ # Generic marker many teams adopt
46
+ ("ai", "message", r"^(ai-assisted|ai-generated|assisted-by):"),
47
+ ]
48
+
49
+
50
+ @dataclass
51
+ class Detector:
52
+ signatures: list[tuple[str, str, re.Pattern[str]]]
53
+ forced: dict[str, str] # sha prefix -> tool, from config
54
+
55
+ @classmethod
56
+ def build(cls, extra: dict[str, str] | None = None, forced: dict[str, str] | None = None) -> Detector:
57
+ sigs = [(tool, where, re.compile(pat, re.IGNORECASE | re.MULTILINE)) for tool, where, pat in BUILTIN_SIGNATURES]
58
+ for tool, pat in (extra or {}).items():
59
+ where = "message"
60
+ if pat.startswith("author:"):
61
+ where, pat = "author", pat[len("author:") :]
62
+ sigs.append((tool, where, re.compile(pat, re.IGNORECASE | re.MULTILINE)))
63
+ return cls(sigs, {k.lower(): v for k, v in (forced or {}).items()})
64
+
65
+ def tool_for(self, info: CommitInfo) -> str | None:
66
+ for prefix, tool in self.forced.items():
67
+ if info.sha.lower().startswith(prefix):
68
+ return tool or None
69
+ author = f"{info.author_name} <{info.author_email}>"
70
+ for tool, where, rx in self.signatures:
71
+ text = info.message if where == "message" else author
72
+ if rx.search(text):
73
+ return tool
74
+ return None
grokmap/gitutil.py ADDED
@@ -0,0 +1,158 @@
1
+ """Thin wrappers around the git CLI. grokmap shells out to git and has no other dependencies."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ class GitError(RuntimeError):
12
+ pass
13
+
14
+
15
+ def run_git(args: list[str], cwd: Path, input_text: str | None = None, check: bool = True) -> str:
16
+ env = dict(os.environ)
17
+ env.setdefault("LC_ALL", "C")
18
+ env["GIT_OPTIONAL_LOCKS"] = "0"
19
+ proc = subprocess.run(
20
+ ["git", *args],
21
+ cwd=str(cwd),
22
+ input=input_text,
23
+ capture_output=True,
24
+ text=True,
25
+ encoding="utf-8",
26
+ errors="replace",
27
+ env=env,
28
+ )
29
+ if check and proc.returncode != 0:
30
+ raise GitError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
31
+ return proc.stdout
32
+
33
+
34
+ def repo_root(start: Path) -> Path:
35
+ try:
36
+ out = run_git(["rev-parse", "--show-toplevel"], start).strip()
37
+ except (GitError, FileNotFoundError) as exc:
38
+ raise GitError(f"{start} is not inside a git repository") from exc
39
+ return Path(out)
40
+
41
+
42
+ def head_sha(root: Path) -> str | None:
43
+ out = run_git(["rev-parse", "--verify", "-q", "HEAD"], root, check=False).strip()
44
+ return out or None
45
+
46
+
47
+ def current_user(root: Path) -> str:
48
+ for key in ("user.email", "user.name"):
49
+ out = run_git(["config", key], root, check=False).strip()
50
+ if out:
51
+ return out
52
+ return os.environ.get("USER") or os.environ.get("USERNAME") or "unknown"
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class TrackedFile:
57
+ path: str # repo-relative, forward slashes
58
+ blob: str # blob sha at HEAD
59
+
60
+
61
+ def tracked_files(root: Path) -> list[TrackedFile]:
62
+ """Files tracked at HEAD with their blob ids (regular files only, no submodules)."""
63
+ out = run_git(["ls-tree", "-r", "-z", "--full-tree", "HEAD"], root, check=False)
64
+ files: list[TrackedFile] = []
65
+ for entry in out.split("\0"):
66
+ if not entry:
67
+ continue
68
+ meta, _, path = entry.partition("\t")
69
+ parts = meta.split()
70
+ if len(parts) != 3 or parts[1] != "blob" or parts[0] == "120000":
71
+ continue
72
+ files.append(TrackedFile(path=path, blob=parts[2]))
73
+ return files
74
+
75
+
76
+ @dataclass
77
+ class CommitInfo:
78
+ sha: str
79
+ author_name: str
80
+ author_email: str
81
+ time: int
82
+ message: str
83
+
84
+
85
+ def commit_infos(root: Path, shas: list[str]) -> dict[str, CommitInfo]:
86
+ """Fetch author and full message for many commits in one git call."""
87
+ result: dict[str, CommitInfo] = {}
88
+ if not shas:
89
+ return result
90
+ fmt = "%H%x00%an%x00%ae%x00%ct%x00%B%x1e"
91
+ out = run_git(
92
+ ["log", "--no-walk=unsorted", "--stdin", f"--format={fmt}"],
93
+ root,
94
+ input_text="\n".join(shas) + "\n",
95
+ )
96
+ for record in out.split("\x1e"):
97
+ record = record.lstrip("\n")
98
+ if not record:
99
+ continue
100
+ parts = record.split("\x00")
101
+ if len(parts) < 5:
102
+ continue
103
+ sha, name, email, ts, message = parts[0], parts[1], parts[2], parts[3], "\x00".join(parts[4:])
104
+ try:
105
+ t = int(ts)
106
+ except ValueError:
107
+ t = 0
108
+ result[sha] = CommitInfo(sha, name, email, t, message)
109
+ return result
110
+
111
+
112
+ def blame_porcelain(root: Path, path: str, rev: str = "HEAD") -> str:
113
+ return run_git(["blame", "--line-porcelain", "-w", rev, "--", path], root)
114
+
115
+
116
+ def diff_files(root: Path, base: str | None, staged: bool) -> list[str]:
117
+ """Paths changed relative to base (or the working tree vs HEAD)."""
118
+ args = ["diff", "--name-only", "--diff-filter=AMR", "-z"]
119
+ if staged:
120
+ args.append("--cached")
121
+ if base:
122
+ args.append(base)
123
+ out = run_git(args, root)
124
+ paths = [p for p in out.split("\0") if p]
125
+ if not staged and not base:
126
+ # include untracked files too: an agent often writes brand-new files
127
+ extra = run_git(["ls-files", "--others", "--exclude-standard", "-z"], root)
128
+ paths += [p for p in extra.split("\0") if p]
129
+ return sorted(set(paths))
130
+
131
+
132
+ def diff_added_lines(root: Path, path: str, base: str | None, staged: bool) -> list[tuple[int, int]] | None:
133
+ """Line ranges (1-based, inclusive) added in the working copy of path. None = whole file is new."""
134
+ args = ["diff", "-U0", "--no-color"]
135
+ if staged:
136
+ args.append("--cached")
137
+ if base:
138
+ args.append(base)
139
+ args += ["--", path]
140
+ out = run_git(args, root, check=False)
141
+ if not out.strip():
142
+ tracked = run_git(["ls-files", "--error-unmatch", "--", path], root, check=False).strip()
143
+ return None if not tracked else []
144
+ ranges: list[tuple[int, int]] = []
145
+ for line in out.splitlines():
146
+ if line.startswith("@@"):
147
+ try:
148
+ plus = line.split("+", 1)[1].split(" ", 1)[0]
149
+ except IndexError:
150
+ continue
151
+ if "," in plus:
152
+ start_s, count_s = plus.split(",", 1)
153
+ start, count = int(start_s), int(count_s)
154
+ else:
155
+ start, count = int(plus), 1
156
+ if count > 0:
157
+ ranges.append((start, start + count - 1))
158
+ return ranges
grokmap/ledger.py ADDED
@@ -0,0 +1,97 @@
1
+ """The understanding ledger: an append-only record of who has shown they understand which code.
2
+
3
+ Each record stores short hashes of the meaningful lines the person was checked on.
4
+ A line counts as understood only while its content is unchanged, so edits made
5
+ after the quiz automatically show up as new, not-yet-understood code.
6
+
7
+ The ledger lives in `.grokmap/ledger.jsonl` and is meant to be committed, so the
8
+ whole team shares it. One JSON object per line keeps git merges painless
9
+ (grokmap init adds `merge=union` for it in .gitattributes).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from dataclasses import dataclass
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+
19
+ from grokmap.scan import STATE_DIR
20
+
21
+ LEDGER_NAME = "ledger.jsonl"
22
+ METHODS = ("quiz", "explain", "review", "wrote", "pair")
23
+
24
+
25
+ @dataclass
26
+ class Record:
27
+ path: str
28
+ who: str
29
+ score: float
30
+ method: str
31
+ at: datetime
32
+ hashes: frozenset[str]
33
+ note: str = ""
34
+
35
+ def to_json(self) -> str:
36
+ return json.dumps(
37
+ {
38
+ "v": 1,
39
+ "path": self.path,
40
+ "who": self.who,
41
+ "score": round(self.score, 3),
42
+ "method": self.method,
43
+ "at": self.at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
44
+ "lines": "".join(sorted(self.hashes)),
45
+ **({"note": self.note} if self.note else {}),
46
+ },
47
+ ensure_ascii=False,
48
+ )
49
+
50
+
51
+ def ledger_path(root: Path) -> Path:
52
+ return root / STATE_DIR / LEDGER_NAME
53
+
54
+
55
+ def parse_time(value: str) -> datetime:
56
+ try:
57
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
58
+ except ValueError:
59
+ return datetime.fromtimestamp(0, UTC)
60
+
61
+
62
+ def load_ledger(root: Path) -> list[Record]:
63
+ p = ledger_path(root)
64
+ if not p.exists():
65
+ return []
66
+ records: list[Record] = []
67
+ for raw in p.read_text(encoding="utf-8").splitlines():
68
+ raw = raw.strip()
69
+ if not raw or raw.startswith("#"):
70
+ continue
71
+ try:
72
+ d = json.loads(raw)
73
+ lines = d.get("lines", "")
74
+ hashes = frozenset(lines[i : i + 8] for i in range(0, len(lines), 8))
75
+ records.append(
76
+ Record(
77
+ path=d["path"],
78
+ who=d.get("who", "unknown"),
79
+ score=float(d.get("score", 0)),
80
+ method=d.get("method", "quiz"),
81
+ at=parse_time(d.get("at", "")),
82
+ hashes=hashes,
83
+ note=d.get("note", ""),
84
+ )
85
+ )
86
+ except (KeyError, ValueError, TypeError, json.JSONDecodeError):
87
+ continue # tolerate hand edits and merge debris
88
+ return records
89
+
90
+
91
+ def append_records(root: Path, records: list[Record]) -> Path:
92
+ p = ledger_path(root)
93
+ p.parent.mkdir(exist_ok=True)
94
+ with p.open("a", encoding="utf-8") as fh:
95
+ for rec in records:
96
+ fh.write(rec.to_json() + "\n")
97
+ return p
grokmap/prdiff.py ADDED
@@ -0,0 +1,144 @@
1
+ """Summarize the AI-written code a branch or pull request adds, and how much of it is understood."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from grokmap import gitutil
10
+ from grokmap.config import Config
11
+ from grokmap.ledger import load_ledger
12
+ from grokmap.scan import scan_repo
13
+ from grokmap.score import HUMAN, UNDERSTOOD, UNREAD, evaluate
14
+
15
+ MARKER = "<!-- grokmap:pr-summary -->"
16
+
17
+
18
+ @dataclass
19
+ class FileDelta:
20
+ path: str
21
+ ai: int = 0
22
+ human: int = 0
23
+ understood: int = 0
24
+ unread: int = 0
25
+ partial: int = 0 # skimmed or fading
26
+ tools: Counter = field(default_factory=Counter)
27
+
28
+
29
+ @dataclass
30
+ class PrDelta:
31
+ base: str
32
+ merge_base: str
33
+ commits: int
34
+ files: list[FileDelta]
35
+
36
+ @property
37
+ def ai(self) -> int:
38
+ return sum(f.ai for f in self.files)
39
+
40
+ @property
41
+ def human(self) -> int:
42
+ return sum(f.human for f in self.files)
43
+
44
+ @property
45
+ def understood(self) -> int:
46
+ return sum(f.understood for f in self.files)
47
+
48
+ @property
49
+ def unread(self) -> int:
50
+ return sum(f.unread for f in self.files)
51
+
52
+ @property
53
+ def tools(self) -> Counter:
54
+ c: Counter = Counter()
55
+ for f in self.files:
56
+ c.update(f.tools)
57
+ return c
58
+
59
+
60
+ def compute(root: Path, cfg: Config, base: str) -> PrDelta:
61
+ merge_base = gitutil.run_git(["merge-base", base, "HEAD"], root).strip()
62
+ branch_commits = set(gitutil.run_git(["rev-list", f"{merge_base}..HEAD"], root).split())
63
+ changed = set(
64
+ gitutil.run_git(["diff", "--name-only", "--diff-filter=AMR", "-z", f"{merge_base}..HEAD"], root).split("\0")
65
+ ) - {""}
66
+ changed = {p for p in changed if cfg.is_included(p)}
67
+ scan = scan_repo(root, cfg, only=changed)
68
+ result = evaluate(scan, load_ledger(root), cfg)
69
+ files = []
70
+ for path in sorted(changed):
71
+ fd = FileDelta(path)
72
+ for ls in result.line_states.get(path, []):
73
+ if ls.sha not in branch_commits:
74
+ continue # line predates the branch
75
+ if ls.state == HUMAN:
76
+ fd.human += 1
77
+ continue
78
+ fd.ai += 1
79
+ fd.tools[ls.tool] += 1
80
+ if ls.state == UNDERSTOOD:
81
+ fd.understood += 1
82
+ elif ls.state == UNREAD:
83
+ fd.unread += 1
84
+ else:
85
+ fd.partial += 1
86
+ if fd.ai or fd.human:
87
+ files.append(fd)
88
+ return PrDelta(base, merge_base, len(branch_commits), files)
89
+
90
+
91
+ def _s(n: int) -> str:
92
+ return "" if n == 1 else "s"
93
+
94
+
95
+ def render_markdown(d: PrDelta, top: int = 15) -> str:
96
+ out = [MARKER, "### grokmap: comprehension check", ""]
97
+ if not d.files:
98
+ out.append("This change adds no code lines that grokmap tracks.")
99
+ return "\n".join(out)
100
+ if not d.ai:
101
+ out.append(f"This change adds **{d.human:,}** line{_s(d.human)}, all written by people. No new comprehension debt.")
102
+ return "\n".join(out)
103
+ pct = 100 * d.understood / d.ai
104
+ tools = ", ".join(f"{k} {v:,}" for k, v in d.tools.most_common())
105
+ out.append(
106
+ f"This change adds **{d.ai:,} AI-written line{_s(d.ai)}** ({tools}) and {d.human:,} human-written line{_s(d.human)}. "
107
+ f"**{d.understood:,} of the AI lines ({pct:.0f}%)** have been understood by someone on the team."
108
+ )
109
+ out += ["", "| File | AI lines | Understood | Not checked |", "|---|---:|---:|---:|"]
110
+ ranked = sorted((f for f in d.files if f.ai), key=lambda f: (-f.unread, -f.ai))
111
+ for f in ranked[:top]:
112
+ out.append(f"| `{f.path}` | {f.ai:,} | {f.understood:,} | {f.unread:,} |")
113
+ if len(ranked) > top:
114
+ out.append(f"| _…and {len(ranked) - top} more files_ | | | |")
115
+ out += [""]
116
+ if d.unread:
117
+ out.append(
118
+ f"Before merging, the author can ask their coding agent to run `grokmap quiz --diff {d.base}` "
119
+ "for a 2-minute quiz on the unchecked lines."
120
+ )
121
+ else:
122
+ out.append("Every AI-written line in this change has been understood by someone. 🎉")
123
+ out.append("")
124
+ out.append(
125
+ "<sub>Measured by [grokmap](https://github.com/Aadithya-kl/grokmap) from commit trailers and the team's understanding ledger.</sub>"
126
+ )
127
+ return "\n".join(out)
128
+
129
+
130
+ def to_json(d: PrDelta) -> dict:
131
+ return {
132
+ "base": d.base,
133
+ "merge_base": d.merge_base,
134
+ "commits": d.commits,
135
+ "ai": d.ai,
136
+ "human": d.human,
137
+ "understood": d.understood,
138
+ "unread": d.unread,
139
+ "tools": dict(d.tools.most_common()),
140
+ "files": [
141
+ {"path": f.path, "ai": f.ai, "human": f.human, "understood": f.understood, "unread": f.unread, "partial": f.partial}
142
+ for f in d.files
143
+ ],
144
+ }