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/scan.py ADDED
@@ -0,0 +1,212 @@
1
+ """Walk the repository at HEAD and attribute every meaningful line to the commit that wrote it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+
13
+ from grokmap import gitutil
14
+ from grokmap.config import Config
15
+ from grokmap.detect import Detector
16
+
17
+ CACHE_VERSION = 2
18
+ STATE_DIR = ".grokmap"
19
+ _TRIVIAL = re.compile(r"^[\W_]{0,3}$")
20
+ _WS = re.compile(r"\s+")
21
+
22
+
23
+ def normalize(line: str) -> str:
24
+ return _WS.sub(" ", line.strip())
25
+
26
+
27
+ def is_meaningful(norm: str) -> bool:
28
+ """Skip blank lines and lone punctuation such as `}` or `});` — nothing to understand there."""
29
+ return bool(norm) and not _TRIVIAL.match(norm)
30
+
31
+
32
+ def line_hash(norm: str) -> str:
33
+ return hashlib.sha1(norm.encode("utf-8", "replace")).hexdigest()[:8]
34
+
35
+
36
+ @dataclass
37
+ class Line:
38
+ lineno: int
39
+ sha: str
40
+ h: str
41
+
42
+
43
+ @dataclass
44
+ class FileScan:
45
+ path: str
46
+ lines: list[Line]
47
+
48
+
49
+ @dataclass
50
+ class CommitMeta:
51
+ sha: str
52
+ tool: str | None
53
+ author: str
54
+ email: str
55
+ time: int
56
+ summary: str
57
+
58
+
59
+ @dataclass
60
+ class Scan:
61
+ root: Path
62
+ head: str | None
63
+ files: dict[str, FileScan] = field(default_factory=dict)
64
+ commits: dict[str, CommitMeta] = field(default_factory=dict)
65
+ skipped: list[str] = field(default_factory=list)
66
+
67
+
68
+ def parse_blame(porcelain: str) -> list[tuple[int, str, str]]:
69
+ """Return (final_lineno, sha, content) for each line of `git blame --line-porcelain` output."""
70
+ out: list[tuple[int, str, str]] = []
71
+ sha = ""
72
+ lineno = 0
73
+ expect_header = True
74
+ for raw in porcelain.split("\n"):
75
+ if raw.startswith("\t"):
76
+ out.append((lineno, sha, raw[1:]))
77
+ expect_header = True
78
+ continue
79
+ if expect_header and raw:
80
+ parts = raw.split(" ")
81
+ if len(parts) >= 3 and len(parts[0]) >= 40:
82
+ sha = parts[0]
83
+ try:
84
+ lineno = int(parts[2])
85
+ except ValueError:
86
+ lineno = 0
87
+ expect_header = False
88
+ return out
89
+
90
+
91
+ def _cache_path(root: Path) -> Path:
92
+ return root / STATE_DIR / "cache.json"
93
+
94
+
95
+ def _load_cache(root: Path) -> dict:
96
+ p = _cache_path(root)
97
+ if not p.exists():
98
+ return {"version": CACHE_VERSION, "blame": {}, "commits": {}}
99
+ try:
100
+ data = json.loads(p.read_text(encoding="utf-8"))
101
+ if data.get("version") == CACHE_VERSION:
102
+ return data
103
+ except (OSError, json.JSONDecodeError):
104
+ pass
105
+ return {"version": CACHE_VERSION, "blame": {}, "commits": {}}
106
+
107
+
108
+ def _save_cache(root: Path, data: dict) -> None:
109
+ state = root / STATE_DIR
110
+ try:
111
+ state.mkdir(exist_ok=True)
112
+ gi = state / ".gitignore"
113
+ if not gi.exists():
114
+ gi.write_text("# local cache, safe to delete\ncache.json\n", encoding="utf-8")
115
+ tmp = _cache_path(root).with_suffix(".tmp")
116
+ tmp.write_text(json.dumps(data, separators=(",", ":")), encoding="utf-8")
117
+ os.replace(tmp, _cache_path(root))
118
+ except OSError:
119
+ pass # read-only checkout: caching is best-effort
120
+
121
+
122
+ def text_files_at_head(root: Path) -> set[str]:
123
+ out = gitutil.run_git(["grep", "-I", "-l", "-z", "-e", "", "HEAD", "--"], root, check=False)
124
+ files = set()
125
+ for item in out.split("\0"):
126
+ if item.startswith("HEAD:"):
127
+ files.add(item[5:])
128
+ return files
129
+
130
+
131
+ def scan_repo(root: Path, cfg: Config, use_cache: bool = True, progress=None, only: set[str] | None = None) -> Scan:
132
+ """Blame every included text file at HEAD (or just the paths in `only`)."""
133
+ head = gitutil.head_sha(root)
134
+ scan = Scan(root=root, head=head)
135
+ if head is None:
136
+ return scan
137
+
138
+ cache = _load_cache(root) if use_cache else {"version": CACHE_VERSION, "blame": {}, "commits": {}}
139
+ blame_cache: dict = cache["blame"]
140
+ text_files = text_files_at_head(root)
141
+
142
+ todo = []
143
+ for tf in gitutil.tracked_files(root):
144
+ if not cfg.is_included(tf.path) or (only is not None and tf.path not in only):
145
+ continue
146
+ if tf.path not in text_files:
147
+ scan.skipped.append(tf.path)
148
+ continue
149
+ todo.append(tf)
150
+
151
+ def work(tf: gitutil.TrackedFile):
152
+ cached = blame_cache.get(tf.path)
153
+ if cached and cached.get("blob") == tf.blob:
154
+ return tf, cached["lines"], True
155
+ try:
156
+ porcelain = gitutil.blame_porcelain(root, tf.path)
157
+ except gitutil.GitError:
158
+ return tf, None, False
159
+ rows = parse_blame(porcelain)
160
+ if len(rows) > cfg.max_file_lines:
161
+ return tf, None, False
162
+ lines = []
163
+ for lineno, sha, content in rows:
164
+ norm = normalize(content)
165
+ if is_meaningful(norm):
166
+ lines.append([lineno, sha, line_hash(norm)])
167
+ return tf, lines, False
168
+
169
+ workers = max(2, min(8, (os.cpu_count() or 4)))
170
+ new_blame: dict = {}
171
+ done = 0
172
+ with ThreadPoolExecutor(max_workers=workers) as pool:
173
+ for tf, lines, _hit in pool.map(work, todo):
174
+ done += 1
175
+ if progress:
176
+ progress(done, len(todo))
177
+ if lines is None:
178
+ scan.skipped.append(tf.path)
179
+ continue
180
+ new_blame[tf.path] = {"blob": tf.blob, "lines": lines}
181
+ if lines:
182
+ scan.files[tf.path] = FileScan(tf.path, [Line(row[0], row[1], row[2]) for row in lines])
183
+
184
+ # commit metadata (cached raw, AI detection re-run every time so config changes apply)
185
+ shas = sorted({ln.sha for f in scan.files.values() for ln in f.lines})
186
+ commit_cache: dict = cache["commits"]
187
+ missing = [s for s in shas if s not in commit_cache]
188
+ for i in range(0, len(missing), 500):
189
+ infos = gitutil.commit_infos(root, missing[i : i + 500])
190
+ for sha, info in infos.items():
191
+ commit_cache[sha] = [info.author_name, info.author_email, info.time, info.message[:6000]]
192
+ detector = Detector.build(cfg.ai_patterns, cfg.ai_commits)
193
+ for sha in shas:
194
+ raw = commit_cache.get(sha)
195
+ if raw is None:
196
+ # uncommitted or unknown: treat as human so we never over-claim AI authorship
197
+ scan.commits[sha] = CommitMeta(sha, None, "unknown", "", 0, "")
198
+ continue
199
+ info = gitutil.CommitInfo(sha, raw[0], raw[1], raw[2], raw[3])
200
+ summary = raw[3].strip().splitlines()[0] if raw[3].strip() else ""
201
+ scan.commits[sha] = CommitMeta(sha, detector.tool_for(info), raw[0], raw[1], raw[2], summary[:120])
202
+
203
+ if use_cache:
204
+ keep_commits = {s: commit_cache[s] for s in shas if s in commit_cache}
205
+ if only is not None:
206
+ # partial scan: keep everything else we already knew
207
+ blame = {**blame_cache, **new_blame}
208
+ keep_commits = {**cache["commits"], **keep_commits}
209
+ else:
210
+ blame = new_blame
211
+ _save_cache(root, {"version": CACHE_VERSION, "blame": blame, "commits": keep_commits})
212
+ return scan
grokmap/score.py ADDED
@@ -0,0 +1,158 @@
1
+ """Combine the blame scan with the ledger into per-line states and debt scores."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter, defaultdict
6
+ from dataclasses import dataclass, field
7
+ from datetime import UTC, datetime, timedelta
8
+
9
+ from grokmap.config import Config
10
+ from grokmap.ledger import Record
11
+ from grokmap.scan import Scan
12
+
13
+ HUMAN, UNDERSTOOD, FADING, SKIMMED, UNREAD = "human", "understood", "fading", "skimmed", "unread"
14
+ AI_STATES = (UNDERSTOOD, FADING, SKIMMED, UNREAD)
15
+ # how much each state of AI-written code counts toward comprehension debt
16
+ DEBT_WEIGHT = {HUMAN: 0.0, UNDERSTOOD: 0.0, FADING: 0.5, SKIMMED: 0.5, UNREAD: 1.0}
17
+ _RANK = {UNREAD: 0, SKIMMED: 1, FADING: 2, UNDERSTOOD: 3}
18
+
19
+
20
+ @dataclass
21
+ class Stats:
22
+ lines: int = 0
23
+ human: int = 0
24
+ understood: int = 0
25
+ fading: int = 0
26
+ skimmed: int = 0
27
+ unread: int = 0
28
+ debt: float = 0.0
29
+ tools: Counter = field(default_factory=Counter)
30
+ people: Counter = field(default_factory=Counter)
31
+
32
+ @property
33
+ def ai(self) -> int:
34
+ return self.understood + self.fading + self.skimmed + self.unread
35
+
36
+ @property
37
+ def debt_pct(self) -> float:
38
+ return 100.0 * self.debt / self.lines if self.lines else 0.0
39
+
40
+ @property
41
+ def ai_pct(self) -> float:
42
+ return 100.0 * self.ai / self.lines if self.lines else 0.0
43
+
44
+ @property
45
+ def understood_pct_of_ai(self) -> float:
46
+ return 100.0 * self.understood / self.ai if self.ai else 100.0
47
+
48
+ def add(self, other: Stats) -> None:
49
+ for k in ("lines", "human", "understood", "fading", "skimmed", "unread"):
50
+ setattr(self, k, getattr(self, k) + getattr(other, k))
51
+ self.debt += other.debt
52
+ self.tools.update(other.tools)
53
+ self.people.update(other.people)
54
+
55
+ def to_dict(self) -> dict:
56
+ return {
57
+ "lines": self.lines,
58
+ "human": self.human,
59
+ "ai": self.ai,
60
+ "understood": self.understood,
61
+ "fading": self.fading,
62
+ "skimmed": self.skimmed,
63
+ "unread": self.unread,
64
+ "debt_lines": round(self.debt, 1),
65
+ "debt_pct": round(self.debt_pct, 1),
66
+ "ai_pct": round(self.ai_pct, 1),
67
+ "tools": dict(self.tools.most_common()),
68
+ "people": dict(self.people.most_common()),
69
+ }
70
+
71
+
72
+ @dataclass
73
+ class LineState:
74
+ lineno: int
75
+ state: str
76
+ tool: str | None
77
+ sha: str
78
+
79
+
80
+ @dataclass
81
+ class Result:
82
+ files: dict[str, Stats]
83
+ line_states: dict[str, list[LineState]]
84
+ total: Stats
85
+ by_dir: dict[str, Stats]
86
+ critical: Stats
87
+ critical_files: list[str]
88
+
89
+
90
+ def _record_state(rec: Record, cfg: Config, now: datetime) -> str:
91
+ if rec.method == "review" or rec.score < cfg.pass_score:
92
+ return SKIMMED
93
+ if cfg.decay_days > 0 and now - rec.at > timedelta(days=cfg.decay_days):
94
+ return FADING
95
+ return UNDERSTOOD
96
+
97
+
98
+ def evaluate(scan: Scan, records: list[Record], cfg: Config, now: datetime | None = None) -> Result:
99
+ now = now or datetime.now(UTC)
100
+ by_path: dict[str, list[tuple[str, Record]]] = defaultdict(list)
101
+ for rec in records:
102
+ by_path[rec.path].append((_record_state(rec, cfg, now), rec))
103
+
104
+ files: dict[str, Stats] = {}
105
+ line_states: dict[str, list[LineState]] = {}
106
+ for path, fs in scan.files.items():
107
+ st = Stats()
108
+ states: list[LineState] = []
109
+ recs = by_path.get(path, [])
110
+ for ln in fs.lines:
111
+ meta = scan.commits.get(ln.sha)
112
+ tool = meta.tool if meta else None
113
+ st.lines += 1
114
+ if tool is None:
115
+ state = HUMAN
116
+ st.human += 1
117
+ else:
118
+ st.tools[tool] += 1
119
+ state = UNREAD
120
+ best = -1
121
+ knowers: set[str] = set()
122
+ for rstate, rec in recs:
123
+ if ln.h in rec.hashes:
124
+ if rstate in (UNDERSTOOD, FADING):
125
+ knowers.add(rec.who)
126
+ if _RANK[rstate] > best:
127
+ best, state = _RANK[rstate], rstate
128
+ st.people.update(knowers)
129
+ setattr(st, state, getattr(st, state) + 1)
130
+ st.debt += DEBT_WEIGHT[state]
131
+ states.append(LineState(ln.lineno, state, tool, ln.sha))
132
+ files[path] = st
133
+ line_states[path] = states
134
+
135
+ total = Stats()
136
+ by_dir: dict[str, Stats] = defaultdict(Stats)
137
+ critical = Stats()
138
+ critical_files = []
139
+ for path, st in files.items():
140
+ total.add(st)
141
+ parts = path.split("/")
142
+ for i in range(1, len(parts)):
143
+ by_dir["/".join(parts[:i])].add(st)
144
+ if cfg.is_critical(path):
145
+ critical.add(st)
146
+ critical_files.append(path)
147
+ return Result(files, line_states, total, dict(by_dir), critical, sorted(critical_files))
148
+
149
+
150
+ def ranges(numbers: list[int]) -> list[tuple[int, int]]:
151
+ """Collapse sorted line numbers into inclusive ranges, bridging gaps of up to 2 lines."""
152
+ out: list[tuple[int, int]] = []
153
+ for n in sorted(numbers):
154
+ if out and n - out[-1][1] <= 3:
155
+ out[-1] = (out[-1][0], n)
156
+ else:
157
+ out.append((n, n))
158
+ return out
grokmap/trend.py ADDED
@@ -0,0 +1,151 @@
1
+ """How much of the code added over time was written by AI agents (from `git log --numstat`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import Counter
7
+ from dataclasses import dataclass, field
8
+ from datetime import UTC, date, datetime, timedelta
9
+ from pathlib import Path
10
+
11
+ from grokmap import gitutil
12
+ from grokmap.config import Config
13
+ from grokmap.detect import Detector
14
+
15
+ _BRACE_RENAME = re.compile(r"\{([^{}]*) => ([^{}]*)\}")
16
+
17
+
18
+ def renamed_path(path: str) -> str:
19
+ """numstat shows renames as `src/{old => new}/f.py` or `old.py => new.py`; keep the new path."""
20
+ if "=>" not in path:
21
+ return path
22
+ if "{" in path:
23
+ return re.sub(r"//+", "/", _BRACE_RENAME.sub(lambda m: m.group(2), path))
24
+ return path.split(" => ", 1)[1]
25
+
26
+
27
+ @dataclass
28
+ class Bucket:
29
+ start: date
30
+ human: int = 0
31
+ tools: Counter = field(default_factory=Counter)
32
+
33
+ @property
34
+ def ai(self) -> int:
35
+ return sum(self.tools.values())
36
+
37
+ @property
38
+ def total(self) -> int:
39
+ return self.human + self.ai
40
+
41
+
42
+ def bucket_start(d: date, by: str) -> date:
43
+ if by == "month":
44
+ return d.replace(day=1)
45
+ return d - timedelta(days=d.weekday()) # Monday
46
+
47
+
48
+ def _next(d: date, by: str) -> date:
49
+ if by == "month":
50
+ return date(d.year + (d.month == 12), d.month % 12 + 1, 1)
51
+ return d + timedelta(days=7)
52
+
53
+
54
+ def collect(root: Path, cfg: Config, by: str = "auto", since: str | None = None) -> tuple[str, list[Bucket]]:
55
+ """Lines added per period, split into human and per-agent. Merge commits are skipped."""
56
+ fmt = "%x1e%H%x00%an%x00%ae%x00%ct%x00%B%x1f"
57
+ args = ["log", "--no-merges", "--numstat", "-M", f"--format={fmt}", "HEAD"]
58
+ if since:
59
+ args.append(f"--since={since}")
60
+ if gitutil.head_sha(root) is None:
61
+ return "week", []
62
+ out = gitutil.run_git(args, root)
63
+ detector = Detector.build(cfg.ai_patterns, cfg.ai_commits)
64
+
65
+ rows: list[tuple[date, str | None, int]] = []
66
+ for record in out.split("\x1e"):
67
+ if not record.strip():
68
+ continue
69
+ head, _, stats = record.partition("\x1f")
70
+ parts = head.split("\x00")
71
+ if len(parts) < 5:
72
+ continue
73
+ sha, name, email, ts, message = parts[0], parts[1], parts[2], parts[3], "\x00".join(parts[4:])
74
+ try:
75
+ when = datetime.fromtimestamp(int(ts), UTC).date()
76
+ except ValueError:
77
+ continue
78
+ tool = detector.tool_for(gitutil.CommitInfo(sha, name, email, int(ts), message))
79
+ added = 0
80
+ for line in stats.strip().splitlines():
81
+ cols = line.split("\t")
82
+ if len(cols) != 3 or cols[0] == "-":
83
+ continue # binary files
84
+ if cfg.is_included(renamed_path(cols[2])):
85
+ added += int(cols[0])
86
+ if added:
87
+ rows.append((when, tool, added))
88
+
89
+ if not rows:
90
+ return ("week" if by == "auto" else by), []
91
+ first, last = min(r[0] for r in rows), max(r[0] for r in rows)
92
+ if by == "auto":
93
+ by = "week" if (last - first).days <= 26 * 7 else "month"
94
+
95
+ buckets: dict[date, Bucket] = {}
96
+ cur = bucket_start(first, by)
97
+ while cur <= last:
98
+ buckets[cur] = Bucket(cur)
99
+ cur = _next(cur, by)
100
+ for when, tool, added in rows:
101
+ b = buckets[bucket_start(when, by)]
102
+ if tool:
103
+ b.tools[tool] += added
104
+ else:
105
+ b.human += added
106
+ return by, [buckets[k] for k in sorted(buckets)]
107
+
108
+
109
+ def summarize(buckets: list[Bucket]) -> dict:
110
+ tools: Counter = Counter()
111
+ human = 0
112
+ for b in buckets:
113
+ tools.update(b.tools)
114
+ human += b.human
115
+ ai = sum(tools.values())
116
+ return {
117
+ "human": human,
118
+ "ai": ai,
119
+ "tools": dict(tools.most_common()),
120
+ "ai_pct": round(100 * ai / (ai + human), 1) if ai + human else 0.0,
121
+ }
122
+
123
+
124
+ def to_json(by: str, buckets: list[Bucket]) -> dict:
125
+ return {
126
+ "by": by,
127
+ "summary": summarize(buckets),
128
+ "periods": [{"start": b.start.isoformat(), "human": b.human, "tools": dict(b.tools)} for b in buckets],
129
+ }
130
+
131
+
132
+ def render_text(by: str, buckets: list[Bucket], width: int = 40) -> str:
133
+ if not buckets:
134
+ return "grokmap trend: no commits with added lines in range."
135
+ s = summarize(buckets)
136
+ peak = max(b.total for b in buckets) or 1
137
+ label = "Week of" if by == "week" else "Month"
138
+ lines = [
139
+ f"Lines added per {by}: {s['ai']:,} by AI ({s['ai_pct']:.0f}%), {s['human']:,} by people",
140
+ "",
141
+ f"{label:<11} {'AI %':>5} {'added':>7} █ AI ░ people",
142
+ ]
143
+ for b in buckets:
144
+ n_ai = round(width * b.ai / peak)
145
+ n_h = round(width * b.human / peak)
146
+ pct = f"{100 * b.ai / b.total:.0f}%" if b.total else "–"
147
+ stamp = b.start.isoformat() if by == "week" else b.start.strftime("%Y-%m")
148
+ lines.append(f"{stamp:<11} {pct:>5} {b.total:>7,} {'█' * n_ai}{'░' * n_h}")
149
+ if s["tools"]:
150
+ lines += ["", "By agent: " + ", ".join(f"{k} {v:,}" for k, v in s["tools"].items())]
151
+ return "\n".join(lines)