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/quiz.py ADDED
@@ -0,0 +1,334 @@
1
+ """Build quiz briefs for coding agents and record the results in the ledger."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+
10
+ from grokmap import gitutil
11
+ from grokmap.config import Config
12
+ from grokmap.ledger import Record, append_records, load_ledger
13
+ from grokmap.scan import Scan, is_meaningful, line_hash, normalize
14
+ from grokmap.score import UNDERSTOOD, _record_state, ranges
15
+
16
+ LANG = {
17
+ ".py": "python",
18
+ ".js": "javascript",
19
+ ".jsx": "jsx",
20
+ ".ts": "typescript",
21
+ ".tsx": "tsx",
22
+ ".go": "go",
23
+ ".rs": "rust",
24
+ ".java": "java",
25
+ ".kt": "kotlin",
26
+ ".rb": "ruby",
27
+ ".php": "php",
28
+ ".c": "c",
29
+ ".h": "c",
30
+ ".cc": "cpp",
31
+ ".cpp": "cpp",
32
+ ".hpp": "cpp",
33
+ ".cs": "csharp",
34
+ ".swift": "swift",
35
+ ".sh": "bash",
36
+ ".sql": "sql",
37
+ ".html": "html",
38
+ ".css": "css",
39
+ ".scss": "scss",
40
+ ".vue": "vue",
41
+ ".svelte": "svelte",
42
+ ".yml": "yaml",
43
+ ".yaml": "yaml",
44
+ ".toml": "toml",
45
+ ".json": "json",
46
+ ".md": "markdown",
47
+ ".lua": "lua",
48
+ ".dart": "dart",
49
+ ".scala": "scala",
50
+ ".ex": "elixir",
51
+ ".exs": "elixir",
52
+ ".zig": "zig",
53
+ }
54
+
55
+
56
+ @dataclass
57
+ class Target:
58
+ path: str
59
+ ranges: list[tuple[int, int]]
60
+ tools: list[str]
61
+ lines: dict[int, str] # lineno -> text (only lines inside ranges)
62
+
63
+
64
+ def parse_ranges(spec: str) -> list[tuple[int, int]]:
65
+ out = []
66
+ for part in spec.split(","):
67
+ part = part.strip()
68
+ if not part:
69
+ continue
70
+ if "-" in part:
71
+ a, b = part.split("-", 1)
72
+ lo, hi = int(a), int(b)
73
+ else:
74
+ lo = hi = int(part)
75
+ if lo < 1 or hi < lo:
76
+ raise ValueError(f"bad line range: {part}")
77
+ out.append((lo, hi))
78
+ return out
79
+
80
+
81
+ def format_ranges(rs: list[tuple[int, int]]) -> str:
82
+ return ",".join(f"{a}-{b}" if a != b else str(a) for a, b in rs)
83
+
84
+
85
+ def read_lines(root: Path, path: str) -> list[str]:
86
+ try:
87
+ return (root / path).read_text(encoding="utf-8", errors="replace").splitlines()
88
+ except OSError:
89
+ return []
90
+
91
+
92
+ def known_hashes(records: list[Record], who: str, path: str, cfg: Config) -> set[str]:
93
+ now = datetime.now(UTC)
94
+ known: set[str] = set()
95
+ for rec in records:
96
+ if rec.path == path and rec.who == who and _record_state(rec, cfg, now) == UNDERSTOOD:
97
+ known |= rec.hashes
98
+ return known
99
+
100
+
101
+ def build_targets(
102
+ root: Path,
103
+ cfg: Config,
104
+ who: str,
105
+ scan: Scan | None,
106
+ paths: list[str],
107
+ diff_base: str | None,
108
+ staged: bool,
109
+ diff_mode: bool,
110
+ include_human: bool = False,
111
+ ) -> list[Target]:
112
+ records = load_ledger(root)
113
+ targets: list[Target] = []
114
+
115
+ if diff_mode:
116
+ for path in gitutil.diff_files(root, diff_base, staged):
117
+ if not cfg.is_included(path) or (paths and not any(path == p or path.startswith(p.rstrip("/") + "/") for p in paths)):
118
+ continue
119
+ text = read_lines(root, path)
120
+ if not text:
121
+ continue
122
+ added = gitutil.diff_added_lines(root, path, diff_base, staged)
123
+ if added is None:
124
+ added = [(1, len(text))]
125
+ known = known_hashes(records, who, path, cfg)
126
+ picked = []
127
+ for lo, hi in added:
128
+ for n in range(lo, min(hi, len(text)) + 1):
129
+ norm = normalize(text[n - 1])
130
+ if is_meaningful(norm) and line_hash(norm) not in known:
131
+ picked.append(n)
132
+ if picked:
133
+ rs = ranges(picked)
134
+ targets.append(Target(path, rs, [], _slice(text, rs)))
135
+ return targets
136
+
137
+ if scan is None:
138
+ return targets
139
+ wanted = list(scan.files)
140
+ if paths:
141
+ norm_paths = [p.rstrip("/") for p in paths]
142
+ wanted = [f for f in wanted if any(f == p or f.startswith(p + "/") or p in ("", ".") for p in norm_paths)]
143
+ for path in sorted(wanted):
144
+ fs = scan.files[path]
145
+ known = known_hashes(records, who, path, cfg)
146
+ picked, tools = [], set()
147
+ for ln in fs.lines:
148
+ meta = scan.commits.get(ln.sha)
149
+ tool = meta.tool if meta else None
150
+ if (tool or include_human) and ln.h not in known:
151
+ picked.append(ln.lineno)
152
+ if tool:
153
+ tools.add(tool)
154
+ if picked:
155
+ text = read_lines(root, path)
156
+ rs = ranges(picked)
157
+ targets.append(Target(path, rs, sorted(tools) or ["human"], _slice(text, rs)))
158
+ return targets
159
+
160
+
161
+ def _slice(text: list[str], rs: list[tuple[int, int]]) -> dict[int, str]:
162
+ out = {}
163
+ for lo, hi in rs:
164
+ for n in range(lo, min(hi, len(text)) + 1):
165
+ out[n] = text[n - 1]
166
+ return out
167
+
168
+
169
+ def truncate(targets: list[Target], max_lines: int) -> tuple[list[Target], bool]:
170
+ """Keep the brief small enough for one quiz: biggest chunks first, up to max_lines lines."""
171
+ if max_lines <= 0:
172
+ return targets, False
173
+ budget = max_lines
174
+ kept: list[Target] = []
175
+ cut = False
176
+ for t in sorted(targets, key=lambda t: -len(t.lines)):
177
+ if budget <= 0:
178
+ cut = True
179
+ break
180
+ rs_kept, lines_kept = [], {}
181
+ for lo, hi in t.ranges:
182
+ if budget <= 0:
183
+ cut = True
184
+ break
185
+ span = [n for n in range(lo, hi + 1) if n in t.lines]
186
+ if not span:
187
+ continue
188
+ if len(span) > budget:
189
+ span = span[:budget]
190
+ cut = True
191
+ rs_kept.append((span[0], span[-1]))
192
+ for n in span:
193
+ lines_kept[n] = t.lines[n]
194
+ budget -= len(span)
195
+ if rs_kept:
196
+ kept.append(Target(t.path, rs_kept, t.tools, lines_kept))
197
+ kept.sort(key=lambda t: t.path)
198
+ return kept, cut
199
+
200
+
201
+ QUIZ_RULES = """\
202
+ ## How to run this quiz
203
+
204
+ You are checking that **{who}** understands this code well enough to debug it at 2am without an AI.
205
+
206
+ 1. Read the code below yourself first. Find the parts that matter: the core logic, edge cases, error paths, and anything surprising.
207
+ 2. Ask **{n_questions} questions, one at a time**, and wait for each answer before asking the next. Do not show the code again in the question and do not hint at the answer.
208
+ 3. Good questions ask *why* and *what if*, not trivia:
209
+ - "What happens if `X` is empty / null / huge?"
210
+ - "Why is this done before that?"
211
+ - "A user reports <symptom>. Where would you look first?"
212
+ - "What would break if we removed this line?"
213
+ Avoid questions answerable by re-reading a name (for example "what does `get_user` return?").
214
+ 4. Grade each answer: **1** = correct and explains why, **0.5** = partly right or vague, **0** = wrong or "I don't know". Explain the right answer after each one, briefly.
215
+ 5. Score = average of the grades. Then record it (this command covers exactly the lines shown below):
216
+
217
+ ```
218
+ {mark_cmd}
219
+ ```
220
+
221
+ If the person does not want a quiz, offer the lighter options instead: ask them to explain the change back in their own words (`--method explain`, you grade it), or record that they only skimmed it (`--method review`, counts as half-understood).
222
+ """
223
+
224
+
225
+ def render_markdown(targets: list[Target], who: str, truncated: bool, n_questions: int = 3) -> str:
226
+ total = sum(len(t.lines) for t in targets)
227
+ if not targets:
228
+ return f"# grokmap quiz brief\n\nNothing to quiz: **{who}** already understands every AI-written line in scope.\n"
229
+ if len(targets) == 1:
230
+ mark_cmd = f"grokmap mark {targets[0].path} --lines {format_ranges(targets[0].ranges)} --score <0..1> --method quiz"
231
+ else:
232
+ mark_cmd = (
233
+ "grokmap mark " + " ".join(f"{t.path}:{format_ranges(t.ranges)}" for t in targets) + " --score <0..1> --method quiz"
234
+ )
235
+ n_q = max(n_questions, min(6, 2 + total // 80))
236
+ head = [
237
+ "# grokmap quiz brief",
238
+ "",
239
+ f"Person: **{who}** · {total} lines in {len(targets)} file(s) they have not yet shown they understand.",
240
+ ]
241
+ if truncated:
242
+ head.append("_The brief was cut to keep the quiz short. Run it again afterwards to cover the rest._")
243
+ head += ["", QUIZ_RULES.format(who=who, n_questions=n_q, mark_cmd=mark_cmd), "## Code to quiz on", ""]
244
+ body = []
245
+ for t in targets:
246
+ lang = LANG.get(Path(t.path).suffix.lower(), "")
247
+ span = format_ranges(t.ranges)
248
+ word = "line" if len(t.ranges) == 1 and t.ranges[0][0] == t.ranges[0][1] else "lines"
249
+ origin = f"written by {', '.join(t.tools)}" if t.tools else "new or changed, not committed yet"
250
+ body.append(f"### `{t.path}` — {word} {span} · {origin}")
251
+ body.append("")
252
+ for lo, hi in t.ranges:
253
+ body.append(f"```{lang}")
254
+ width = len(str(hi))
255
+ for n in range(lo, hi + 1):
256
+ if n in t.lines:
257
+ body.append(f"{str(n).rjust(width)} | {t.lines[n]}")
258
+ body.append("```")
259
+ body.append("")
260
+ return "\n".join(head + body)
261
+
262
+
263
+ def render_json(targets: list[Target], who: str, truncated: bool) -> str:
264
+ return json.dumps(
265
+ {
266
+ "who": who,
267
+ "truncated": truncated,
268
+ "targets": [
269
+ {"path": t.path, "ranges": t.ranges, "tools": t.tools, "lines": {str(k): v for k, v in t.lines.items()}}
270
+ for t in targets
271
+ ],
272
+ },
273
+ indent=2,
274
+ )
275
+
276
+
277
+ def mark(
278
+ root: Path,
279
+ cfg: Config,
280
+ specs: list[str],
281
+ score: float,
282
+ method: str,
283
+ who: str,
284
+ line_spec: str | None,
285
+ note: str = "",
286
+ ) -> list[Record]:
287
+ """Record understanding for files (optionally only some lines). Directories expand to their files."""
288
+ if score > 1.0:
289
+ score = score / 100.0 # accept 85 as well as 0.85
290
+ if not 0.0 <= score <= 1.0:
291
+ raise ValueError("score must be between 0 and 1 (or 0 and 100)")
292
+ if method == "wrote" and score < cfg.pass_score:
293
+ score = 1.0
294
+
295
+ jobs: list[tuple[str, list[tuple[int, int]] | None]] = []
296
+ for spec in specs:
297
+ path, rs = spec, None
298
+ if ":" in spec and spec.rsplit(":", 1)[1].replace("-", "").replace(",", "").isdigit():
299
+ path, r = spec.rsplit(":", 1)
300
+ rs = parse_ranges(r)
301
+ path = path.replace("\\", "/").rstrip("/")
302
+ if path.startswith("./"):
303
+ path = path[2:]
304
+ full = root / path
305
+ if full.is_dir():
306
+ for f in sorted(full.rglob("*")):
307
+ rel = f.relative_to(root).as_posix()
308
+ if f.is_file() and cfg.is_included(rel) and "/.git/" not in f"/{rel}/":
309
+ jobs.append((rel, None))
310
+ elif full.is_file():
311
+ jobs.append((path, rs))
312
+ else:
313
+ raise FileNotFoundError(f"no such file or directory: {path}")
314
+ if line_spec:
315
+ if len(jobs) != 1:
316
+ raise ValueError("--lines only works with a single file (use path:10-40 for several)")
317
+ jobs[0] = (jobs[0][0], parse_ranges(line_spec))
318
+
319
+ now = datetime.now(UTC)
320
+ records = []
321
+ for path, rs in jobs:
322
+ text = read_lines(root, path)
323
+ wanted = set()
324
+ for n, raw in enumerate(text, start=1):
325
+ if rs and not any(lo <= n <= hi for lo, hi in rs):
326
+ continue
327
+ norm = normalize(raw)
328
+ if is_meaningful(norm):
329
+ wanted.add(line_hash(norm))
330
+ if wanted:
331
+ records.append(Record(path, who, score, method, now, frozenset(wanted), note))
332
+ if records:
333
+ append_records(root, records)
334
+ return records
grokmap/report.py ADDED
@@ -0,0 +1,60 @@
1
+ """Render the self-contained HTML comprehension map."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import UTC, datetime
7
+ from importlib import resources
8
+ from pathlib import Path
9
+
10
+ from grokmap import __version__
11
+ from grokmap.scan import Scan
12
+ from grokmap.score import Result
13
+
14
+
15
+ def build_payload(scan: Scan, result: Result, repo_name: str, trend: dict | None = None, note: str | None = None) -> dict:
16
+ files = []
17
+ for path, st in sorted(result.files.items()):
18
+ files.append(
19
+ {
20
+ "p": path,
21
+ "n": st.lines,
22
+ "h": st.human,
23
+ "u": st.understood,
24
+ "f": st.fading,
25
+ "s": st.skimmed,
26
+ "x": st.unread,
27
+ "d": round(st.debt, 1),
28
+ "t": dict(st.tools.most_common()),
29
+ "k": dict(st.people.most_common()),
30
+ "c": path in result.critical_files,
31
+ }
32
+ )
33
+ total = result.total
34
+ return {
35
+ "repo": repo_name,
36
+ "head": (scan.head or "")[:10],
37
+ "generated": datetime.now(UTC).strftime("%Y-%m-%d %H:%M UTC"),
38
+ "version": __version__,
39
+ "total": total.to_dict(),
40
+ "critical": result.critical.to_dict() if result.critical_files else None,
41
+ "files": files,
42
+ "trend": trend,
43
+ "note": note,
44
+ }
45
+
46
+
47
+ def render_report(scan: Scan, result: Result, repo_name: str, trend: dict | None = None, note: str | None = None) -> str:
48
+ template = resources.files("grokmap").joinpath("report_template.html").read_text(encoding="utf-8")
49
+ data = json.dumps(build_payload(scan, result, repo_name, trend, note), separators=(",", ":"))
50
+ data = data.replace("</", "<\\/")
51
+ return template.replace("/*__GROKMAP_DATA__*/null", data).replace("__GROKMAP_TITLE__", _html_escape(repo_name))
52
+
53
+
54
+ def _html_escape(s: str) -> str:
55
+ return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
56
+
57
+
58
+ def write_report(path: Path, html: str) -> None:
59
+ path.parent.mkdir(parents=True, exist_ok=True)
60
+ path.write_text(html, encoding="utf-8")