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/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """grokmap: measure comprehension debt — the AI-written code nobody on the team understands."""
2
+
3
+ __version__ = "0.2.0"
grokmap/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from grokmap.cli import main
2
+
3
+ raise SystemExit(main())
grokmap/badge.py ADDED
@@ -0,0 +1,42 @@
1
+ """A shields-style SVG badge: `comprehension debt | 23%`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from xml.sax.saxutils import escape
6
+
7
+
8
+ def badge_color(debt_pct: float, ai_lines: int) -> str:
9
+ if ai_lines == 0:
10
+ return "#6b7280"
11
+ if debt_pct < 10:
12
+ return "#0a8f1e"
13
+ if debt_pct < 25:
14
+ return "#7a9a01"
15
+ if debt_pct < 50:
16
+ return "#c77c02"
17
+ return "#c62828"
18
+
19
+
20
+ def _width(text: str) -> int:
21
+ # approximate Verdana 11px advance widths, good enough for a badge
22
+ wide = sum(1 for c in text if c in "mwMW%@")
23
+ narrow = sum(1 for c in text if c in "il.,:;|!' ")
24
+ return int(6.6 * (len(text) - wide - narrow) + 9.5 * wide + 3.6 * narrow) + 12
25
+
26
+
27
+ def render_badge(debt_pct: float, ai_lines: int, label: str = "comprehension debt") -> str:
28
+ value = "no AI code" if ai_lines == 0 else f"{debt_pct:.0f}%"
29
+ color = badge_color(debt_pct, ai_lines)
30
+ lw, vw = _width(label), _width(value)
31
+ total = lw + vw
32
+ lab, val = escape(label), escape(value)
33
+ return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{total}" height="20" role="img" aria-label="{lab}: {val}">
34
+ <title>{lab}: {val}</title>
35
+ <linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>
36
+ <clipPath id="r"><rect width="{total}" height="20" rx="3" fill="#fff"/></clipPath>
37
+ <g clip-path="url(#r)"><rect width="{lw}" height="20" fill="#555"/><rect x="{lw}" width="{vw}" height="20" fill="{color}"/><rect width="{total}" height="20" fill="url(#s)"/></g>
38
+ <g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
39
+ <text x="{lw / 2:.1f}" y="15" fill="#010101" fill-opacity=".3">{lab}</text><text x="{lw / 2:.1f}" y="14">{lab}</text>
40
+ <text x="{lw + vw / 2:.1f}" y="15" fill="#010101" fill-opacity=".3">{val}</text><text x="{lw + vw / 2:.1f}" y="14">{val}</text>
41
+ </g></svg>
42
+ """
grokmap/cli.py ADDED
@@ -0,0 +1,397 @@
1
+ """grokmap command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import webbrowser
9
+ from pathlib import Path
10
+
11
+ from grokmap import __version__, gitutil, prdiff, trend
12
+ from grokmap.badge import render_badge
13
+ from grokmap.config import DEFAULT_TOML, load_config
14
+ from grokmap.ledger import METHODS, ledger_path, load_ledger
15
+ from grokmap.quiz import build_targets, mark, render_json, render_markdown, truncate
16
+ from grokmap.report import render_report, write_report
17
+ from grokmap.scan import scan_repo
18
+ from grokmap.score import evaluate
19
+
20
+ ROW = "{:<52} {:>7} {:>7} {:>7} {:>7}"
21
+
22
+
23
+ def _use_color() -> bool:
24
+ return sys.stdout.isatty()
25
+
26
+
27
+ def _c(text: str, code: str) -> str:
28
+ return f"\033[{code}m{text}\033[0m" if _use_color() else text
29
+
30
+
31
+ def _progress(done: int, total: int) -> None:
32
+ if sys.stderr.isatty() and total > 50:
33
+ sys.stderr.write(f"\rgrokmap: blaming files {done}/{total}")
34
+ if done == total:
35
+ sys.stderr.write("\r" + " " * 40 + "\r")
36
+ sys.stderr.flush()
37
+
38
+
39
+ def _context(args):
40
+ root = gitutil.repo_root(Path(args.repo).resolve())
41
+ cfg = load_config(root)
42
+ return root, cfg
43
+
44
+
45
+ def _analyze(root, cfg, no_cache=False):
46
+ scan = scan_repo(root, cfg, use_cache=not no_cache, progress=_progress)
47
+ result = evaluate(scan, load_ledger(root), cfg)
48
+ return scan, result
49
+
50
+
51
+ def _debt_label(pct: float, ai: int) -> str:
52
+ if ai == 0:
53
+ return _c("no AI code", "2")
54
+ code = "32" if pct < 10 else "33" if pct < 35 else "31"
55
+ return _c(f"{pct:.1f}%", code)
56
+
57
+
58
+ def cmd_status(args) -> int:
59
+ root, cfg = _context(args)
60
+ scan, res = _analyze(root, cfg, args.no_cache)
61
+ if args.json:
62
+ out = {
63
+ "repo": root.name,
64
+ "head": scan.head,
65
+ "total": res.total.to_dict(),
66
+ "critical": res.critical.to_dict() if res.critical_files else None,
67
+ "files": {p: s.to_dict() for p, s in sorted(res.files.items())},
68
+ }
69
+ print(json.dumps(out, indent=2))
70
+ return 0
71
+ if args.markdown:
72
+ print(_markdown_summary(root.name, scan.head, res, args.top))
73
+ return 0
74
+ t = res.total
75
+ if scan.head is None:
76
+ print("grokmap: this repository has no commits yet.")
77
+ return 0
78
+ print(f"{_c('grokmap', '1')} · {root.name} @ {scan.head[:10]}")
79
+ print()
80
+ print(f" Comprehension debt {_debt_label(t.debt_pct, t.ai)}")
81
+ print(f" Lines scanned {t.lines:,} in {len(res.files):,} files")
82
+ print(
83
+ f" Written by AI {t.ai:,} lines ({t.ai_pct:.1f}%)"
84
+ + (f" — {', '.join(f'{k} {v:,}' for k, v in t.tools.most_common())}" if t.tools else "")
85
+ )
86
+ if t.ai:
87
+ print(f" understood {t.understood:,} ({100 * t.understood / t.ai:.0f}%)")
88
+ print(f" fading {t.fading:,}")
89
+ print(f" skimmed {t.skimmed:,}")
90
+ print(f" nobody checked {t.unread:,}")
91
+ if res.critical_files:
92
+ c = res.critical
93
+ print(f" Critical paths {_debt_label(c.debt_pct, c.ai)} debt over {c.lines:,} lines")
94
+ if t.people:
95
+ print(f" Understood by {', '.join(f'{p} ({n:,})' for p, n in t.people.most_common(5))}")
96
+ risky = sorted(((p, s) for p, s in res.files.items() if s.debt > 0), key=lambda x: -x[1].debt)[: args.top]
97
+ if risky:
98
+ print()
99
+ print(_c(ROW.format("Riskiest files", "lines", "AI", "unread", "debt"), "1"))
100
+ for p, s in risky:
101
+ name = p if len(p) <= 52 else "…" + p[-51:]
102
+ print(ROW.format(name, s.lines, s.ai, s.unread, f"{s.debt_pct:.0f}%"))
103
+ print()
104
+ print("Pay it down: ask your coding agent to run `grokmap quiz <file>` and quiz you.")
105
+ elif t.ai:
106
+ print()
107
+ print("Every AI-written line has been understood by someone. Nice.")
108
+ return 0
109
+
110
+
111
+ def _markdown_summary(name, head, res, top: int) -> str:
112
+ t = res.total
113
+ lines = [f"### grokmap · {name} @ `{(head or '')[:10]}`", ""]
114
+ if not t.ai:
115
+ lines.append("No AI-written code detected. Comprehension debt: **0%**.")
116
+ return "\n".join(lines)
117
+ lines += [
118
+ "| | |",
119
+ "|---|---|",
120
+ f"| Comprehension debt | **{t.debt_pct:.1f}%** |",
121
+ f"| Written by AI | {t.ai:,} of {t.lines:,} lines ({t.ai_pct:.1f}%) |",
122
+ f"| AI code understood | {t.understood:,} lines ({t.understood_pct_of_ai:.0f}%) |",
123
+ f"| Nobody has checked | {t.unread:,} lines |",
124
+ ]
125
+ if res.critical_files:
126
+ lines.append(f"| Debt on critical paths | {res.critical.debt_pct:.1f}% |")
127
+ if t.tools:
128
+ lines.append(f"| Agents | {', '.join(f'{k} ({v:,})' for k, v in t.tools.most_common())} |")
129
+ risky = sorted(((p, s) for p, s in res.files.items() if s.debt > 0), key=lambda x: -x[1].debt)[:top]
130
+ if risky:
131
+ lines += ["", "**Riskiest files**", "", "| File | AI lines | Unread | Debt |", "|---|---:|---:|---:|"]
132
+ lines += [f"| `{p}` | {s.ai:,} | {s.unread:,} | {s.debt_pct:.0f}% |" for p, s in risky]
133
+ return "\n".join(lines)
134
+
135
+
136
+ def cmd_report(args) -> int:
137
+ root, cfg = _context(args)
138
+ scan, res = _analyze(root, cfg, args.no_cache)
139
+ out = Path(args.output) if args.output else root / "grokmap-report.html"
140
+ by, buckets = trend.collect(root, cfg)
141
+ write_report(out, render_report(scan, res, args.name or root.name, trend.to_json(by, buckets), args.note))
142
+ print(f"grokmap: wrote {out}")
143
+ if args.open:
144
+ webbrowser.open(out.resolve().as_uri())
145
+ return 0
146
+
147
+
148
+ def cmd_trend(args) -> int:
149
+ root, cfg = _context(args)
150
+ by, buckets = trend.collect(root, cfg, args.by, args.since)
151
+ if args.json:
152
+ print(json.dumps(trend.to_json(by, buckets), indent=2))
153
+ else:
154
+ print(trend.render_text(by, buckets))
155
+ return 0
156
+
157
+
158
+ def cmd_diff(args) -> int:
159
+ root, cfg = _context(args)
160
+ try:
161
+ delta = prdiff.compute(root, cfg, args.base)
162
+ except gitutil.GitError:
163
+ print(f"grokmap diff: can't compare with '{args.base}'. Fetch it first (e.g. git fetch origin main).", file=sys.stderr)
164
+ return 2
165
+ if args.json:
166
+ print(json.dumps(prdiff.to_json(delta), indent=2))
167
+ elif args.markdown:
168
+ print(prdiff.render_markdown(delta))
169
+ else:
170
+ if not delta.ai:
171
+ print(f"grokmap diff vs {args.base}: {delta.human:,} lines added, none by AI.")
172
+ else:
173
+ print(
174
+ f"grokmap diff vs {args.base}: {delta.ai:,} AI-written lines added "
175
+ f"({', '.join(f'{k} {v:,}' for k, v in delta.tools.most_common())}), "
176
+ f"{delta.understood:,} understood, {delta.unread:,} nobody has checked."
177
+ )
178
+ for f in sorted(delta.files, key=lambda f: -f.unread):
179
+ if f.ai:
180
+ print(f" {f.path}: {f.ai} AI lines, {f.unread} unchecked")
181
+ if delta.unread:
182
+ print(f"Quiz yourself: grokmap quiz --diff {args.base}")
183
+ if args.max_unread is not None and delta.unread > args.max_unread:
184
+ return 1
185
+ return 0
186
+
187
+
188
+ def cmd_badge(args) -> int:
189
+ root, cfg = _context(args)
190
+ _, res = _analyze(root, cfg, args.no_cache)
191
+ svg = render_badge(res.total.debt_pct, res.total.ai, args.label)
192
+ out = Path(args.output) if args.output else root / "grokmap-badge.svg"
193
+ out.write_text(svg, encoding="utf-8")
194
+ print(f"grokmap: wrote {out} ({res.total.debt_pct:.0f}% comprehension debt)")
195
+ return 0
196
+
197
+
198
+ def cmd_check(args) -> int:
199
+ root, cfg = _context(args)
200
+ _, res = _analyze(root, cfg, args.no_cache)
201
+ limit = args.max_debt if args.max_debt is not None else cfg.max_debt
202
+ stats = res.critical if args.critical else res.total
203
+ scope = "critical paths" if args.critical else "repository"
204
+ if args.critical and not res.critical_files:
205
+ print("grokmap check: no critical paths configured (set `critical = [...]` in .grokmap.toml); skipping.")
206
+ return 0
207
+ ok = stats.debt_pct <= limit
208
+ verdict = _c("PASS", "32") if ok else _c("FAIL", "31")
209
+ print(f"grokmap check {verdict}: {scope} comprehension debt {stats.debt_pct:.1f}% (limit {limit:.0f}%)")
210
+ if not ok:
211
+ files = res.critical_files if args.critical else list(res.files)
212
+ worst = sorted(files, key=lambda p: -res.files[p].debt)[:5]
213
+ print("Biggest contributors:")
214
+ for p in worst:
215
+ s = res.files[p]
216
+ if s.debt > 0:
217
+ print(f" {p}: {s.unread} unread AI lines, {s.debt_pct:.0f}% debt")
218
+ print("Run `grokmap quiz <file>` with your coding agent to bring it down.")
219
+ return 0 if ok else 1
220
+
221
+
222
+ def cmd_quiz(args) -> int:
223
+ root, cfg = _context(args)
224
+ who = args.who or gitutil.current_user(root)
225
+ diff_mode = bool(args.diff or args.staged or args.uncommitted)
226
+ scan = None if diff_mode else scan_repo(root, cfg, progress=_progress)
227
+ base = args.diff if args.diff and args.diff != "WORKTREE" else None
228
+ paths = [p.replace("\\", "/").removeprefix("./") for p in args.paths]
229
+ targets = build_targets(root, cfg, who, scan, paths, base, args.staged, diff_mode, include_human=args.include_human)
230
+ targets, cut = truncate(targets, args.max_lines)
231
+ print(render_json(targets, who, cut) if args.format == "json" else render_markdown(targets, who, cut, args.questions))
232
+ return 0
233
+
234
+
235
+ def cmd_mark(args) -> int:
236
+ root, cfg = _context(args)
237
+ who = args.who or gitutil.current_user(root)
238
+ try:
239
+ recs = mark(root, cfg, args.paths, args.score, args.method, who, args.lines, args.note or "")
240
+ except (ValueError, FileNotFoundError) as exc:
241
+ print(f"grokmap mark: {exc}", file=sys.stderr)
242
+ return 2
243
+ if not recs:
244
+ print("grokmap mark: nothing to record (no meaningful lines in those files).")
245
+ return 1
246
+ n = sum(len(r.hashes) for r in recs)
247
+ state = "understood" if args.method != "review" and recs[0].score >= cfg.pass_score else "skimmed"
248
+ print(f"grokmap: recorded {who} — {args.method}, score {recs[0].score:.2f} ({state}) — {n} lines in {len(recs)} file(s)")
249
+ print(f" ledger: {ledger_path(root).relative_to(root)} (commit it so your team shares it)")
250
+ return 0
251
+
252
+
253
+ def cmd_who(args) -> int:
254
+ root, cfg = _context(args)
255
+ scan, res = _analyze(root, cfg)
256
+ path = args.path.replace("\\", "/").removeprefix("./").rstrip("/")
257
+ matches = [p for p in res.files if p == path or p.startswith(path + "/")]
258
+ if not matches:
259
+ print(f"grokmap who: no scanned files under {path}")
260
+ return 1
261
+ from grokmap.score import Stats
262
+
263
+ agg = Stats()
264
+ for p in matches:
265
+ agg.add(res.files[p])
266
+ print(f"{path}: {agg.lines:,} lines, {agg.ai:,} written by AI, debt {agg.debt_pct:.1f}%")
267
+ if agg.people:
268
+ for person, n in agg.people.most_common():
269
+ print(f" {person}: understands {n:,} of {agg.ai:,} AI lines ({100 * n / max(agg.ai, 1):.0f}%)")
270
+ else:
271
+ print(" Nobody has shown they understand the AI-written code here yet.")
272
+ return 0
273
+
274
+
275
+ def cmd_init(args) -> int:
276
+ root = gitutil.repo_root(Path(args.repo).resolve())
277
+ cfg_path = root / ".grokmap.toml"
278
+ if not cfg_path.exists():
279
+ cfg_path.write_text(DEFAULT_TOML, encoding="utf-8")
280
+ print(f"grokmap: wrote {cfg_path.name}")
281
+ else:
282
+ print(f"grokmap: {cfg_path.name} already exists, left it alone")
283
+ state = root / ".grokmap"
284
+ state.mkdir(exist_ok=True)
285
+ (state / ".gitignore").write_text("# local cache, safe to delete\ncache.json\n", encoding="utf-8")
286
+ ledger = ledger_path(root)
287
+ if not ledger.exists():
288
+ ledger.write_text("", encoding="utf-8")
289
+ ga = root / ".gitattributes"
290
+ line = ".grokmap/ledger.jsonl merge=union"
291
+ existing = ga.read_text(encoding="utf-8") if ga.exists() else ""
292
+ if line not in existing:
293
+ ga.write_text(existing + ("" if existing.endswith("\n") or not existing else "\n") + line + "\n", encoding="utf-8")
294
+ print("grokmap: added union merge for the ledger to .gitattributes")
295
+ print("grokmap: ready. Next: `grokmap status`, then install the agent skill (see README).")
296
+ return 0
297
+
298
+
299
+ def build_parser() -> argparse.ArgumentParser:
300
+ p = argparse.ArgumentParser(
301
+ prog="grokmap",
302
+ description="Measure comprehension debt: AI-written code that nobody on the team has shown they understand.",
303
+ )
304
+ p.add_argument("--version", action="version", version=f"grokmap {__version__}")
305
+ p.add_argument("-C", "--repo", default=".", help="path inside the git repository (default: .)")
306
+ sub = p.add_subparsers(dest="cmd", required=True)
307
+
308
+ s = sub.add_parser("status", help="summary of comprehension debt and the riskiest files")
309
+ s.add_argument("--top", type=int, default=10)
310
+ s.add_argument("--json", action="store_true", help="machine-readable output")
311
+ s.add_argument("--markdown", action="store_true", help="markdown summary (for PR comments and CI job summaries)")
312
+ s.add_argument("--no-cache", action="store_true")
313
+ s.set_defaults(func=cmd_status)
314
+
315
+ s = sub.add_parser("report", help="write the interactive HTML heatmap")
316
+ s.add_argument("-o", "--output")
317
+ s.add_argument("--name", help="project name shown in the report")
318
+ s.add_argument("--open", action="store_true", help="open it in a browser")
319
+ s.add_argument("--note", help="a line of text shown under the title (e.g. 'Demo data')")
320
+ s.add_argument("--no-cache", action="store_true")
321
+ s.set_defaults(func=cmd_report)
322
+
323
+ s = sub.add_parser("trend", help="AI-written vs human-written lines added over time")
324
+ s.add_argument("--by", choices=("auto", "week", "month"), default="auto")
325
+ s.add_argument("--since", help="only commits after this date, e.g. 2026-01-01 or '6 months ago'")
326
+ s.add_argument("--json", action="store_true")
327
+ s.set_defaults(func=cmd_trend)
328
+
329
+ s = sub.add_parser("diff", help="AI-written lines a branch adds, and how many are understood (for PRs)")
330
+ s.add_argument("--base", default="origin/main", help="branch to compare with (default: origin/main)")
331
+ s.add_argument("--markdown", action="store_true", help="markdown for a PR comment")
332
+ s.add_argument("--json", action="store_true")
333
+ s.add_argument("--max-unread", type=int, help="exit 1 when more AI lines than this are unchecked")
334
+ s.set_defaults(func=cmd_diff)
335
+
336
+ s = sub.add_parser("badge", help="write an SVG README badge")
337
+ s.add_argument("-o", "--output")
338
+ s.add_argument("--label", default="comprehension debt")
339
+ s.add_argument("--no-cache", action="store_true")
340
+ s.set_defaults(func=cmd_badge)
341
+
342
+ s = sub.add_parser("check", help="exit 1 when debt is above the limit (for CI)")
343
+ s.add_argument("--max-debt", type=float, help="limit in percent (default: max_debt from config, 40)")
344
+ s.add_argument("--critical", action="store_true", help="only check paths listed as critical in config")
345
+ s.add_argument("--no-cache", action="store_true")
346
+ s.set_defaults(func=cmd_check)
347
+
348
+ s = sub.add_parser("quiz", help="print a quiz brief for your coding agent")
349
+ s.add_argument("paths", nargs="*", help="files or folders (default: whole repo)")
350
+ s.add_argument("--uncommitted", action="store_true", help="quiz on changes not yet committed (incl. new files)")
351
+ s.add_argument("--staged", action="store_true", help="quiz on staged changes")
352
+ s.add_argument("--diff", metavar="REV", help="quiz on what changed since REV (e.g. main, HEAD~3)")
353
+ s.add_argument("--max-lines", type=int, default=200, help="cap the brief at this many lines (0 = no cap)")
354
+ s.add_argument("--questions", type=int, default=3, help="minimum number of questions")
355
+ s.add_argument("--include-human", action="store_true", help="also quiz on human-written code")
356
+ s.add_argument("--who", help="person being quizzed (default: git user.email)")
357
+ s.add_argument("--format", choices=("md", "json"), default="md")
358
+ s.set_defaults(func=cmd_quiz)
359
+
360
+ s = sub.add_parser("mark", help="record that someone understands files or lines")
361
+ s.add_argument("paths", nargs="+", help="files or folders; use path:10-40,55-60 for line ranges")
362
+ s.add_argument("--score", type=float, required=True, help="quiz score 0..1 (or 0..100)")
363
+ s.add_argument("--method", choices=METHODS, default="quiz")
364
+ s.add_argument("--lines", help="line ranges for a single file, e.g. 10-40,55-60")
365
+ s.add_argument("--who", help="person (default: git user.email)")
366
+ s.add_argument("--note", help="optional note stored with the record")
367
+ s.set_defaults(func=cmd_mark)
368
+
369
+ s = sub.add_parser("who", help="who understands the AI-written code in a file or folder")
370
+ s.add_argument("path")
371
+ s.set_defaults(func=cmd_who)
372
+
373
+ s = sub.add_parser("init", help="add config, ledger and .gitattributes to this repo")
374
+ s.set_defaults(func=cmd_init)
375
+ return p
376
+
377
+
378
+ def main(argv: list[str] | None = None) -> int:
379
+ args = build_parser().parse_args(argv)
380
+ try:
381
+ return args.func(args)
382
+ except gitutil.GitError as exc:
383
+ print(f"grokmap: {exc}", file=sys.stderr)
384
+ return 2
385
+ except KeyboardInterrupt:
386
+ return 130
387
+ except BrokenPipeError:
388
+ # output piped into `head` or similar: stop quietly
389
+ import os
390
+
391
+ devnull = os.open(os.devnull, os.O_WRONLY)
392
+ os.dup2(devnull, sys.stdout.fileno())
393
+ return 0
394
+
395
+
396
+ if __name__ == "__main__":
397
+ raise SystemExit(main())
grokmap/config.py ADDED
@@ -0,0 +1,167 @@
1
+ """Configuration: `.grokmap.toml` at the repo root, or `[tool.grokmap]` in pyproject.toml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import re
7
+ import tomllib
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+
11
+ DEFAULT_EXCLUDE = [
12
+ # dependencies and build output
13
+ "node_modules/**",
14
+ "vendor/**",
15
+ "third_party/**",
16
+ "dist/**",
17
+ "build/**",
18
+ "out/**",
19
+ ".venv/**",
20
+ "venv/**",
21
+ "__pycache__/**",
22
+ "target/**",
23
+ ".next/**",
24
+ "coverage/**",
25
+ # generated and lock files
26
+ "*.lock",
27
+ "package-lock.json",
28
+ "pnpm-lock.yaml",
29
+ "yarn.lock",
30
+ "poetry.lock",
31
+ "uv.lock",
32
+ "Cargo.lock",
33
+ "go.sum",
34
+ "*.min.js",
35
+ "*.min.css",
36
+ "*.map",
37
+ "*.snap",
38
+ "*.pb.go",
39
+ "*_pb2.py",
40
+ # data, media and binaries
41
+ "*.svg",
42
+ "*.png",
43
+ "*.jpg",
44
+ "*.jpeg",
45
+ "*.gif",
46
+ "*.ico",
47
+ "*.webp",
48
+ "*.pdf",
49
+ "*.zip",
50
+ "*.gz",
51
+ "*.woff",
52
+ "*.woff2",
53
+ "*.ttf",
54
+ "*.eot",
55
+ "*.mp4",
56
+ "*.mp3",
57
+ "*.wav",
58
+ "*.csv",
59
+ "*.tsv",
60
+ "*.parquet",
61
+ "*.ipynb",
62
+ # grokmap's own state
63
+ ".grokmap/**",
64
+ ".grokmap.toml",
65
+ "grokmap-report.html",
66
+ "grokmap-badge.svg",
67
+ ]
68
+
69
+
70
+ @dataclass
71
+ class Config:
72
+ pass_score: float = 0.7
73
+ decay_days: int = 180
74
+ max_debt: float = 40.0
75
+ include: list[str] = field(default_factory=list)
76
+ exclude: list[str] = field(default_factory=list)
77
+ critical: list[str] = field(default_factory=list)
78
+ ai_patterns: dict[str, str] = field(default_factory=dict)
79
+ ai_commits: dict[str, str] = field(default_factory=dict)
80
+ max_file_lines: int = 20000
81
+
82
+ def is_included(self, path: str) -> bool:
83
+ if self.include and not any(match(path, g) for g in self.include):
84
+ return False
85
+ return not any(match(path, g) for g in DEFAULT_EXCLUDE + self.exclude)
86
+
87
+ def is_critical(self, path: str) -> bool:
88
+ return any(match(path, g) for g in self.critical)
89
+
90
+
91
+ def match(path: str, pattern: str) -> bool:
92
+ """Glob match where `dir/**` matches anything below dir and a bare name matches at any depth."""
93
+ if pattern.endswith("/**"):
94
+ prefix = pattern[:-3]
95
+ return path == prefix or path.startswith(prefix + "/") or ("/" + prefix + "/") in ("/" + path)
96
+ if "/" not in pattern:
97
+ return _glob(pattern).fullmatch(path.rsplit("/", 1)[-1]) is not None
98
+ return _glob(pattern).fullmatch(path) is not None
99
+
100
+
101
+ @functools.lru_cache(maxsize=512)
102
+ def _glob(pattern: str) -> re.Pattern[str]:
103
+ """Translate a glob: `**` crosses folders, `*` and `?` stay within one path segment."""
104
+ out, i = [], 0
105
+ while i < len(pattern):
106
+ c = pattern[i]
107
+ if pattern.startswith("**/", i):
108
+ out.append("(?:.*/)?")
109
+ i += 3
110
+ continue
111
+ if pattern.startswith("**", i):
112
+ out.append(".*")
113
+ i += 2
114
+ continue
115
+ out.append("[^/]*" if c == "*" else "[^/]" if c == "?" else re.escape(c))
116
+ i += 1
117
+ return re.compile("".join(out))
118
+
119
+
120
+ def load_config(root: Path) -> Config:
121
+ data: dict = {}
122
+ toml_path = root / ".grokmap.toml"
123
+ pyproject = root / "pyproject.toml"
124
+ if toml_path.exists():
125
+ raw = tomllib.loads(toml_path.read_text(encoding="utf-8"))
126
+ data = raw.get("grokmap", raw)
127
+ elif pyproject.exists():
128
+ try:
129
+ data = tomllib.loads(pyproject.read_text(encoding="utf-8")).get("tool", {}).get("grokmap", {})
130
+ except tomllib.TOMLDecodeError:
131
+ data = {}
132
+ cfg = Config()
133
+ for key in ("pass_score", "decay_days", "max_debt", "max_file_lines"):
134
+ if key in data:
135
+ setattr(cfg, key, type(getattr(cfg, key))(data[key]))
136
+ for key in ("include", "exclude", "critical"):
137
+ if key in data:
138
+ setattr(cfg, key, [str(x) for x in data[key]])
139
+ if "ai_patterns" in data:
140
+ cfg.ai_patterns = {str(k): str(v) for k, v in data["ai_patterns"].items()}
141
+ if "ai_commits" in data:
142
+ cfg.ai_commits = {str(k): str(v) for k, v in data["ai_commits"].items()}
143
+ return cfg
144
+
145
+
146
+ DEFAULT_TOML = """\
147
+ # grokmap configuration — https://github.com/Aadithya-kl/grokmap
148
+ [grokmap]
149
+ # A quiz score at or above this counts as "understood" (0.0 - 1.0).
150
+ pass_score = 0.7
151
+ # Understanding older than this many days counts as "fading" (0 = never fades).
152
+ decay_days = 180
153
+ # `grokmap check` fails when comprehension debt (%) is above this.
154
+ max_debt = 40
155
+ # Extra globs to skip, on top of the built-in list (lock files, build output, media...).
156
+ exclude = []
157
+ # Paths where debt matters most; `grokmap check --critical` only looks at these.
158
+ critical = []
159
+
160
+ # Extra AI signatures: tool = "regex on the commit message", or "author:regex".
161
+ [grokmap.ai_patterns]
162
+ # internal-bot = "^co-authored-by:.*internal-bot"
163
+
164
+ # Mark specific commits as AI-written (sha prefix = tool), e.g. before trailers were used.
165
+ [grokmap.ai_commits]
166
+ # "3f2a9c1" = "claude"
167
+ """