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/profile.py ADDED
@@ -0,0 +1,699 @@
1
+ """Architecture profiles: everything repo-specific, as data.
2
+
3
+ A profile describes one repository's architecture (layers and components, mapped to paths), where its
4
+ architectural contracts live, which review rules apply, which signals and line heuristics to look for,
5
+ and how to classify PR authors. The dashboard's core reads only the profile, so onboarding a new repo is
6
+ writing (or generating) a profile, not changing code.
7
+
8
+ Profiles are TOML (stdlib ``tomllib``) and versioned with ``schema``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ import tomllib
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass, field
17
+ from functools import cached_property
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from readthrough.config import portable_path
22
+ from readthrough.model import REPO_PATH_RE, ChangedFile
23
+ from readthrough.registry import Registry
24
+ from readthrough.rules import glob_to_regex
25
+
26
+ SCHEMA = 1
27
+ FALLBACK = "other"
28
+ # Ids name layers, components, signals, and author kinds in URLs, CSS classes, and data attributes, so they are
29
+ # plain slugs. A layer's color lands in a style attribute, so it is a CSS color token and nothing else.
30
+ ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}")
31
+ COLOR_RE = re.compile(r"#[0-9a-fA-F]{3,8}|[A-Za-z]+|(?:rgb|hsl)a?\([0-9 .,%/]+\)")
32
+ # Who wrote the first draft, shown so readers know what to double-check: readthrough's heuristics from the file
33
+ # tree, or a model (the header comment names which). Older profiles say "copilot", the drafter's former name;
34
+ # it's read as "model".
35
+ DRAFTERS = ("readthrough", "model")
36
+ LEGACY_DRAFTERS = {"copilot": "model"}
37
+ KINDS = ("risk", "blocker", "convention", "responsibility", "correctness", "info", "author", "you")
38
+ DEFAULT_ASSOCIATION = {
39
+ "OWNER": "internal",
40
+ "MEMBER": "internal",
41
+ "COLLABORATOR": "internal",
42
+ "CONTRIBUTOR": "external",
43
+ "FIRST_TIME_CONTRIBUTOR": "first-time",
44
+ "FIRST_TIMER": "first-time",
45
+ "NONE": "first-time",
46
+ }
47
+
48
+
49
+ class ProfileError(ValueError):
50
+ pass
51
+
52
+
53
+ @dataclass
54
+ class Layer:
55
+ id: str
56
+ label: str
57
+ source: bool = True
58
+ flow: bool = False
59
+ color: str | None = None
60
+
61
+
62
+ @dataclass
63
+ class Component:
64
+ id: str
65
+ label: str
66
+ layer: str
67
+ paths: list[str]
68
+ contract: str | None = None
69
+ responsibility: str | None = None
70
+ does_not_own: str | None = None
71
+ questions: list[str] = field(default_factory=list)
72
+
73
+ @cached_property
74
+ def regexes(self) -> list[re.Pattern[str]]:
75
+ return [glob_to_regex(p) for p in self.paths]
76
+
77
+ def matches(self, path: str) -> bool:
78
+ return any(r.match(path) for r in self.regexes)
79
+
80
+
81
+ @dataclass
82
+ class Signal:
83
+ """Flag a PR when any changed file matches ``paths`` (optionally only for some change types)."""
84
+
85
+ id: str
86
+ kind: str
87
+ message: str
88
+ paths: list[str]
89
+ change_types: list[str] = field(default_factory=list)
90
+
91
+ @cached_property
92
+ def regexes(self) -> list[re.Pattern[str]]:
93
+ return [glob_to_regex(p) for p in self.paths]
94
+
95
+ def fires(self, files: list[ChangedFile]) -> bool:
96
+ return any(
97
+ any(r.match(f.path) for r in self.regexes) and (not self.change_types or f.change in self.change_types)
98
+ for f in files
99
+ )
100
+
101
+
102
+ @dataclass
103
+ class PairedFiles:
104
+ """Files that should change together, e.g. a notebook and the script it's generated from."""
105
+
106
+ id: str
107
+ kind: str
108
+ message: str
109
+ under: str
110
+ extensions: list[str]
111
+
112
+
113
+ @dataclass
114
+ class Smell:
115
+ """A regex over added lines. Prompts to look closer, never verdicts."""
116
+
117
+ id: str
118
+ kind: str
119
+ message: str
120
+ path: str
121
+ line: str
122
+ strip_brackets: bool = False
123
+
124
+ @cached_property
125
+ def path_re(self) -> re.Pattern[str]:
126
+ return re.compile(self.path)
127
+
128
+ @cached_property
129
+ def line_re(self) -> re.Pattern[str]:
130
+ return re.compile(self.line)
131
+
132
+
133
+ @dataclass
134
+ class AuthorKind:
135
+ id: str
136
+ label: str
137
+ badge: str
138
+ group: str
139
+ signal: dict[str, str] | None = None
140
+ questions: list[str] = field(default_factory=list)
141
+ priority: float = 0.0
142
+
143
+
144
+ @dataclass
145
+ class Authors:
146
+ internal: list[str] = field(default_factory=list)
147
+ external: list[str] = field(default_factory=list)
148
+ bots: list[str] = field(default_factory=list)
149
+ internal_teams: list[str] = field(default_factory=list)
150
+ internal_orgs: list[str] = field(default_factory=list)
151
+ association: dict[str, str] = field(default_factory=lambda: dict(DEFAULT_ASSOCIATION))
152
+ unknown: str = "external"
153
+ kinds: dict[str, AuthorKind] = field(default_factory=dict)
154
+
155
+
156
+ @dataclass
157
+ class Profile:
158
+ repo: str
159
+ title: str
160
+ layers: list[Layer]
161
+ components: list[Component]
162
+ read_order: list[str]
163
+ contracts_source: str | None = None
164
+ contracts_parser: str = "markdown-sections"
165
+ contracts_labels: dict[str, str] = field(
166
+ default_factory=lambda: {"responsibility": "Responsibility", "does_not_own": "Does not own"}
167
+ )
168
+ instructions_dir: str | None = ".github/instructions"
169
+ review_guidance_file: str | None = None
170
+ review_guidance: str = ""
171
+ study_guidance: str = ""
172
+ test_cmd: str | None = None
173
+ questions: list[str] = field(default_factory=list)
174
+ signals: list[Signal] = field(default_factory=list)
175
+ paired_files: list[PairedFiles] = field(default_factory=list)
176
+ smells: list[Smell] = field(default_factory=list)
177
+ test_paths: list[str] = field(default_factory=lambda: ["tests/**", "**/tests/**"])
178
+ tests_component: str | None = "tests"
179
+ no_tests_min_lines: int = 20
180
+ cross_cutting_layers: int = 3
181
+ large_lines: int = 800
182
+ stale_days: int = 21
183
+ capped_paths: list[str] = field(default_factory=list)
184
+ capped_lines: int = 20
185
+ overlap_ignore: list[str] = field(default_factory=list)
186
+ overlap_non_source: list[str] = field(default_factory=list)
187
+ authors: Authors = field(default_factory=Authors)
188
+ drafted_by: str | None = None
189
+ origin: str = ""
190
+ notes: list[str] = field(default_factory=list) # anything odd about how it was found, for the build's warnings
191
+
192
+ # ---- lookups
193
+
194
+ @cached_property
195
+ def layer_by_id(self) -> dict[str, Layer]:
196
+ return {layer.id: layer for layer in self.layers}
197
+
198
+ @cached_property
199
+ def component_by_id(self) -> dict[str, Component]:
200
+ return {c.id: c for c in self.components}
201
+
202
+ @cached_property
203
+ def layer_order(self) -> dict[str, int]:
204
+ return {layer.id: i for i, layer in enumerate(self.layers)}
205
+
206
+ @cached_property
207
+ def source_layers(self) -> set[str]:
208
+ return {layer.id for layer in self.layers if layer.source}
209
+
210
+ @cached_property
211
+ def _test_res(self) -> list[re.Pattern[str]]:
212
+ return [glob_to_regex(p) for p in self.test_paths]
213
+
214
+ @cached_property
215
+ def _capped_res(self) -> list[re.Pattern[str]]:
216
+ return [glob_to_regex(p) for p in self.capped_paths]
217
+
218
+ @cached_property
219
+ def _overlap_ignore_res(self) -> list[re.Pattern[str]]:
220
+ return [glob_to_regex(p) for p in self.overlap_ignore]
221
+
222
+ def component_of(self, path: str) -> str:
223
+ for comp in self.components:
224
+ if comp.matches(path):
225
+ return comp.id
226
+ return FALLBACK
227
+
228
+ def is_test(self, path: str) -> bool:
229
+ return any(r.match(path) for r in self._test_res)
230
+
231
+ def is_capped(self, path: str) -> bool:
232
+ return any(r.match(path) for r in self._capped_res)
233
+
234
+ def overlap_ignored(self, path: str) -> bool:
235
+ return any(r.match(path) for r in self._overlap_ignore_res)
236
+
237
+ def is_source(self, component: str) -> bool:
238
+ return self.component_by_id[component].layer in self.source_layers
239
+
240
+ def to_payload(self) -> dict[str, Any]:
241
+ """What the dashboard needs to draw the map."""
242
+ return {
243
+ "repo": self.repo,
244
+ "title": self.title,
245
+ "layers": [vars(layer) for layer in self.layers],
246
+ "overlap_non_source": [glob_to_regex(p).pattern for p in self.overlap_non_source],
247
+ "author_kinds": {
248
+ k: {"label": v.label, "badge": v.badge, "group": v.group} for k, v in self.authors.kinds.items()
249
+ },
250
+ "origin": self.origin,
251
+ "drafted_by": self.drafted_by,
252
+ "contracts_source": self.contracts_source,
253
+ }
254
+
255
+
256
+ # ---------------------------------------------------------------- finding a repo's profile
257
+
258
+ PROFILE_FILE = "readthrough.toml"
259
+
260
+
261
+ def repo_profile_paths(forge: Any = None) -> list[str]:
262
+ """Where a repo may carry its own profile, in the order they're tried.
263
+
264
+ The forge's dot-directory first (``.github/readthrough.toml`` on GitHub: next to CODEOWNERS and the
265
+ other review conventions, and what "Propose upstream" creates), then the repo root, dotted or plain.
266
+ """
267
+ config_dir = getattr(forge, "config_dir", "") or ".github"
268
+ return [f"{config_dir}/{PROFILE_FILE}", f".{PROFILE_FILE}", PROFILE_FILE]
269
+
270
+
271
+ @dataclass
272
+ class ProfileSource:
273
+ kind: str # a finder's name: explicit | local | repo | shared
274
+ label: str
275
+ load: Any
276
+ path: Path | None = None # the file, for every kind except "repo"
277
+ text: str | None = None # the file's content when it was fetched rather than read from ``path``
278
+
279
+ def read(self) -> str:
280
+ return self.path.read_text(encoding="utf-8") if self.path is not None else (self.text or "")
281
+
282
+
283
+ # A finder returns the source it would supply for this repo, or None. ``cfg`` is the repo's Config and
284
+ # ``forge`` its forge adapter (None when the caller wants to stay offline). Options come from the
285
+ # ``[profile_sources.<name>]`` table in config.toml, validated against the finder's options dataclass.
286
+ Finder = Callable[[Any, Any, Any], "ProfileSource | None"]
287
+
288
+ PROFILE_SOURCES: Registry[Finder] = Registry("profile source")
289
+
290
+ # Highest precedence first. A local draft always wins, so you can experiment; the repo's own file is the
291
+ # shared one; directories of profiles are for teams whose repos can't carry the file.
292
+ PRECEDENCE = ("explicit", "local", "repo", "shared")
293
+
294
+
295
+ @PROFILE_SOURCES.add("explicit", "the file named by `profile = ...` in the repo's config entry")
296
+ def _explicit(cfg: Any, forge: Any, options: Any) -> ProfileSource | None:
297
+ if not getattr(cfg, "profile", None):
298
+ return None
299
+ path = Path(cfg.profile).expanduser()
300
+ if not path.is_file():
301
+ raise ProfileError(f"The profile configured for {cfg.repo}, {path}, doesn't exist")
302
+ label = portable_path(path)
303
+ return ProfileSource("explicit", label, lambda: load_profile(path, origin=label), path)
304
+
305
+
306
+ @PROFILE_SOURCES.add("local", "your draft from onboarding, in the repo's data directory")
307
+ def _local(cfg: Any, forge: Any, options: Any) -> ProfileSource | None:
308
+ local = cfg.local_profile_path
309
+ if not local.exists():
310
+ return None
311
+ label = portable_path(local)
312
+ return ProfileSource("local", label, lambda: load_profile(local, origin=label), local)
313
+
314
+
315
+ @PROFILE_SOURCES.add(
316
+ "repo", f"the repo's own {PROFILE_FILE} (in its forge's dot-directory or at the root), read from the forge"
317
+ )
318
+ def _repo(cfg: Any, forge: Any, options: Any) -> ProfileSource | None:
319
+ if forge is None:
320
+ return None
321
+ candidates = repo_profile_paths(forge)
322
+ found = forge.read_files(candidates)
323
+ if not found:
324
+ return None
325
+ path = next(p for p in candidates if p in found)
326
+ label = f"{cfg.repo}:{path}"
327
+ notes = []
328
+ if len(found) > 1:
329
+ others = ", ".join(p for p in candidates if p in found and p != path)
330
+ notes.append(f"{cfg.repo} carries more than one profile ({path} is used; also found {others})")
331
+
332
+ def load() -> Profile:
333
+ profile = parse_profile(_toml(found[path], label), origin=label)
334
+ profile.notes.extend(notes)
335
+ return profile
336
+
337
+ return ProfileSource("repo", label, load, text=found[path])
338
+
339
+
340
+ @dataclass(frozen=True)
341
+ class SharedOptions:
342
+ dirs: list[Path] = field(default_factory=list) # each holds <owner>/<name>.toml files
343
+
344
+
345
+ @PROFILE_SOURCES.add(
346
+ "shared", "directories of profiles, one file per repo (`dirs` in [profile_sources.shared])", options=SharedOptions
347
+ )
348
+ def _shared(cfg: Any, forge: Any, options: Any) -> ProfileSource | None:
349
+ for directory in options.dirs:
350
+ path = shared_profile_path(directory, getattr(cfg, "slug", f"github/{cfg.repo}"))
351
+ if path is not None:
352
+ return ProfileSource("shared", str(path), lambda p=path: load_profile(p), path)
353
+ return None
354
+
355
+
356
+ def shared_profile_path(directory: Path, slug: str) -> Path | None:
357
+ """``<directory>/<forge>/<owner>/<name>.toml``, matched case-insensitively the way forges treat repo names.
358
+
359
+ ``<directory>/<owner>/<name>.toml`` is also accepted for GitHub repos, which is what the directory
360
+ held before there were other forges.
361
+ """
362
+ *parents, name = slug.split("/")
363
+ layouts = [parents] + ([parents[1:]] if parents[:1] == ["github"] else [])
364
+ for layout in layouts:
365
+ exact = directory.joinpath(*layout) / f"{name}.toml"
366
+ if exact.is_file():
367
+ return exact
368
+ if not directory.is_dir():
369
+ return None
370
+ pattern = "/".join(["*"] * len(layout) + ["*.toml"])
371
+ for candidate in directory.glob(pattern):
372
+ found = [*candidate.relative_to(directory).parts[:-1], candidate.stem]
373
+ if [p.lower() for p in found] == [p.lower() for p in [*layout, name]]:
374
+ return candidate
375
+ return None
376
+
377
+
378
+ def profile_sources(cfg: Any, forge: Any = None, *, first_only: bool = False) -> list[ProfileSource]:
379
+ """Every place a profile for ``cfg.repo`` could come from, highest precedence first.
380
+
381
+ With ``first_only``, stops at the first one found, so a local profile saves fetching the repo's file.
382
+ """
383
+ configured = getattr(cfg, "profile_source_options", None) or {}
384
+ sources: list[ProfileSource] = []
385
+ for name in PRECEDENCE:
386
+ finder = PROFILE_SOURCES.get(name)
387
+ options = configured.get(name) or PROFILE_SOURCES.defaults_for(name)
388
+ source = finder.impl(cfg, forge, options)
389
+ if source is not None:
390
+ sources.append(source)
391
+ if first_only:
392
+ break
393
+ return sources
394
+
395
+
396
+ def _toml(text: str, label: str) -> dict[str, Any]:
397
+ try:
398
+ return tomllib.loads(text)
399
+ except tomllib.TOMLDecodeError as exc:
400
+ raise ProfileError(f"{label}: {exc}") from exc
401
+
402
+
403
+ def resolve_profile(cfg: Any, forge: Any = None) -> Profile:
404
+ """The profile for ``cfg.repo`` from the highest-precedence source that has one."""
405
+ sources = profile_sources(cfg, forge, first_only=True)
406
+ if not sources:
407
+ raise ProfileError(f"No architecture profile for {cfg.repo}. Onboard it: readthrough onboard {cfg.repo}")
408
+ profile = sources[0].load()
409
+ if profile.repo.lower() != cfg.repo.lower():
410
+ raise ProfileError(f"{profile.origin} is for {profile.repo}, not {cfg.repo}")
411
+ # Local login overrides from config.toml extend the profile's lists.
412
+ profile.authors.internal = [*profile.authors.internal, *getattr(cfg, "internal_authors", [])]
413
+ profile.authors.external = [*profile.authors.external, *getattr(cfg, "external_authors", [])]
414
+ return profile
415
+
416
+
417
+ # ---------------------------------------------------------------- loading
418
+
419
+
420
+ _TOP_KEYS = {
421
+ "schema", "repo", "title", "drafted_by", "layers", "components", "read_order", "contracts", "rules", "review", "study",
422
+ "questions", "signals", "paired_files", "smells", "checks", "weights", "overlap", "authors",
423
+ } # fmt: skip
424
+
425
+
426
+ def load_profile(path: Path | str, *, origin: str | None = None) -> Profile:
427
+ path = Path(path)
428
+ try:
429
+ raw = tomllib.loads(path.read_text(encoding="utf-8"))
430
+ except tomllib.TOMLDecodeError as exc:
431
+ raise ProfileError(f"{path}: {exc}") from exc
432
+ return parse_profile(raw, origin=origin or str(path))
433
+
434
+
435
+ def parse_profile(raw: dict[str, Any], *, origin: str = "") -> Profile:
436
+ where = origin or "profile"
437
+
438
+ def fail(msg: str) -> ProfileError:
439
+ return ProfileError(f"{where}: {msg}")
440
+
441
+ def table(data: Any, name: str, allowed: set[str]) -> dict[str, Any]:
442
+ if data is None:
443
+ return {}
444
+ if not isinstance(data, dict):
445
+ raise fail(f"[{name}] must be a table")
446
+ unknown = set(data) - allowed
447
+ if unknown:
448
+ raise fail(f"unknown key(s) in [{name}]: {', '.join(sorted(unknown))}")
449
+ return data
450
+
451
+ def strs(value: Any, name: str) -> list[str]:
452
+ if value is None:
453
+ return []
454
+ if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
455
+ raise fail(f"{name} must be a list of strings")
456
+ return value
457
+
458
+ def kind_of(value: Any, name: str) -> str:
459
+ if value not in KINDS:
460
+ raise fail(f"{name}: kind must be one of {', '.join(KINDS)}")
461
+ return value
462
+
463
+ def ident(value: Any, name: str) -> str:
464
+ if not isinstance(value, str) or not ID_RE.fullmatch(value):
465
+ raise fail(f"{name}: id must be letters, digits, '_', '.', or '-', up to 64 characters (got {value!r})")
466
+ return value
467
+
468
+ unknown = set(raw) - _TOP_KEYS
469
+ if unknown:
470
+ raise fail(f"unknown top-level key(s): {', '.join(sorted(unknown))}")
471
+ if raw.get("schema") != SCHEMA:
472
+ raise fail(f"schema must be {SCHEMA} (got {raw.get('schema')!r})")
473
+ drafted_by = LEGACY_DRAFTERS.get(raw.get("drafted_by"), raw.get("drafted_by"))
474
+ if drafted_by not in (None, *DRAFTERS):
475
+ raise fail(f"drafted_by must be one of {', '.join(DRAFTERS)}")
476
+ repo = raw.get("repo")
477
+ # The repo's path on its forge: owner/name on most, group/subgroup/project on GitLab, org/project/repo on
478
+ # Azure DevOps. Which forge is implied by where the profile was found, so it isn't repeated here.
479
+ if not isinstance(repo, str) or not REPO_PATH_RE.fullmatch(repo):
480
+ raise fail("repo must be the repo's path on its forge, like 'owner/name'")
481
+
482
+ layers = []
483
+ for i, item in enumerate(raw.get("layers") or []):
484
+ t = table(item, f"layers[{i}]", {"id", "label", "source", "flow", "color"})
485
+ if not t.get("id") or not t.get("label"):
486
+ raise fail(f"layers[{i}] needs id and label")
487
+ color = t.get("color")
488
+ if color is not None and (not isinstance(color, str) or not COLOR_RE.fullmatch(color)):
489
+ raise fail(f"layers[{i}] ({t['id']}): color must be a CSS color such as '#1b7c83' (got {color!r})")
490
+ layers.append(
491
+ Layer(
492
+ ident(t["id"], f"layers[{i}]"),
493
+ t["label"],
494
+ bool(t.get("source", True)),
495
+ bool(t.get("flow", False)),
496
+ color,
497
+ )
498
+ )
499
+ if not layers:
500
+ raise fail("at least one [[layers]] entry is required")
501
+ layer_ids = [layer.id for layer in layers]
502
+ if len(set(layer_ids)) != len(layer_ids):
503
+ raise fail("layer ids must be unique")
504
+
505
+ components = []
506
+ for i, item in enumerate(raw.get("components") or []):
507
+ name = f"components[{i}]"
508
+ t = table(
509
+ item, name, {"id", "label", "layer", "paths", "contract", "responsibility", "does_not_own", "questions"}
510
+ )
511
+ for key in ("id", "label", "layer"):
512
+ if not t.get(key):
513
+ raise fail(f"{name} needs {key}")
514
+ ident(t["id"], name)
515
+ if t["layer"] not in layer_ids:
516
+ raise fail(f"{name} ({t['id']}): unknown layer {t['layer']!r}")
517
+ paths = strs(t.get("paths"), f"{name}.paths")
518
+ if not paths:
519
+ raise fail(f"{name} ({t['id']}) needs at least one path pattern")
520
+ components.append(
521
+ Component(
522
+ t["id"], t["label"], t["layer"], paths, t.get("contract"), t.get("responsibility"), t.get("does_not_own"),
523
+ strs(t.get("questions"), f"{name}.questions"),
524
+ )
525
+ ) # fmt: skip
526
+ if not components:
527
+ raise fail("at least one [[components]] entry is required")
528
+ ids = [c.id for c in components]
529
+ if len(set(ids)) != len(ids):
530
+ raise fail("component ids must be unique")
531
+ if FALLBACK not in ids:
532
+ components.append(Component(FALLBACK, "Other", layers[-1].id, ["**"]))
533
+ ids.append(FALLBACK)
534
+
535
+ read_order = strs(raw.get("read_order"), "read_order")
536
+ bad = set(read_order) - set(ids)
537
+ if bad:
538
+ raise fail(f"read_order mentions unknown component(s): {', '.join(sorted(bad))}")
539
+ by_layer = sorted(components, key=lambda c: layer_ids.index(c.layer))
540
+ read_order += [c.id for c in by_layer if c.id not in read_order]
541
+
542
+ contracts = table(raw.get("contracts"), "contracts", {"source", "parser", "labels"})
543
+ if contracts.get("parser", "markdown-sections") != "markdown-sections":
544
+ raise fail("contracts.parser: only 'markdown-sections' is supported")
545
+ labels = {"responsibility": "Responsibility", "does_not_own": "Does not own", **(contracts.get("labels") or {})}
546
+
547
+ rules = table(raw.get("rules"), "rules", {"instructions_dir", "guidance_file"})
548
+ review = table(raw.get("review"), "review", {"guidance", "test_cmd"})
549
+ study = table(raw.get("study"), "study", {"guidance"})
550
+ checks = table(
551
+ raw.get("checks"),
552
+ "checks",
553
+ {"test_paths", "tests_component", "no_tests_min_lines", "cross_cutting_layers", "large_lines", "stale_days"},
554
+ )
555
+ weights = table(raw.get("weights"), "weights", {"capped_paths", "capped_lines"})
556
+ overlap = table(raw.get("overlap"), "overlap", {"ignore", "non_source"})
557
+ questions = table(raw.get("questions"), "questions", {"always"})
558
+
559
+ tests_component = checks.get("tests_component", "tests" if "tests" in ids else None)
560
+ if tests_component is not None and tests_component not in ids:
561
+ raise fail(f"checks.tests_component: unknown component {tests_component!r}")
562
+
563
+ signals = []
564
+ for i, item in enumerate(raw.get("signals") or []):
565
+ t = table(item, f"signals[{i}]", {"id", "kind", "message", "paths", "change_types"})
566
+ signals.append(
567
+ Signal(
568
+ ident(t.get("id"), f"signals[{i}]"),
569
+ kind_of(t.get("kind"), f"signals[{i}]"),
570
+ t["message"],
571
+ strs(t.get("paths"), f"signals[{i}].paths"),
572
+ strs(t.get("change_types"), f"signals[{i}].change_types"),
573
+ )
574
+ )
575
+ paired = []
576
+ for i, item in enumerate(raw.get("paired_files") or []):
577
+ t = table(item, f"paired_files[{i}]", {"id", "kind", "message", "under", "extensions"})
578
+ exts = strs(t.get("extensions"), f"paired_files[{i}].extensions")
579
+ if len(exts) != 2:
580
+ raise fail(f"paired_files[{i}].extensions needs exactly two extensions")
581
+ paired.append(
582
+ PairedFiles(
583
+ ident(t.get("id"), f"paired_files[{i}]"),
584
+ kind_of(t.get("kind"), f"paired_files[{i}]"),
585
+ t["message"],
586
+ t.get("under", ""),
587
+ exts,
588
+ )
589
+ )
590
+ smells = []
591
+ for i, item in enumerate(raw.get("smells") or []):
592
+ t = table(item, f"smells[{i}]", {"id", "kind", "message", "path", "line", "strip_brackets"})
593
+ smell = Smell(
594
+ ident(t.get("id"), f"smells[{i}]"),
595
+ kind_of(t.get("kind"), f"smells[{i}]"),
596
+ t["message"],
597
+ t.get("path", "."),
598
+ t["line"],
599
+ bool(t.get("strip_brackets", False)),
600
+ )
601
+ try:
602
+ _ = (smell.path_re, smell.line_re) # compiles both, raising on a bad regex
603
+ except re.error as exc:
604
+ raise fail(f"smells[{i}] ({smell.id}): bad regex: {exc}") from exc
605
+ smells.append(smell)
606
+
607
+ return Profile(
608
+ repo=repo,
609
+ title=raw.get("title") or repo.rsplit("/", 1)[1],
610
+ layers=layers,
611
+ components=components,
612
+ read_order=read_order,
613
+ contracts_source=contracts.get("source"),
614
+ contracts_labels=labels,
615
+ instructions_dir=rules.get("instructions_dir", ".github/instructions"),
616
+ review_guidance_file=rules.get("guidance_file"),
617
+ review_guidance=review.get("guidance", ""),
618
+ study_guidance=study.get("guidance", ""),
619
+ test_cmd=review.get("test_cmd"),
620
+ questions=strs(questions.get("always"), "questions.always"),
621
+ signals=signals,
622
+ paired_files=paired,
623
+ smells=smells,
624
+ test_paths=strs(checks.get("test_paths"), "checks.test_paths") or ["tests/**", "**/tests/**"],
625
+ tests_component=tests_component,
626
+ no_tests_min_lines=int(checks.get("no_tests_min_lines", 20)),
627
+ cross_cutting_layers=int(checks.get("cross_cutting_layers", 3)),
628
+ large_lines=int(checks.get("large_lines", 800)),
629
+ stale_days=int(checks.get("stale_days", 21)),
630
+ capped_paths=strs(weights.get("capped_paths"), "weights.capped_paths"),
631
+ capped_lines=int(weights.get("capped_lines", 20)),
632
+ overlap_ignore=strs(overlap.get("ignore"), "overlap.ignore"),
633
+ overlap_non_source=strs(overlap.get("non_source"), "overlap.non_source"),
634
+ authors=_parse_authors(raw.get("authors"), fail=fail, table=table, strs=strs, kind_of=kind_of, ident=ident),
635
+ drafted_by=drafted_by,
636
+ origin=origin,
637
+ )
638
+
639
+
640
+ OUTSIDE_QUESTIONS = [
641
+ "Is there a linked issue or earlier discussion showing the maintainers want this change?",
642
+ "Does it add dependencies, network calls, file writes, or subprocesses? Read each of those lines.",
643
+ ]
644
+ DEFAULT_KINDS = {
645
+ "internal": AuthorKind("internal", "internal", "internal", "internal"),
646
+ "external": AuthorKind(
647
+ "external", "external", "external", "external",
648
+ {"id": "external", "kind": "author", "message": "External contributor: look closely at new dependencies, network, file, and subprocess access"},
649
+ OUTSIDE_QUESTIONS,
650
+ ),
651
+ "first-time": AuthorKind(
652
+ "first-time", "first-time contributor", "first-time", "external",
653
+ {"id": "first-time", "kind": "author", "message": "First-time contributor: check that maintainers asked for this change"},
654
+ OUTSIDE_QUESTIONS,
655
+ ),
656
+ "bot": AuthorKind("bot", "bot", "bot", "bot"),
657
+ "unknown": AuthorKind("unknown", "unknown", "unknown", "external"),
658
+ } # fmt: skip
659
+ GROUPS = ("internal", "external", "bot")
660
+
661
+
662
+ def _parse_authors(data: Any, *, fail: Any, table: Any, strs: Any, kind_of: Any, ident: Any) -> Authors:
663
+ t = table(
664
+ data,
665
+ "authors",
666
+ {"internal", "external", "bots", "internal_teams", "internal_orgs", "association", "unknown", "kinds"},
667
+ )
668
+ kinds = {k: AuthorKind(**vars(v)) for k, v in DEFAULT_KINDS.items()}
669
+ for kid, spec in (t.get("kinds") or {}).items():
670
+ ident(kid, f"authors.kinds.{kid}")
671
+ s = table(spec, f"authors.kinds.{kid}", {"label", "badge", "group", "signal", "questions", "priority"})
672
+ base = kinds.get(kid) or AuthorKind(kid, kid, kid, "external")
673
+ group = s.get("group", base.group)
674
+ if group not in GROUPS:
675
+ raise fail(f"authors.kinds.{kid}.group must be one of {', '.join(GROUPS)}")
676
+ signal = s.get("signal", base.signal)
677
+ if signal is not None:
678
+ signal = table(signal, f"authors.kinds.{kid}.signal", {"id", "kind", "message"})
679
+ ident(signal.get("id"), f"authors.kinds.{kid}.signal")
680
+ kind_of(signal.get("kind"), f"authors.kinds.{kid}.signal")
681
+ kinds[kid] = AuthorKind(
682
+ kid, s.get("label", base.label), s.get("badge", base.badge), group, signal,
683
+ strs(s.get("questions"), f"authors.kinds.{kid}.questions") or base.questions, float(s.get("priority", base.priority)),
684
+ ) # fmt: skip
685
+ association = {**DEFAULT_ASSOCIATION, **(t.get("association") or {})}
686
+ unknown_kind = t.get("unknown", "external")
687
+ for name, kid in [*association.items(), ("unknown", unknown_kind)]:
688
+ if kid not in kinds:
689
+ raise fail(f"authors: {name} maps to unknown kind {kid!r}")
690
+ return Authors(
691
+ internal=strs(t.get("internal"), "authors.internal"),
692
+ external=strs(t.get("external"), "authors.external"),
693
+ bots=strs(t.get("bots"), "authors.bots"),
694
+ internal_teams=strs(t.get("internal_teams"), "authors.internal_teams"),
695
+ internal_orgs=strs(t.get("internal_orgs"), "authors.internal_orgs"),
696
+ association=association,
697
+ unknown=unknown_kind,
698
+ kinds=kinds,
699
+ )