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
@@ -0,0 +1,635 @@
1
+ """Onboarding and repo settings from the browser.
2
+
3
+ Everything here mirrors a CLI command (``readthrough onboard``, ``remove``, ``default``, editing config.toml), and
4
+ the page shows the CLI equivalent for each action. The server only calls this for requests that carry its
5
+ token and come from its own pages; on top of that, every input is validated here.
6
+
7
+ Kept out of the browser on purpose: ``agent_args`` (flags passed straight to a program the server
8
+ launches), the ``profile`` path override (makes the server read an arbitrary file), and ``port`` (changing
9
+ it from the page you're on breaks that page). The page shows them read-only with the CLI command.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import datetime as dt
15
+ import logging
16
+ import re
17
+ import shutil
18
+ import threading
19
+ import time
20
+ import tomllib
21
+ import uuid
22
+ from collections.abc import Callable
23
+ from pathlib import Path
24
+ from typing import Any
25
+ from urllib.parse import quote
26
+
27
+ from readthrough import forges, onboard, review
28
+ from readthrough.config import Config, ConfigError, Settings, guess_clone, remote_for
29
+ from readthrough.faults import ForgeError
30
+ from readthrough.forges import Forge
31
+ from readthrough.forges.github import signed_in_accounts
32
+ from readthrough.limits import BROWSER_EDITABLE_INTS, LOGIN_RE, MODEL_RE
33
+ from readthrough.process import run
34
+ from readthrough.profile import ProfileError, parse_profile, profile_sources, repo_profile_paths
35
+ from readthrough.registry import RegistryError
36
+
37
+ log = logging.getLogger(__name__)
38
+
39
+ EDITABLE_LISTS = ("internal_authors", "external_authors")
40
+
41
+
42
+ class SetupError(ValueError):
43
+ """A problem to show the user, as a 400."""
44
+
45
+
46
+ class Conflict(SetupError):
47
+ """config.toml changed since the page loaded it."""
48
+
49
+
50
+ class SetupService:
51
+ def __init__(
52
+ self, settings_loader: Callable[[], Settings], *, on_change: Callable[[], None] = lambda: None
53
+ ) -> None:
54
+ self.load = settings_loader
55
+ self.on_change = on_change
56
+ self._facts: dict[tuple[str, str | None, str | None], tuple[float, onboard.RepoFacts]] = {}
57
+ self._jobs: dict[str, dict[str, Any]] = {}
58
+ self._previews: dict[str, dict[str, Any]] = {}
59
+ self._lock = threading.Lock()
60
+ self._config_lock = threading.Lock()
61
+
62
+ # ---------------------------------------------------------------- routing
63
+
64
+ def get(self, path: str, query: dict[str, str]) -> Any:
65
+ if path == "/api/setup/state":
66
+ return self.state(query.get("repo"), query.get("forge"))
67
+ if m := re.fullmatch(r"/api/setup/jobs/([0-9a-f]{32})", path):
68
+ return self.job(m.group(1))
69
+ raise LookupError("not found")
70
+
71
+ def post(self, path: str, body: dict[str, Any]) -> Any:
72
+ actions: dict[str, Callable[[dict[str, Any]], Any]] = {
73
+ "/api/setup/inspect": self.inspect,
74
+ "/api/setup/clone": self.check_clone,
75
+ "/api/setup/draft": self.start_draft,
76
+ "/api/setup/check": self.check,
77
+ "/api/setup/preview": self.start_preview,
78
+ "/api/setup/save": self.save_profile,
79
+ "/api/setup/accept": self.accept,
80
+ "/api/setup/settings": self.save_settings,
81
+ "/api/setup/remove": self.remove,
82
+ }
83
+ if path not in actions:
84
+ raise LookupError("not found")
85
+ return actions[path](body)
86
+
87
+ def preview_payload(self, preview_id: str) -> dict[str, Any] | None:
88
+ with self._lock:
89
+ return self._previews.get(preview_id)
90
+
91
+ # ---------------------------------------------------------------- reading
92
+
93
+ def state(self, repo: str | None, forge: str | None = None) -> dict[str, Any]:
94
+ settings = self.load()
95
+ out: dict[str, Any] = {
96
+ "settings": {
97
+ "default_repo": settings.default_repo,
98
+ "port": settings.port,
99
+ "refresh_minutes": settings.refresh_minutes,
100
+ "version": _version(settings),
101
+ "path": str(settings.path),
102
+ },
103
+ "repos": [{**_repo_view(c), "cli_name": n} for n, c in zip(settings.names(), settings.all(), strict=True)],
104
+ "accounts": signed_in_accounts(),
105
+ "forges": [_forge_view(name) for name in forges.names()],
106
+ "runtime": _runtime_view(settings),
107
+ }
108
+ if repo:
109
+ forge_name, repo = _locator(repo, forge)
110
+ entry = settings.entry(repo, forge_name)
111
+ cfg = settings.config_for(repo, forge=forge_name)
112
+ cli_name = settings.display_name(cfg.slug) if entry is not None else cfg.repo
113
+ out["repo"] = {
114
+ **_repo_view(cfg),
115
+ "cli_name": cli_name,
116
+ "configured": entry is not None,
117
+ "auth": forges.make(cfg).describe_auth(), # resolves the credential once per process; no prompt
118
+ **self._profile_view(cfg),
119
+ }
120
+ return out
121
+
122
+ def _profile_view(self, cfg: Config, forge: Forge | None = None) -> dict[str, Any]:
123
+ try:
124
+ sources = profile_sources(cfg, forge)
125
+ except ForgeError:
126
+ sources = profile_sources(cfg)
127
+ if not sources:
128
+ return {"source": None, "sources": [], "profile_text": "", "editable": True}
129
+ first = sources[0]
130
+ return {
131
+ "source": {"kind": first.kind, "label": first.label},
132
+ "sources": [{"kind": s.kind, "label": s.label} for s in sources],
133
+ "profile_text": first.read(),
134
+ "editable": first.kind == "local",
135
+ }
136
+
137
+ def job(self, job_id: str) -> dict[str, Any]:
138
+ with self._lock:
139
+ job = self._jobs.get(job_id)
140
+ if job is None:
141
+ raise LookupError("no such job")
142
+ return {k: v for k, v in job.items() if k != "thread"}
143
+
144
+ # ---------------------------------------------------------------- repo, account, clone
145
+
146
+ def inspect(self, body: dict[str, Any]) -> dict[str, Any]:
147
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
148
+ account = _account(body.get("account"), forge_name)
149
+ settings = self.load()
150
+ cfg = settings.config_for(repo, forge=forge_name)
151
+ if account:
152
+ cfg.account = account
153
+ forge = forges.make(cfg)
154
+ try:
155
+ info = forge.repo_info()
156
+ except ForgeError as exc:
157
+ accounts = signed_in_accounts() if "accounts" in forge.capabilities else []
158
+ hint = f" Signed-in gh accounts: {', '.join(accounts)}; pick the one that can see it." if accounts else ""
159
+ raise SetupError(
160
+ f"Can't read {repo} on {forge.label}{' as ' + account if account else ''}: {exc.reason}.{hint}"
161
+ ) from exc
162
+ name = info.get("full_name") or repo
163
+ entry = settings.entry(name, forge_name) or {}
164
+ clone = entry.get("clone") or guess_clone(name, forge_name)
165
+ if name.lower() != repo.lower(): # the forge's own spelling of the name
166
+ cfg = settings.config_for(name, forge=forge_name)
167
+ if account:
168
+ cfg.account = account
169
+ forge = forges.make(cfg)
170
+ branch = info.get("default_branch") or "main"
171
+ profile_path = repo_profile_paths(forge)[0]
172
+ return {
173
+ "full_name": name,
174
+ "forge": forge_name,
175
+ "forge_label": forge.label,
176
+ "auth": forge.describe_auth(), # what Check access actually used, so the page can say so
177
+ "slug": cfg.slug,
178
+ "private": info.get("private", False),
179
+ "default_branch": branch,
180
+ "description": info.get("description") or "",
181
+ "configured": bool(entry),
182
+ "onboarded": cfg.onboarded,
183
+ "clone": str(clone) if clone else "",
184
+ "profile_path": profile_path,
185
+ "propose_url": forge.new_file_url(profile_path, branch),
186
+ **self._profile_view(cfg, forge),
187
+ }
188
+
189
+ def check_clone(self, body: dict[str, Any]) -> dict[str, Any]:
190
+ forge, repo = _locator(body.get("repo"), body.get("forge"))
191
+ clone = _clone_path(body.get("clone"))
192
+ if clone is None:
193
+ return {"ok": False, "message": "No clone: reviews and worktrees need one, but the map works without it."}
194
+ remotes = []
195
+ for line in run(["git", "-C", str(clone), "remote", "-v"], check=False).splitlines():
196
+ parts = line.split()
197
+ if len(parts) >= 2 and parts[0] not in (r["name"] for r in remotes):
198
+ remotes.append({"name": parts[0], "url": parts[1]})
199
+ detected = remote_for(clone, repo, forge)
200
+ return {
201
+ "ok": True,
202
+ "remotes": remotes,
203
+ "detected": detected,
204
+ "message": f"Git repo; remote '{detected}' points at {repo}."
205
+ if detected
206
+ else f"Git repo, but no remote points at {repo}; reviews would fetch PRs through 'origin'.",
207
+ }
208
+
209
+ # ---------------------------------------------------------------- drafting and checking
210
+
211
+ def start_draft(self, body: dict[str, Any]) -> dict[str, Any]:
212
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
213
+ account = _account(body.get("account"), forge_name)
214
+ mode = body.get("mode", "plain")
215
+ if mode not in ("plain", "model", "source"):
216
+ raise SetupError("mode must be plain, model, or source")
217
+ clone = _clone_path(body.get("clone"))
218
+ remote = _remote(body.get("remote"))
219
+ version = body.get("version")
220
+
221
+ def work(say: Callable[[str], None]) -> dict[str, Any]:
222
+ cfg = self._remember(repo, forge_name, account=account, clone=clone, remote=remote, version=version)
223
+ forge = forges.make(cfg)
224
+ facts = self._gather(cfg, forge, say)
225
+ if mode == "source":
226
+ view = self._profile_view(cfg, forge)
227
+ text = view["profile_text"]
228
+ if not text:
229
+ raise SetupError("There's no existing profile for this repo; draft one instead.")
230
+ elif mode == "model":
231
+ from readthrough import runtimes
232
+ from readthrough.onboard_model import model_draft
233
+
234
+ name, ok, why = runtimes.resolve(cfg.runtime, cfg.runtime_options)
235
+ if not ok:
236
+ raise SetupError(f"Drafting with a model needs a model runtime: {why}.")
237
+ engine = runtimes.make(name, cfg.runtime_options).describe()
238
+ say(f"The model is reading the repo ({engine}). This takes a few minutes.")
239
+ text = model_draft(cfg, forge, facts, on_progress=say)
240
+ else:
241
+ say("Drafting from the file tree, CODEOWNERS, docs, and recent PRs")
242
+ text = onboard.draft_profile(facts, title=cfg.repo.rsplit("/", 1)[-1])
243
+ return {"toml": text, "report": self._report(text, cfg, facts)}
244
+
245
+ return {"job": self._run_job(f"draft:{forge_name}/{repo.lower()}", work)}
246
+
247
+ def check(self, body: dict[str, Any]) -> dict[str, Any]:
248
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
249
+ text = _toml_text(body.get("toml"))
250
+ cfg = self.load().config_for(repo, forge=forge_name)
251
+ facts = self._gather(cfg, forges.make(cfg), log.info)
252
+ return self._report(text, cfg, facts)
253
+
254
+ def _report(self, text: str, cfg: Config, facts: onboard.RepoFacts) -> dict[str, Any]:
255
+ try:
256
+ raw = tomllib.loads(text)
257
+ profile = parse_profile(raw, origin="editor")
258
+ except (tomllib.TOMLDecodeError, ProfileError) as exc:
259
+ return {"valid": False, "error": str(exc).removeprefix("editor: ")}
260
+ if profile.repo.lower() != cfg.repo.lower():
261
+ return {"valid": False, "error": f"repo is {profile.repo!r}; this page is for {cfg.repo}"}
262
+ cov = onboard.measure(profile, facts, raw=raw, min_coverage=cfg.tuning.onboarding.min_coverage)
263
+ profile.authors.internal = [*profile.authors.internal, *cfg.internal_authors]
264
+ profile.authors.external = [*profile.authors.external, *cfg.external_authors]
265
+ labels = {c.id: c.label for c in profile.components}
266
+ return {
267
+ "valid": True,
268
+ "share": round(cov.share, 3),
269
+ "need": cov.need,
270
+ "basis": cov.basis,
271
+ "total": cov.total,
272
+ "busiest": [[labels.get(c, c), n] for c, n in cov.by_component.most_common(12) if c != "other"],
273
+ "unmapped": cov.unmapped_top,
274
+ "problems": cov.problems(),
275
+ "authors": onboard.author_table(profile, facts),
276
+ "layers": [{"id": layer.id, "label": layer.label, "source": layer.source} for layer in profile.layers],
277
+ "components": len(profile.components),
278
+ }
279
+
280
+ def start_preview(self, body: dict[str, Any]) -> dict[str, Any]:
281
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
282
+ text = _toml_text(body.get("toml"))
283
+
284
+ def work(say: Callable[[str], None]) -> dict[str, Any]:
285
+ from readthrough.build import build
286
+
287
+ cfg = self.load().config_for(repo, forge=forge_name)
288
+ profile = _parse(text)
289
+ say("Fetching open PRs and laying them out with this profile (no diffs, so it's quick)")
290
+ payload = build(cfg, with_diffs=False, profile=profile, draft=True, write=False)
291
+ preview_id = uuid.uuid4().hex
292
+ with self._lock:
293
+ self._previews[preview_id] = payload
294
+ while len(self._previews) > 5:
295
+ self._previews.pop(next(iter(self._previews)))
296
+ return {"url": f"/setup/preview/{preview_id}"}
297
+
298
+ return {"job": self._run_job(f"preview:{forge_name}/{repo.lower()}", work)}
299
+
300
+ # ---------------------------------------------------------------- writing
301
+
302
+ def save_profile(self, body: dict[str, Any]) -> dict[str, Any]:
303
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
304
+ text = _toml_text(body.get("toml"))
305
+ profile = _parse(text)
306
+ if profile.repo.lower() != repo.lower():
307
+ raise SetupError(f"The profile's repo is {profile.repo!r}, not {repo}")
308
+ cfg = self._remember(repo, forge_name, version=body.get("version"))
309
+ cfg.repo_dir.mkdir(parents=True, exist_ok=True)
310
+ path = cfg.local_profile_path
311
+ if path.exists():
312
+ if path.read_text(encoding="utf-8") == text:
313
+ return {"saved": str(path), "unchanged": True}
314
+ path.replace(path.with_name(f"profile.{dt.datetime.now().astimezone():%Y%m%d-%H%M%S}.toml"))
315
+ path.write_text(text, encoding="utf-8")
316
+ return {"saved": str(path)}
317
+
318
+ def accept(self, body: dict[str, Any]) -> dict[str, Any]:
319
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
320
+ if body.get("toml"):
321
+ self.save_profile(body)
322
+ settings = self.load()
323
+ cfg = settings.config_for(repo, forge=forge_name)
324
+ forge = forges.make(cfg)
325
+ sources = profile_sources(cfg, forge, first_only=True) # a local draft saves fetching the repo's file
326
+ if not sources:
327
+ raise SetupError("Draft or choose a profile first.")
328
+ report = self._report(sources[0].read(), cfg, self._gather(cfg, forge, log.info))
329
+ if not report.get("valid"):
330
+ raise SetupError(report.get("error", "The profile doesn't load."))
331
+ if report["problems"] and not body.get("force"):
332
+ raise SetupError("Not accepted yet: " + " ".join(report["problems"]))
333
+ with self._config_lock:
334
+ settings = self.load()
335
+ settings.upsert(cfg.slug, onboarded=dt.datetime.now(dt.UTC).isoformat(timespec="seconds"))
336
+ if not settings.default_repo and len(settings.repos) == 1:
337
+ settings.default_repo = cfg.repo
338
+ settings.save()
339
+ self.on_change()
340
+ return {"onboarded": True, "url": f"/r/{quote(cfg.slug)}/"}
341
+
342
+ def save_settings(self, body: dict[str, Any]) -> dict[str, Any]:
343
+ values = body.get("values") or {}
344
+ glob = body.get("global") or {}
345
+ if not isinstance(values, dict) or not isinstance(glob, dict):
346
+ raise SetupError("values and global must be objects")
347
+ with self._config_lock:
348
+ settings = self.load()
349
+ _check_version(settings, body.get("version"))
350
+ if body.get("repo"):
351
+ forge_name, repo = _locator(body["repo"], body.get("forge"))
352
+ if settings.entry(repo, forge_name) is None:
353
+ raise SetupError(f"{repo} isn't configured; onboard it first")
354
+ settings.upsert(repo, forge=forge_name, **_clean_repo_values(values, repo, forge_name))
355
+ if "default_repo" in glob:
356
+ default = glob["default_repo"]
357
+ if not isinstance(default, str | None):
358
+ raise SetupError("default_repo must be a repo name")
359
+ if default and settings.entry(default) is None:
360
+ raise SetupError(f"{default} isn't configured")
361
+ settings.default_repo = settings.display_name(default) if default else None
362
+ if "refresh_minutes" in glob:
363
+ settings.refresh_minutes = _int(glob["refresh_minutes"], "refresh_minutes", 1, 1440)
364
+ settings.save()
365
+ self.on_change()
366
+ return {"version": _version(self.load())}
367
+
368
+ def remove(self, body: dict[str, Any]) -> dict[str, Any]:
369
+ forge_name, repo = _locator(body.get("repo"), body.get("forge"))
370
+ with self._config_lock:
371
+ settings = self.load()
372
+ _check_version(settings, body.get("version"))
373
+ cfg = settings.config_for(repo, forge=forge_name)
374
+ if not settings.remove(cfg.slug):
375
+ raise SetupError(f"{repo} isn't configured")
376
+ settings.save()
377
+ self.on_change()
378
+ purged = False
379
+ if body.get("purge") is True and cfg.repo_dir.exists():
380
+ # Belt and braces for a delete: the locator was validated, and the directory must still be ours.
381
+ if not cfg.repo_dir.resolve().is_relative_to((cfg.home / "repos").resolve()):
382
+ raise SetupError(f"{cfg.repo_dir} isn't under {cfg.home / 'repos'}; nothing deleted")
383
+ if cfg.worktrees_dir.exists():
384
+ for wt in cfg.worktrees_dir.glob("pr-*"):
385
+ if wt.name[3:].isdigit():
386
+ review.remove_worktree(cfg, int(wt.name[3:]))
387
+ shutil.rmtree(cfg.repo_dir, ignore_errors=True)
388
+ purged = True
389
+ return {"removed": cfg.repo, "purged": purged}
390
+
391
+ # ---------------------------------------------------------------- helpers
392
+
393
+ def _remember(self, repo: str, forge: str, *, account: str | None = None, clone: Path | None = None,
394
+ remote: str | None = None, version: Any = None) -> Config: # fmt: skip
395
+ """Add the repo to config.toml (or update it), the way `readthrough onboard` does before drafting."""
396
+ with self._config_lock:
397
+ settings = self.load()
398
+ if version is not None:
399
+ _check_version(settings, version)
400
+ values: dict[str, Any] = {}
401
+ if account:
402
+ values["account"] = account
403
+ if clone:
404
+ values["clone"] = clone
405
+ values["remote"] = remote or remote_for(clone, repo, forge)
406
+ if settings.entry(repo, forge) is None or values:
407
+ settings.upsert(repo, forge=forge, **values)
408
+ settings.save()
409
+ return settings.config_for(repo, forge=forge)
410
+
411
+ def _gather(self, cfg: Config, forge: Forge, say: Callable[[str], None]) -> onboard.RepoFacts:
412
+ key = (cfg.slug.lower(), cfg.account, str(cfg.clone) if cfg.clone else None)
413
+ with self._lock:
414
+ cached = self._facts.get(key)
415
+ if cached and time.time() - cached[0] < cfg.tuning.onboarding.facts_cache_minutes * 60:
416
+ return cached[1]
417
+ say(f"Reading {cfg.repo}: recent merged {forge.pr_noun}s, the file tree, CODEOWNERS, and docs")
418
+ facts = onboard.gather(forge, clone=cfg.clone, sample=cfg.tuning.onboarding.merged_sample)
419
+ with self._lock:
420
+ self._facts[key] = (time.time(), facts)
421
+ return facts
422
+
423
+ def _run_job(self, key: str, work: Callable[[Callable[[str], None]], dict[str, Any]]) -> str:
424
+ with self._lock:
425
+ for job_id, job in self._jobs.items():
426
+ if job["key"] == key and job["status"] == "running":
427
+ return job_id
428
+ job_id = uuid.uuid4().hex
429
+ job: dict[str, Any] = {"key": key, "status": "running", "log": [], "result": None, "error": None}
430
+ self._jobs[job_id] = job
431
+ while len(self._jobs) > 20:
432
+ self._jobs.pop(next(iter(self._jobs)))
433
+
434
+ def say(message: str) -> None:
435
+ with self._lock:
436
+ job["log"].append(message)
437
+
438
+ def target() -> None:
439
+ try:
440
+ result = work(say)
441
+ with self._lock:
442
+ job.update(status="done", result=result)
443
+ except (SetupError, ConfigError, ProfileError, ForgeError, RuntimeError, ValueError) as exc:
444
+ with self._lock:
445
+ job.update(status="error", error=str(exc))
446
+ except Exception as exc:
447
+ log.exception("Setup job %s failed", key)
448
+ with self._lock:
449
+ job.update(status="error", error=f"Unexpected error: {exc}")
450
+
451
+ threading.Thread(target=target, daemon=True, name=f"setup:{key}").start()
452
+ return job_id
453
+
454
+
455
+ # ---------------------------------------------------------------- validation
456
+
457
+
458
+ def _locator(value: Any, forge: Any) -> tuple[str, str]:
459
+ """``(forge name, repo)`` from a request, checked against the forge's idea of a repo locator.
460
+
461
+ ``repo`` may be a ``forge/owner/name`` slug, in which case ``forge`` is redundant and must agree.
462
+ """
463
+ if not isinstance(value, str) or not value.strip() or len(value) > 300:
464
+ raise SetupError("Which repo?")
465
+ repo = value.strip().strip("/")
466
+ if forge is not None and not isinstance(forge, str):
467
+ raise SetupError("forge must be a name")
468
+ forge = forge or None
469
+ try:
470
+ asked = forges.adapter(forge) if forge else None
471
+ except RegistryError as exc:
472
+ raise SetupError(str(exc)) from exc
473
+ head, _, rest = repo.partition("/")
474
+ # A slug (forge/owner/name) names its forge, unless the "forge" is really an owner who shares a forge's name
475
+ # (the whole string then has to be a valid locator for the forge that was asked for, or GitHub).
476
+ is_slug = head in forges.names() and bool(rest) and forges.validate_repo(head, rest) is None
477
+ if is_slug and (asked or forges.adapter("github")).validate_repo(repo) is None:
478
+ is_slug = False
479
+ if is_slug:
480
+ if forge and head != forge:
481
+ raise SetupError(f"{repo} names a {head} repo, but the request says {forge}")
482
+ forge, repo = head, rest
483
+ adapter = forges.adapter(forge or "github")
484
+ forge = adapter.name
485
+ problem = adapter.validate_repo(repo)
486
+ if problem:
487
+ raise SetupError(f"On {adapter.label}, a repo looks like {adapter.shape}: {problem}")
488
+ return forge, repo
489
+
490
+
491
+ def _account(value: Any, forge: str = "github") -> str | None:
492
+ if value in (None, ""):
493
+ return None
494
+ if "accounts" not in forges.adapter(forge).capabilities:
495
+ raise SetupError(f"Accounts apply to GitHub repos; {forges.adapter(forge).label} uses its own token")
496
+ if not isinstance(value, str) or not LOGIN_RE.match(value):
497
+ raise SetupError("That isn't a GitHub login")
498
+ if value not in signed_in_accounts():
499
+ raise SetupError(f"gh isn't signed in as {value}. Run `gh auth login` for it first.")
500
+ return value
501
+
502
+
503
+ def _clone_path(value: Any) -> Path | None:
504
+ if value in (None, ""):
505
+ return None
506
+ if not isinstance(value, str) or "\0" in value or len(value) > 400:
507
+ raise SetupError("That isn't a usable path")
508
+ path = Path(value).expanduser()
509
+ if not path.is_absolute():
510
+ raise SetupError("Give the clone's full path")
511
+ if not (path / ".git").exists():
512
+ raise SetupError(f"{path} isn't a git clone (no .git)")
513
+ return path.resolve()
514
+
515
+
516
+ def _remote(value: Any) -> str | None:
517
+ if value in (None, ""):
518
+ return None
519
+ if not isinstance(value, str) or not re.fullmatch(r"[\w.-]{1,60}", value):
520
+ raise SetupError("That isn't a git remote name")
521
+ return value
522
+
523
+
524
+ def _toml_text(value: Any) -> str:
525
+ if not isinstance(value, str) or not value.strip():
526
+ raise SetupError("The profile is empty")
527
+ if len(value) > 200_000:
528
+ raise SetupError("The profile is too big")
529
+ return value
530
+
531
+
532
+ def _parse(text: str) -> Any:
533
+ try:
534
+ return parse_profile(tomllib.loads(text), origin="editor")
535
+ except (tomllib.TOMLDecodeError, ProfileError) as exc:
536
+ raise SetupError(str(exc)) from exc
537
+
538
+
539
+ def _int(value: Any, name: str, low: int, high: int) -> int:
540
+ if isinstance(value, bool) or not isinstance(value, int | str) or not str(value).strip().isdigit():
541
+ raise SetupError(f"{name} must be a whole number")
542
+ number = int(value)
543
+ if not low <= number <= high:
544
+ raise SetupError(f"{name} must be between {low} and {high}")
545
+ return number
546
+
547
+
548
+ def _clean_repo_values(values: dict[str, Any], repo: str, forge: str = "github") -> dict[str, Any]:
549
+ out: dict[str, Any] = {}
550
+ for key, value in values.items():
551
+ if key in BROWSER_EDITABLE_INTS:
552
+ out[key] = None if value in (None, "") else _int(value, key, *BROWSER_EDITABLE_INTS[key])
553
+ elif key in EDITABLE_LISTS:
554
+ if not isinstance(value, list) or not all(isinstance(v, str) and LOGIN_RE.match(v) for v in value):
555
+ raise SetupError(f"{key} must be a list of logins")
556
+ out[key] = sorted(set(value), key=str.lower) or None
557
+ elif key == "study_model":
558
+ if value not in (None, "") and not (isinstance(value, str) and MODEL_RE.match(value)):
559
+ raise SetupError("That isn't a model name")
560
+ out[key] = value or None
561
+ elif key == "account":
562
+ out[key] = _account(value, forge)
563
+ elif key == "clone":
564
+ out[key] = _clone_path(value)
565
+ elif key == "remote":
566
+ out[key] = _remote(value)
567
+ else:
568
+ raise SetupError(f"{key} can't be changed from the browser")
569
+ if out.get("clone") and "remote" not in out:
570
+ out["remote"] = remote_for(out["clone"], repo, forge)
571
+ return out
572
+
573
+
574
+ def _version(settings: Settings) -> str:
575
+ try:
576
+ return str(settings.path.stat().st_mtime_ns)
577
+ except FileNotFoundError:
578
+ return "0"
579
+
580
+
581
+ def _check_version(settings: Settings, version: Any) -> None:
582
+ if version is not None and str(version) != _version(settings):
583
+ raise Conflict(
584
+ "config.toml changed since this page loaded it (maybe from the command line). Reload and try again."
585
+ )
586
+
587
+
588
+ def _forge_view(name: str) -> dict[str, Any]:
589
+ plugin = forges.FORGES.get(name)
590
+ adapter = plugin.impl
591
+ return {
592
+ "name": name,
593
+ "label": adapter.label,
594
+ "summary": plugin.summary,
595
+ "pr_noun": adapter.pr_noun,
596
+ "shape": adapter.shape,
597
+ "accounts": "accounts" in adapter.capabilities,
598
+ "access": adapter.access,
599
+ "credentials": list(adapter.credentials),
600
+ }
601
+
602
+
603
+ def _runtime_view(settings: Settings) -> dict[str, Any]:
604
+ """The model runtime drafting and studying would use: its name, whether it can run (and why not), and its
605
+ own description, so the page can say which model reads the repo before the user asks it to."""
606
+ from readthrough import runtimes
607
+
608
+ name, ok, why = runtimes.resolve(settings.runtime, settings.runtime_options)
609
+ describe = runtimes.make(name, settings.runtime_options).describe() if ok else ""
610
+ return {"name": name, "available": ok, "reason": why, "describe": describe}
611
+
612
+
613
+ def _repo_view(cfg: Config) -> dict[str, Any]:
614
+ built = cfg.data_path.stat().st_mtime if cfg.data_path.exists() else None
615
+ adapter = forges.adapter(cfg.forge)
616
+ return {
617
+ "name": cfg.repo,
618
+ "forge": cfg.forge,
619
+ "forge_label": adapter.label,
620
+ "slug": cfg.slug,
621
+ "pr_noun": adapter.pr_noun,
622
+ "onboarded": cfg.onboarded,
623
+ "account": cfg.account,
624
+ "clone": str(cfg.clone) if cfg.clone else "",
625
+ "remote": cfg.remote,
626
+ "session_minutes": cfg.session_minutes,
627
+ "limit": cfg.limit,
628
+ "study_model": cfg.study_model,
629
+ "internal_authors": cfg.internal_authors,
630
+ "external_authors": cfg.external_authors,
631
+ "agent_args": cfg.agent_args,
632
+ "profile_override": str(cfg.profile) if cfg.profile else None,
633
+ "built": built,
634
+ "data_dir": str(cfg.repo_dir),
635
+ }