readthrough 0.4.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.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
readthrough/onboard.py ADDED
@@ -0,0 +1,551 @@
1
+ """Onboarding: draft an architecture profile for a repo, measure how well it covers real PRs, and gate on it.
2
+
3
+ A repo can't be built until it's onboarded. Onboarding means having a profile (from a shared directory, the
4
+ repo itself, or a draft written here and edited by you) that:
5
+
6
+ * maps at least ``[tuning.onboarding] min_coverage`` of the lines changed by recent PRs to real components;
7
+ * has no path patterns that match nothing in the repo, and no component that earlier ones shadow;
8
+ * has an ``[authors]`` section, so you've decided who counts as internal.
9
+
10
+ The draft is deliberately plain: it reads CODEOWNERS, the directory tree, where recent PRs actually
11
+ changed code, and any architecture docs or instruction files. It gets you a working map in a minute;
12
+ the Copilot-assisted draft (``--copilot``) or your own edits make it good.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import logging
19
+ import re
20
+ from collections import Counter
21
+ from collections.abc import Set as AbstractSet
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path, PurePosixPath
24
+ from typing import Any
25
+
26
+ from readthrough.forges import Forge
27
+ from readthrough.model import MergedPullRequest
28
+ from readthrough.process import run
29
+ from readthrough.profile import FALLBACK, Profile, parse_profile
30
+ from readthrough.rules import glob_to_regex
31
+ from readthrough.tuning import default_tuning
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ TEST_DIRS = {"tests", "test", "spec", "specs", "__tests__", "testing", "e2e", "integration_tests", "unit_tests"}
36
+ GENERIC_DIRS = {"src", "lib", "app", "core", "pkg", "internal", "common", "main"} # mean nothing without their parent
37
+ DOC_DIRS = {"doc", "docs", "documentation", "website", "site", "examples", "example", "samples"}
38
+ INFRA_DIRS = {
39
+ ".github",
40
+ ".azuredevops",
41
+ ".devcontainer",
42
+ ".circleci",
43
+ "build",
44
+ "build_scripts",
45
+ "ci",
46
+ "scripts",
47
+ "docker",
48
+ "infra",
49
+ "deploy",
50
+ "tools",
51
+ ".vscode",
52
+ }
53
+ INFRA_FILES = [
54
+ "Dockerfile",
55
+ "Makefile",
56
+ "*.yml",
57
+ "*.yaml",
58
+ "*.toml",
59
+ "*.cfg",
60
+ "*.ini",
61
+ "*.json",
62
+ "*.lock",
63
+ "LICENSE*",
64
+ ".*",
65
+ ]
66
+ MANIFESTS = ["pyproject.toml", "setup.py", "setup.cfg", "requirements*.txt", "uv.lock", "poetry.lock", "**/package.json", "package.json",
67
+ "**/package-lock.json", "**/yarn.lock", "**/pnpm-lock.yaml", "go.mod", "go.sum", "Cargo.toml", "Cargo.lock", "**/*.csproj", "Gemfile*"] # fmt: skip
68
+ ARCH_DOCS = ["ARCHITECTURE.md", "docs/ARCHITECTURE.md", "docs/architecture.md", "doc/architecture.md", "AGENTS.md"]
69
+ GUIDANCE = [".github/copilot-instructions.md", "AGENTS.md", "CONTRIBUTING.md", ".github/CONTRIBUTING.md"]
70
+ CODEOWNERS = [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"]
71
+
72
+
73
+ @dataclass
74
+ class RepoFacts:
75
+ """What onboarding knows about a repo, gathered once."""
76
+
77
+ repo: str
78
+ default_branch: str
79
+ tree: list[str]
80
+ churn: Counter[str]
81
+ authors: list[dict[str, Any]] # login, bot, association per recent PR
82
+ codeowners: list[tuple[str, list[str]]] = field(default_factory=list)
83
+ docs: dict[str, str] = field(default_factory=dict)
84
+ has_instructions: bool = False
85
+ tree_complete: bool = True # False when the forge listed only part of a huge tree
86
+
87
+
88
+ # ---------------------------------------------------------------- gathering
89
+
90
+
91
+ def gather(
92
+ forge: Forge,
93
+ *,
94
+ clone: Path | None = None,
95
+ open_prs: list[MergedPullRequest] | None = None,
96
+ sample: int | None = None,
97
+ ) -> RepoFacts:
98
+ branch, merged = forge.merged_prs(sample or default_tuning().onboarding.merged_sample)
99
+ churn: Counter[str] = Counter()
100
+ authors: list[dict[str, Any]] = []
101
+ for pr in merged + (open_prs or []):
102
+ for f in pr.files:
103
+ churn[f.path] += f.additions + f.deletions
104
+ authors.append({"login": pr.author.login, "bot": pr.author.bot, "association": pr.association.get("NONE")})
105
+ tree, complete = _tree(forge, branch, clone)
106
+ if not complete:
107
+ log.warning("Listed only %d files of a bigger tree; onboarding with a local clone sees them all", len(tree))
108
+ facts = RepoFacts(forge.repo, branch, tree, churn, authors, tree_complete=complete)
109
+ wanted = [p for p in [*CODEOWNERS, *ARCH_DOCS, *GUIDANCE] if p in tree]
110
+ texts = forge.read_files(wanted)
111
+ for path in CODEOWNERS:
112
+ if path in tree:
113
+ facts.codeowners = parse_codeowners(texts.get(path) or "")
114
+ break
115
+ for path in [*ARCH_DOCS, *GUIDANCE]:
116
+ if path in tree and path not in facts.docs:
117
+ facts.docs[path] = texts.get(path) or ""
118
+ facts.has_instructions = any(p.startswith(".github/instructions/") for p in tree)
119
+ return facts
120
+
121
+
122
+ def _tree(forge: Forge, branch: str, clone: Path | None) -> tuple[list[str], bool]:
123
+ if clone and (clone / ".git").exists():
124
+ out = run(["git", "-C", str(clone), "ls-files"], check=False)
125
+ if out.strip():
126
+ return out.splitlines(), True
127
+ return forge.tree(branch)
128
+
129
+
130
+ def parse_codeowners(text: str) -> list[tuple[str, list[str]]]:
131
+ rules = []
132
+ for raw_line in text.splitlines():
133
+ line = raw_line.split("#", 1)[0].strip()
134
+ if not line:
135
+ continue
136
+ pattern, *owners = line.split()
137
+ rules.append((codeowners_glob(pattern), owners))
138
+ return rules
139
+
140
+
141
+ def codeowners_glob(pattern: str) -> str:
142
+ """Translate a CODEOWNERS (gitignore-style) pattern into the profile's glob syntax."""
143
+ anchored = pattern.startswith("/")
144
+ p = pattern.strip("/")
145
+ if pattern.endswith("/") or ("." not in PurePosixPath(p).name and "*" not in p):
146
+ p = f"{p}/**"
147
+ return p if anchored or "/" in p.rstrip("/*") else f"**/{p}"
148
+
149
+
150
+ # ---------------------------------------------------------------- drafting
151
+
152
+
153
+ def _slug(text: str) -> str:
154
+ return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "root"
155
+
156
+
157
+ def _label(path: str) -> str:
158
+ name = PurePosixPath(path).name.replace("_", " ").replace("-", " ")
159
+ return name[:1].upper() + name[1:]
160
+
161
+
162
+ def _source_roots(tree: list[str], churn: Counter[str] | None = None) -> list[str]:
163
+ """Top-level directories holding the code, excluding tests, docs, and infra.
164
+
165
+ Ordered by where recent PRs changed lines, then by file count. Churn first, because a new directory with
166
+ few files and a lot of change (a port in progress, say) matters more to a reviewer than an old one with
167
+ many files and none; ranking by size alone dropped exactly such a directory on a large repo.
168
+ """
169
+ counts: Counter[str] = Counter(p.split("/", 1)[0] for p in tree if "/" in p)
170
+ churn_by_root: Counter[str] = Counter()
171
+ for path, lines in (churn or {}).items():
172
+ if "/" in path:
173
+ churn_by_root[path.split("/", 1)[0]] += lines
174
+ roots = sorted(
175
+ (d for d in counts if d.lower() not in TEST_DIRS | DOC_DIRS | INFRA_DIRS and not d.startswith(".")),
176
+ key=lambda d: (-churn_by_root[d], -counts[d], d),
177
+ )
178
+ # "src/<pkg>" layouts: look one level deeper.
179
+ expanded = []
180
+ for root in roots:
181
+ if root == "src":
182
+ expanded += [
183
+ f"src/{d}"
184
+ for d in sorted({p.split("/")[1] for p in tree if p.startswith("src/") and p.count("/") >= 2})
185
+ ]
186
+ else:
187
+ expanded.append(root)
188
+ return expanded
189
+
190
+
191
+ def draft_components(facts: RepoFacts, *, max_components: int = 16) -> list[dict[str, Any]]:
192
+ """Choose components from where code lives and where PRs change it."""
193
+ churn_by_dir: Counter[str] = Counter()
194
+ for path, lines in live_churn(facts).items():
195
+ parts = path.split("/")
196
+ for depth in (1, 2, 3):
197
+ if len(parts) > depth:
198
+ churn_by_dir["/".join(parts[:depth])] += lines
199
+ components: list[dict[str, Any]] = []
200
+ roots = _source_roots(facts.tree, live_churn(facts))
201
+ for root in roots[:6]:
202
+ subdirs = sorted(
203
+ {
204
+ p[len(root) + 1 :].split("/", 1)[0]
205
+ for p in facts.tree
206
+ if p.startswith(root + "/") and p[len(root) + 1 :].count("/") >= 1
207
+ }
208
+ )
209
+ busy = [d for d in subdirs if churn_by_dir[f"{root}/{d}"] > 0 and d.lower() not in TEST_DIRS]
210
+ busy.sort(key=lambda d: -churn_by_dir[f"{root}/{d}"])
211
+ layer = _slug(root.split("/")[-1])
212
+ root_name = root.split("/")[-1]
213
+ for d in busy[: max(2, max_components // max(1, len(roots)))]:
214
+ # "src", "lib", or "core" says nothing on its own; name it after the directory it's in.
215
+ generic = d.lower() in GENERIC_DIRS
216
+ components.append(
217
+ {
218
+ "id": _slug(f"{root_name}-{d}") if generic else _slug(d),
219
+ "label": f"{_label(root_name)} {d}" if generic else _label(d),
220
+ "layer": layer,
221
+ "paths": [f"{root}/{d}/**"],
222
+ }
223
+ )
224
+ components.append(
225
+ {
226
+ "id": _slug(root.split("/")[-1]) if busy else _slug(root),
227
+ "label": _label(root) + (" (rest)" if busy else ""),
228
+ "layer": layer,
229
+ "paths": [f"{root}/**"],
230
+ }
231
+ )
232
+ # CODEOWNERS entries for directories the tree heuristic didn't name.
233
+ for glob, _owners in facts.codeowners:
234
+ if glob.endswith("/**") and not any(glob in c["paths"] for c in components):
235
+ base = glob[:-3].lstrip("*/")
236
+ if base and any(p.startswith(base + "/") for p in facts.tree) and base.split("/")[0] in roots:
237
+ components.insert(
238
+ 0,
239
+ {
240
+ "id": _slug(base.split("/")[-1]),
241
+ "label": _label(base),
242
+ "layer": _slug(base.split("/")[0]),
243
+ "paths": [glob],
244
+ },
245
+ )
246
+ test_globs = sorted({f"{p.split('/')[0]}/**" for p in facts.tree if p.split("/")[0].lower() in TEST_DIRS})
247
+ test_globs += [
248
+ g
249
+ for g in (
250
+ "**/test_*.py",
251
+ "**/*_test.py",
252
+ "**/*_test.go",
253
+ "**/*.test.ts",
254
+ "**/*.test.tsx",
255
+ "**/*.spec.ts",
256
+ "**/__tests__/**",
257
+ )
258
+ if any(glob_to_regex(g).match(p) for p in facts.tree)
259
+ ]
260
+ exists = lambda g: any(glob_to_regex(g).match(p) for p in facts.tree) # noqa: E731
261
+ doc_globs = sorted({f"{p.split('/')[0]}/**" for p in facts.tree if p.split("/")[0].lower() in DOC_DIRS})
262
+ doc_globs += [g for g in ["**/*.md"] if exists(g)]
263
+ infra_globs = sorted({f"{p.split('/')[0]}/**" for p in facts.tree if p.split("/")[0] in INFRA_DIRS})
264
+ infra_globs += [g for g in INFRA_FILES if exists(g)]
265
+ support = [
266
+ ("tests", "Tests", test_globs),
267
+ ("docs", "Docs", doc_globs),
268
+ ("infra", "Build / CI / Infra", infra_globs),
269
+ ]
270
+ # Tests and docs inside source roots must win over the source component, so they go first.
271
+ head: list[dict[str, Any]] = [
272
+ {"id": cid, "label": label, "layer": "support", "paths": globs} for cid, label, globs in support if globs
273
+ ]
274
+ seen: set[str] = set()
275
+ out = []
276
+ for comp in [*head, *components]:
277
+ cid = str(comp["id"])
278
+ if cid in seen:
279
+ cid = f"{cid}-{len(seen)}"
280
+ comp["id"] = cid
281
+ seen.add(cid)
282
+ out.append(comp)
283
+ return _drop_unclaimed(out, facts.tree)
284
+
285
+
286
+ def _drop_unclaimed(components: list[dict[str, Any]], tree: list[str]) -> list[dict[str, Any]]:
287
+ """Remove components that end up with no files once first-match-wins is applied (shadowed or empty)."""
288
+ regexes = [[glob_to_regex(g) for g in c["paths"]] for c in components]
289
+ claimed: set[int] = set()
290
+ for path in tree:
291
+ for i, rxs in enumerate(regexes):
292
+ if any(rx.match(path) for rx in rxs):
293
+ claimed.add(i)
294
+ break
295
+ return [c for i, c in enumerate(components) if i in claimed]
296
+
297
+
298
+ def draft_profile(facts: RepoFacts, *, title: str | None = None) -> str:
299
+ """A complete, valid profile as TOML text, with comments pointing at what to edit."""
300
+ components = draft_components(facts)
301
+ layer_ids = list(dict.fromkeys(c["layer"] for c in components if c["layer"] != "support"))
302
+ owner = facts.repo.split("/")[0]
303
+ arch = next((p for p in ARCH_DOCS if p in facts.docs), None)
304
+ guidance = next((p for p in GUIDANCE if p in facts.docs), None)
305
+ out = [
306
+ f"# Architecture profile for {facts.repo}, drafted by `readthrough onboard`.",
307
+ "# Edit freely: rename and regroup components, write each one's responsibility, add signals.",
308
+ "# `readthrough onboard " + facts.repo + "` re-measures coverage; add `--accept` to finish onboarding.",
309
+ "schema = 1",
310
+ f"repo = {json.dumps(facts.repo)}",
311
+ 'drafted_by = "readthrough"',
312
+ f"title = {json.dumps(title or facts.repo.rsplit('/', 1)[1])}",
313
+ "",
314
+ ]
315
+ for lid in layer_ids:
316
+ out += ["[[layers]]", f"id = {json.dumps(lid)}", f"label = {json.dumps(_label(lid))}", ""]
317
+ out += ["[[layers]]", 'id = "support"', 'label = "Tests / docs / infra"', "source = false", ""]
318
+ out.append("# First match wins: tests and docs come first so they aren't counted as source.")
319
+ for c in components:
320
+ out += [
321
+ "[[components]]",
322
+ f"id = {json.dumps(c['id'])}",
323
+ f"label = {json.dumps(c['label'])}",
324
+ f"layer = {json.dumps(c['layer'])}",
325
+ "paths = [" + ", ".join(json.dumps(p) for p in c["paths"]) + "]",
326
+ ]
327
+ if c["layer"] != "support":
328
+ out.append('# responsibility = "What this component is for."')
329
+ out.append('# does_not_own = "What belongs somewhere else, so reviewers can spot responsibility bleed."')
330
+ out.append("")
331
+ if arch:
332
+ out += [
333
+ "[contracts]",
334
+ f"# {arch} could hold each component's contract as '## <section>' headings with",
335
+ "# '**Responsibility**:' lines and '- **Does not own**' bullets. Then set a component's contract = '<section>'.",
336
+ f"source = {json.dumps(arch)}",
337
+ "",
338
+ ]
339
+ out += ["[rules]", f"instructions_dir = {json.dumps('.github/instructions' if facts.has_instructions else '')}"]
340
+ if guidance:
341
+ out.append(f"guidance_file = {json.dumps(guidance)}")
342
+ out.append("")
343
+ manifests = [m for m in MANIFESTS if any(glob_to_regex(m).match(p) for p in facts.tree)]
344
+ if manifests:
345
+ out += [
346
+ "[[signals]]",
347
+ 'id = "deps"',
348
+ 'kind = "risk"',
349
+ 'message = "Dependency manifest changed"',
350
+ "paths = [" + ", ".join(json.dumps(m) for m in manifests) + "]",
351
+ "",
352
+ ]
353
+ migrations = sorted(
354
+ {p.rsplit("/", 1)[0] + "/**" for p in facts.tree if re.search(r"(^|/)(migrations|alembic)/", p)}
355
+ )[:3]
356
+ if migrations:
357
+ out += [
358
+ "[[signals]]",
359
+ 'id = "migration"',
360
+ 'kind = "risk"',
361
+ 'message = "Database migration: check upgrade and downgrade"',
362
+ "paths = [" + ", ".join(json.dumps(m) for m in migrations) + "]",
363
+ "",
364
+ ]
365
+ out += [
366
+ "[[smells]]",
367
+ 'id = "todo"',
368
+ 'kind = "info"',
369
+ 'message = "TODO/FIXME added"',
370
+ 'path = "."',
371
+ "line = '\\b(?:TODO|FIXME|XXX|HACK)\\b'",
372
+ "",
373
+ "[checks]",
374
+ "test_paths = ["
375
+ + ", ".join(
376
+ json.dumps(g) for g in ["tests/**", "**/tests/**", "**/test_*.py", "**/*.test.ts", "**/__tests__/**"]
377
+ )
378
+ + "]",
379
+ "",
380
+ "[weights]",
381
+ "capped_paths = ["
382
+ + ", ".join(json.dumps(g) for g in ["**/*.lock", "**/*-lock.json", "**/*.ipynb", "**/*.snap", "**/*.min.js"])
383
+ + "]",
384
+ "",
385
+ "[overlap]",
386
+ "ignore = "
387
+ + json.dumps(
388
+ [m for m in ("uv.lock", "package-lock.json", "yarn.lock", "go.sum", "Cargo.lock") if m in facts.tree]
389
+ ),
390
+ 'non_source = ["tests/**", "**/tests/**", "docs/**", "doc/**", "**/*.lock", "**/*.md"]',
391
+ "",
392
+ "[authors]",
393
+ "# GitHub's author association does most of the work: org members, owners, and collaborators are",
394
+ "# internal; contributors are external. Fill these in where that's wrong for your team.",
395
+ "internal = [] # logins, e.g. contractors who aren't org members",
396
+ "external = [] # logins, e.g. people who left but kept access",
397
+ "bots = []",
398
+ 'internal_teams = [] # e.g. ["' + owner + '/maintainers"]: members count as internal',
399
+ 'internal_orgs = [] # e.g. ["' + owner + "\"]: checks each author's org membership",
400
+ "",
401
+ ]
402
+ return "\n".join(out)
403
+
404
+
405
+ # ---------------------------------------------------------------- coverage
406
+
407
+
408
+ @dataclass
409
+ class Coverage:
410
+ total: int
411
+ mapped: int
412
+ by_component: Counter[str]
413
+ unmapped_top: list[tuple[str, int]]
414
+ dead_patterns: list[tuple[str, str]]
415
+ shadowed: list[str]
416
+ has_authors: bool
417
+ basis: str = "changed lines in recent PRs"
418
+ need: float = field(default_factory=lambda: default_tuning().onboarding.min_coverage)
419
+
420
+ @property
421
+ def share(self) -> float:
422
+ return self.mapped / self.total if self.total else 1.0
423
+
424
+ def problems(self) -> list[str]:
425
+ out = []
426
+ if self.share < self.need:
427
+ out.append(
428
+ f"Only {self.share:.0%} of {self.basis} map to a component (need {self.need:.0%}). Add components for the unmapped paths below."
429
+ )
430
+ out += [f"Component {cid!r}: pattern {pat!r} matches no file in the repo" for cid, pat in self.dead_patterns]
431
+ out += [
432
+ f"Component {cid!r} never gets a file: earlier components claim everything it matches. Move it up."
433
+ for cid in self.shadowed
434
+ ]
435
+ if not self.has_authors:
436
+ out.append(
437
+ "The profile has no [authors] section. Add one (even empty) once you've checked how authors classify."
438
+ )
439
+ return out
440
+
441
+
442
+ def live_churn(facts: RepoFacts) -> Counter[str]:
443
+ """Lines changed by recent PRs in files that still exist.
444
+
445
+ Files deleted since can't be mapped without a pattern that matches nothing, so they don't count.
446
+ With no merged PRs to learn from (or none touching current files), every file counts once instead.
447
+ """
448
+ tree = set(facts.tree)
449
+ live = Counter({p: n for p, n in facts.churn.items() if p in tree}) if tree else facts.churn
450
+ return live or Counter(dict.fromkeys(facts.tree, 1))
451
+
452
+
453
+ def measure(
454
+ profile: Profile, facts: RepoFacts, *, raw: dict[str, Any] | None = None, min_coverage: float | None = None
455
+ ) -> Coverage:
456
+ by_component: Counter[str] = Counter()
457
+ unmapped: Counter[str] = Counter()
458
+ total = mapped = 0
459
+ # With no merged PRs to learn from, every file in the repo counts once instead.
460
+ sample = live_churn(facts)
461
+ for path, churn in sample.items():
462
+ lines = max(churn, 1)
463
+ comp = profile.component_of(path)
464
+ total += lines
465
+ by_component[comp] += lines
466
+ if comp == FALLBACK:
467
+ unmapped["/".join(path.split("/")[:2]) if "/" in path else path] += lines
468
+ else:
469
+ mapped += lines
470
+ dead, shadowed = [], []
471
+ claimed = {p: profile.component_of(p) for p in facts.tree}
472
+ for comp in profile.components:
473
+ if comp.id == FALLBACK:
474
+ continue
475
+ # A pattern that matches nothing is only a finding when the whole tree was seen.
476
+ for pat, rx in zip(comp.paths, comp.regexes, strict=True):
477
+ if facts.tree_complete and not any(rx.match(p) for p in facts.tree):
478
+ dead.append((comp.id, pat))
479
+ if any(comp.matches(p) for p in facts.tree) and comp.id not in claimed.values():
480
+ shadowed.append(comp.id)
481
+ has_authors = raw is None or "authors" in raw
482
+ basis = (
483
+ "changed lines in recent PRs"
484
+ if any(p in claimed for p in facts.churn)
485
+ else "files in the repo (no merged PRs to learn from yet)"
486
+ )
487
+ if not facts.tree_complete:
488
+ basis += f" (only {len(facts.tree)} files of the tree were listed; onboard with --clone to see them all)"
489
+ need = default_tuning().onboarding.min_coverage if min_coverage is None else min_coverage
490
+ return Coverage(total, mapped, by_component, unmapped.most_common(8), dead, shadowed, has_authors, basis, need)
491
+
492
+
493
+ def author_table(
494
+ profile: Profile, facts: RepoFacts, members: AbstractSet[str] = frozenset()
495
+ ) -> list[tuple[str, str, str, int]]:
496
+ """How recent PR authors classify under this profile: (login, association, kind, PR count)."""
497
+ from readthrough.analyze import author_kind
498
+
499
+ counts: Counter[tuple[str, str, str]] = Counter()
500
+ for a in facts.authors:
501
+ kind = author_kind(a["login"], a["association"], profile.authors, bot=a.get("bot", False), members=members)
502
+ counts[(a["login"], a["association"], kind)] += 1
503
+ return sorted(
504
+ ((login, assoc, kind, n) for (login, assoc, kind), n in counts.items()), key=lambda r: (r[2], -r[3], r[0])
505
+ )
506
+
507
+
508
+ def check_profile_text(
509
+ text: str, facts: RepoFacts, *, origin: str = "draft", min_coverage: float | None = None
510
+ ) -> tuple[Profile, Coverage]:
511
+ import tomllib
512
+
513
+ raw = tomllib.loads(text)
514
+ profile = parse_profile(raw, origin=origin)
515
+ return profile, measure(profile, facts, raw=raw, min_coverage=min_coverage)
516
+
517
+
518
+ def drift(items: list[dict[str, Any]], threshold: float | None = None) -> dict[str, Any] | None:
519
+ """Warn when the map stops fitting: too much of the open PRs' churn falls into "other"."""
520
+ total = sum(sum(it["by_comp"].values()) for it in items)
521
+ other = sum(it["by_comp"].get(FALLBACK, 0) for it in items)
522
+ if not total:
523
+ return None
524
+ share = 1 - other / total
525
+ if share >= (default_tuning().onboarding.drift_coverage if threshold is None else threshold):
526
+ return None
527
+ paths: Counter[str] = Counter()
528
+ for it in items:
529
+ for f in it["files"]:
530
+ if f["comp"] == FALLBACK:
531
+ paths["/".join(f["path"].split("/")[:2])] += f["add"] + f["del"]
532
+ return {"coverage": round(share, 2), "unmapped": paths.most_common(5)}
533
+
534
+
535
+ def report(cov: Coverage, profile: Profile, authors: list[tuple[str, str, str, int]]) -> str:
536
+ lines = [f"Coverage: {cov.share:.0%} of {cov.total} {cov.basis} map to a component."]
537
+ top = [(profile.component_by_id[c].label, n) for c, n in cov.by_component.most_common(12) if c != FALLBACK]
538
+ if top:
539
+ lines.append(" Busiest: " + ", ".join(f"{label} {n}" for label, n in top))
540
+ if cov.unmapped_top:
541
+ lines.append(" Unmapped (falls into 'other'): " + ", ".join(f"{p} {n}" for p, n in cov.unmapped_top))
542
+ lines.append("Authors in recent PRs:")
543
+ for kind in dict.fromkeys(k for _, _, k, _ in authors):
544
+ people = [f"{login} ({assoc.lower()}, {n})" for login, assoc, k, n in authors if k == kind]
545
+ lines.append(
546
+ f" {kind}: " + ", ".join(people[:12]) + (f" and {len(people) - 12} more" if len(people) > 12 else "")
547
+ )
548
+ problems = cov.problems()
549
+ lines.append("Ready to accept." if not problems else "Before accepting:")
550
+ lines += [f" - {p}" for p in problems]
551
+ return "\n".join(lines)