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/cli.py ADDED
@@ -0,0 +1,958 @@
1
+ """Command-line entry point: ``readthrough [--repo owner/name] <command>``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import datetime as dt
7
+ import json
8
+ import logging
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import time
13
+ import webbrowser
14
+ from importlib.resources import files
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from readthrough import __version__, agents, forges, ledger, logs, review, study, system, usage
19
+ from readthrough.analyze import is_newsworthy
20
+ from readthrough.config import Config, ConfigError, Settings, guess_clone, load_settings, remote_for
21
+ from readthrough.faults import ForgeError
22
+ from readthrough.forges.github import signed_in_accounts
23
+ from readthrough.process import run
24
+ from readthrough.profile import ProfileError
25
+
26
+ log = logging.getLogger("readthrough")
27
+ SKILL_NAME = agents.SKILL_NAME
28
+
29
+
30
+ def _setup_logging(settings: Settings, *, verbose: bool, command: str) -> None:
31
+ """readthrough.log always gets timestamped lines. The console does too for the server; commands print plainly."""
32
+ settings.home.mkdir(parents=True, exist_ok=True)
33
+ for stream in (sys.stdout, sys.stderr):
34
+ reconfigure = getattr(stream, "reconfigure", None)
35
+ if reconfigure is not None:
36
+ reconfigure(encoding="utf-8", errors="replace")
37
+ logs.setup(
38
+ settings.log_path, settings.tuning.logging, verbose=verbose, console="full" if command == "serve" else "plain"
39
+ )
40
+
41
+
42
+ def _say(text: str = "") -> None:
43
+ if sys.stdout is not None:
44
+ print(text)
45
+
46
+
47
+ def _open(target: str | Path) -> None:
48
+ webbrowser.open(Path(target).resolve().as_uri() if isinstance(target, Path) else target)
49
+
50
+
51
+ def _open_dashboard(cfg: Config) -> None:
52
+ """Prefer the live server when it's running and serving this repo; fall back to the static file."""
53
+ from readthrough.build import mark_seen
54
+ from readthrough.serve import server_alive, server_url
55
+
56
+ info = server_alive(cfg.port)
57
+ if info and cfg.repo.lower() in (r.lower() for r in info.get("repos", [])):
58
+ _open(server_url(cfg)) # the server records the visit itself
59
+ else:
60
+ _open(cfg.dashboard_path)
61
+ mark_seen(cfg)
62
+
63
+
64
+ def _head_for(cfg: Config, number: int) -> str:
65
+ if not cfg.data_path.exists():
66
+ return ""
67
+ data = json.loads(cfg.data_path.read_text(encoding="utf-8"))
68
+ return next((p["head"] for p in data["prs"] if p["number"] == number), "")
69
+
70
+
71
+ def _require_onboarded(cfg: Config) -> None:
72
+ if not cfg.onboarded:
73
+ raise ConfigError(f"{cfg.repo} isn't onboarded yet. Run `readthrough onboard {cfg.repo}`.")
74
+
75
+
76
+ def _bundled_skill() -> str:
77
+ return files("readthrough").joinpath("assets/SKILL.md").read_text(encoding="utf-8")
78
+
79
+
80
+ # ---------------------------------------------------------------- per-repo commands
81
+
82
+
83
+ def cmd_build(settings: Settings, args: argparse.Namespace) -> int:
84
+ from readthrough.build import BuildFailed, build
85
+
86
+ configs = [c for c in settings.all() if c.onboarded] if args.all else [settings.config_for(args.repo)]
87
+ if not configs:
88
+ log.error("No onboarded repos. Onboard one with `readthrough onboard owner/name`.")
89
+ return 1
90
+ failures = 0
91
+ for cfg in configs:
92
+ try:
93
+ _require_onboarded(cfg)
94
+ payload = build(cfg, with_diffs=not args.no_diffs)
95
+ except BuildFailed as exc: # already logged, with its error id
96
+ _say(f"{cfg.repo}: the build failed [error {exc.error_id}]. Details are in {settings.log_path}.")
97
+ failures += 1
98
+ continue
99
+ except (ProfileError, ConfigError) as exc:
100
+ log.error("%s: %s", cfg.repo, exc)
101
+ failures += 1
102
+ continue
103
+ _summarize(cfg, payload)
104
+ if args.open == "always" or (args.open == "auto" and is_newsworthy(payload["news"])):
105
+ _open_dashboard(cfg)
106
+ return 1 if failures else 0
107
+
108
+
109
+ def _summarize(cfg: Config, payload: dict[str, Any]) -> None:
110
+ lanes: dict[str, int] = {}
111
+ for p in payload["prs"]:
112
+ lanes[p["lane"]] = lanes.get(p["lane"], 0) + 1
113
+ news = payload["news"]
114
+ log.info(
115
+ "%s: %d open PRs | %s", cfg.repo, len(payload["prs"]), " | ".join(f"{k}: {v}" for k, v in sorted(lanes.items()))
116
+ )
117
+ log.info(
118
+ "%d review sessions planned, %d min for the ready lane",
119
+ len(payload["sessions"]),
120
+ sum(s["minutes"] for s in payload["sessions"]),
121
+ )
122
+ if news["since"]:
123
+ log.info(
124
+ "Since you last looked: %d new, %d closed, %d need you, %d changed after your review",
125
+ len(news["opened"]), len(news["closed"]), len(news["needs_you"]), len(news["changed_after_review"]),
126
+ ) # fmt: skip
127
+ if payload.get("drift"):
128
+ d = payload["drift"]
129
+ log.warning("Map drift: only %d%% of open-PR churn maps to a component (unmapped: %s). Run `readthrough onboard %s --update`.",
130
+ d["coverage"] * 100, ", ".join(p for p, _ in d["unmapped"]), cfg.repo) # fmt: skip
131
+ log.info("Dashboard: %s", cfg.dashboard_path)
132
+
133
+
134
+ def cmd_serve(settings: Settings, args: argparse.Namespace) -> int:
135
+ from readthrough.serve import base_url, serve, server_alive
136
+
137
+ def with_overrides(loaded: Settings) -> Settings:
138
+ """Command-line options win over config.toml, including when the server reloads it."""
139
+ if args.port:
140
+ loaded.port = args.port
141
+ if args.interval:
142
+ loaded.refresh_minutes = args.interval
143
+ return loaded
144
+
145
+ settings = with_overrides(settings)
146
+ if server_alive(settings.port):
147
+ log.info("Already running at %s", base_url(settings.port))
148
+ if args.open:
149
+ _open(base_url(settings.port))
150
+ return 0
151
+ if not any(c.onboarded for c in settings.all()):
152
+ log.warning("No onboarded repos yet; the server will pick them up as you onboard them.")
153
+ serve(
154
+ settings, with_diffs=not args.no_diffs, settings_loader=lambda: with_overrides(load_settings(args.home)),
155
+ on_ready=(lambda: _open(base_url(settings.port))) if args.open else None,
156
+ ) # fmt: skip
157
+ return 0
158
+
159
+
160
+ def cmd_open(settings: Settings, args: argparse.Namespace) -> int:
161
+ cfg = settings.config_for(args.repo)
162
+ from readthrough.serve import server_alive
163
+
164
+ if not cfg.dashboard_path.exists() and not server_alive(cfg.port):
165
+ log.error("No dashboard for %s yet. Run `readthrough build` or `readthrough serve` first.", cfg.repo)
166
+ return 1
167
+ _open_dashboard(cfg)
168
+ return 0
169
+
170
+
171
+ def cmd_brief(settings: Settings, args: argparse.Namespace) -> int:
172
+ cfg = settings.config_for(args.repo)
173
+ path = cfg.briefs_dir / f"pr-{args.pr}.md"
174
+ if not path.exists():
175
+ log.error("No brief for %s#%d. Run `readthrough build` (is the PR still open?).", cfg.repo, args.pr)
176
+ return 1
177
+ _say(str(path) if args.path else path.read_text(encoding="utf-8"))
178
+ return 0
179
+
180
+
181
+ def cmd_ledger(settings: Settings, args: argparse.Namespace) -> int:
182
+ cfg = settings.config_for(args.repo)
183
+ if args.clear:
184
+ ledger.clear_status(cfg.ledger_path, args.pr)
185
+ _say(f"#{args.pr}: status cleared")
186
+ return 0
187
+ if args.status is None and args.note is None:
188
+ entry = ledger.load(cfg.ledger_path).get(str(args.pr))
189
+ _say(str(entry) if entry else f"No ledger entry for #{args.pr}")
190
+ return 0
191
+ entry = ledger.record(cfg.ledger_path, args.pr, status=args.status, note=args.note, head=_head_for(cfg, args.pr))
192
+ _say(f"#{args.pr}: {entry.get('status', '(no status)')}")
193
+ return 0
194
+
195
+
196
+ def cmd_study(settings: Settings, args: argparse.Namespace) -> int:
197
+ cfg = settings.config_for(args.repo)
198
+ adds: list[tuple[str, Any]] = [
199
+ (k, getattr(args, k)) for k in ("prediction", "teachback", "note") if getattr(args, k)
200
+ ]
201
+ if args.finding:
202
+ severity, _, summary = args.finding.partition(":")
203
+ path, _, line = (args.at or "").partition(":")
204
+ fields: dict[str, Any] = {"severity": severity.strip(), "summary": summary.strip()}
205
+ if path:
206
+ fields["path"] = path
207
+ if line.isdigit():
208
+ fields["line"] = int(line)
209
+ adds.append(("finding", fields))
210
+ for kind, value in adds:
211
+ entry_fields = value if isinstance(value, dict) else {"text": value}
212
+ by = "you" if kind in ("prediction", "teachback") else args.by
213
+ entry = study.append(cfg, args.pr, kind, by=by, **entry_fields)
214
+ _say(f"#{args.pr}: added {kind} #{entry['id']}")
215
+ if adds:
216
+ study.refresh_brief(cfg, args.pr)
217
+ return 0
218
+ appendix = study.render_appendix(study.load(cfg, args.pr))
219
+ _say(appendix.replace(study.MARKER, "").strip() if appendix else f"No study log for #{args.pr} yet.")
220
+ return 0
221
+
222
+
223
+ def cmd_review(settings: Settings, args: argparse.Namespace) -> int:
224
+ cfg = settings.config_for(args.repo)
225
+ entry = ledger.load(cfg.ledger_path).get(str(args.pr))
226
+ launch = review.plan_review(cfg, args.pr, ledger_entry=entry, fresh=args.fresh)
227
+ if args.fresh:
228
+ ledger.record(cfg.ledger_path, args.pr, session=launch.session_id)
229
+ if args.vscode:
230
+ prompt = review.review_prompt(cfg, args.pr, cfg.briefs_dir / f"pr-{args.pr}.md")
231
+ existing = review.agent_for(cfg, launch.session_id).editor_url(launch.session_id) if launch.resuming else None
232
+ _open(existing or review.vscode_new_session_url(prompt, cfg.clone))
233
+ return 0
234
+ verb = "Resuming" if launch.resuming else "Starting"
235
+ log.info("%s %s session %s for %s#%d in %s", verb, launch.agent, launch.session_id, cfg.repo, args.pr, launch.cwd)
236
+ if args.print:
237
+ _say(subprocess.list2cmdline(launch.argv) if sys.platform == "win32" else " ".join(launch.argv))
238
+ return 0
239
+ if args.here:
240
+ return subprocess.call(launch.argv, cwd=launch.cwd)
241
+ terminal = review.launch_in_terminal(launch, cfg)
242
+ log.info("Opened it in %s", terminal)
243
+ return 0
244
+
245
+
246
+ def cmd_worktree(settings: Settings, args: argparse.Namespace) -> int:
247
+ cfg = settings.config_for(args.repo)
248
+ if args.remove:
249
+ _say("removed" if review.remove_worktree(cfg, args.pr) else "no worktree")
250
+ return 0
251
+ path, merge_base, head = review.ensure_worktree(cfg, args.pr, base=args.base)
252
+ _say(
253
+ f'worktree {path}\nhead {head}\nmerge-base {merge_base}\ndiff git -C "{path}" diff {merge_base}..HEAD'
254
+ )
255
+ return 0
256
+
257
+
258
+ def cmd_handle_url(settings: Settings, args: argparse.Namespace) -> int:
259
+ """Entry point for the readthrough:// protocol. Runs windowless, so errors go to a message box."""
260
+ log.info("URL: %s", args.url)
261
+ try:
262
+ target = review.parse_readthrough_url(args.url, allowed_repos=[c.slug for c in settings.all() if c.onboarded])
263
+ if target.repo is None:
264
+ from readthrough.serve import base_url, server_alive
265
+
266
+ if server_alive(settings.port):
267
+ _open(base_url(settings.port))
268
+ return 0
269
+ return cmd_open(settings, argparse.Namespace(repo=None))
270
+ ns = argparse.Namespace(repo=target.repo, pr=target.number, fresh=False, vscode=False, print=False, here=False,
271
+ all=False, no_diffs=False, open="always") # fmt: skip
272
+ if target.action == "review":
273
+ return cmd_review(settings, ns)
274
+ if target.action == "refresh":
275
+ return cmd_build(settings, ns)
276
+ return cmd_open(settings, ns)
277
+ except Exception as exc:
278
+ log.exception("URL handler failed")
279
+ system.message_box("readthrough", f"{exc}\n\nDetails: {settings.log_path}")
280
+ return 1
281
+
282
+
283
+ # ---------------------------------------------------------------- onboarding and repos
284
+
285
+
286
+ def cmd_onboard(settings: Settings, args: argparse.Namespace) -> int:
287
+ from readthrough import onboard
288
+ from readthrough.profile import profile_sources
289
+
290
+ repo = args.target or args.repo or settings.default_repo
291
+ if not repo:
292
+ log.error("Which repo? readthrough onboard owner/name (or --forge gitlab group/project, and so on)")
293
+ return 1
294
+ existing = settings.entry(repo, args.forge) or {}
295
+ forge_name = existing.get("forge") or args.forge
296
+ repo = existing.get("name", repo)
297
+ clone = (
298
+ Path(args.clone).expanduser()
299
+ if args.clone
300
+ else (Path(existing["clone"]) if existing.get("clone") else guess_clone(repo, forge_name or "github"))
301
+ )
302
+ account = args.account or existing.get("account")
303
+ cfg = settings.config_for(repo, forge=forge_name)
304
+ cfg.account = account
305
+ forge = forges.make(cfg)
306
+ try:
307
+ info = forge.repo_info()
308
+ except ForgeError as exc:
309
+ log.error("Can't read %s on %s%s: %s", repo, forge.label, f" as {account}" if account else "", exc.reason)
310
+ accounts = signed_in_accounts() if "accounts" in forge.capabilities else []
311
+ if accounts:
312
+ log.error("Signed-in gh accounts: %s. Pick one with --account.", ", ".join(accounts))
313
+ return 1
314
+ full_name = info.get("full_name") or repo
315
+ if full_name.lower() != repo.lower() and existing:
316
+ log.error("%s now lives at %s. Remove it and onboard the new name.", repo, full_name)
317
+ return 1
318
+ repo = full_name
319
+ remote = args.remote or existing.get("remote") or (remote_for(clone, repo, forge.name) if clone else None)
320
+ settings.upsert(repo, forge=forge.name, clone=clone, account=account, remote=remote)
321
+ cfg = settings.config_for(repo, forge=forge.name)
322
+ forge = forges.make(cfg)
323
+ if clone is None:
324
+ log.info("No local clone found (looked in ~/src and ~/repos). Reviews need one; set it with --clone.")
325
+
326
+ log.info("Looking at %s: recent merged %ss, the file tree, CODEOWNERS, and docs...", repo, forge.pr_noun)
327
+ facts = onboard.gather(forge, clone=clone, sample=cfg.tuning.onboarding.merged_sample)
328
+ sources = profile_sources(cfg, forge)
329
+
330
+ if args.assisted:
331
+ from readthrough.onboard_model import model_draft
332
+
333
+ _write_profile(cfg, model_draft(cfg, forge, facts, on_progress=lambda m: log.info(" %s", m)))
334
+ sources = profile_sources(cfg, forge)
335
+ elif args.update or args.draft or not sources:
336
+ if cfg.local_profile_path.exists() and not (args.update or args.force):
337
+ log.info("Keeping your draft at %s (pass --update to redraft it).", cfg.local_profile_path)
338
+ else:
339
+ _write_profile(cfg, onboard.draft_profile(facts, title=repo.rsplit("/", 1)[-1]))
340
+ sources = profile_sources(cfg, forge)
341
+ source = sources[0]
342
+ log.info("Profile: %s", source.label)
343
+
344
+ try:
345
+ profile = source.load()
346
+ except ProfileError as exc:
347
+ log.error("The profile doesn't load: %s", exc)
348
+ settings.save()
349
+ return 1
350
+ cov = onboard.measure(profile, facts, raw=_raw_profile(source), min_coverage=cfg.tuning.onboarding.min_coverage)
351
+ _say(onboard.report(cov, profile, onboard.author_table(profile, facts)))
352
+
353
+ if args.preview:
354
+ from readthrough.build import build
355
+
356
+ payload = build(cfg, with_diffs=not args.no_diffs, profile=profile, draft=not cfg.onboarded)
357
+ _summarize(cfg, payload)
358
+ _open(cfg.dashboard_path)
359
+
360
+ if args.accept:
361
+ if cov.problems() and not args.force:
362
+ log.error("Not accepted. Fix the items above, or pass --force to accept anyway.")
363
+ settings.save()
364
+ return 1
365
+ settings.upsert(cfg.slug, onboarded=dt.datetime.now(dt.UTC).isoformat(timespec="seconds"))
366
+ if not settings.default_repo and len(settings.repos) == 1:
367
+ settings.default_repo = repo
368
+ settings.save()
369
+ name = settings.display_name(cfg.slug)
370
+ _say(
371
+ f"\n{repo} is onboarded. Build it with `readthrough --repo {name} build --open`; a running server picks it up on its own."
372
+ )
373
+ return 0
374
+ settings.save()
375
+ if not cfg.onboarded:
376
+ _say(f"\nNext: edit {source.label}, re-check with `readthrough onboard {repo}`,"
377
+ f" look at it with `--preview`, and finish with `--accept`.") # fmt: skip
378
+ return 0
379
+
380
+
381
+ def _write_profile(cfg: Config, text: str) -> None:
382
+ cfg.repo_dir.mkdir(parents=True, exist_ok=True)
383
+ if cfg.local_profile_path.exists():
384
+ backup = cfg.local_profile_path.with_name(f"profile.{dt.datetime.now().astimezone():%Y%m%d-%H%M%S}.toml")
385
+ cfg.local_profile_path.replace(backup)
386
+ log.info("Saved the previous profile as %s", backup.name)
387
+ cfg.local_profile_path.write_text(text, encoding="utf-8")
388
+ log.info("Wrote a draft profile to %s", cfg.local_profile_path)
389
+
390
+
391
+ def _raw_profile(source: Any) -> dict[str, Any] | None:
392
+ """The raw TOML of a profile you're editing, so onboarding can see what you haven't filled in yet."""
393
+ import tomllib
394
+
395
+ if source.kind in ("local", "explicit") and source.path is not None:
396
+ return tomllib.loads(source.path.read_text(encoding="utf-8"))
397
+ return None # shared and in-repo profiles are someone's considered map
398
+
399
+
400
+ def cmd_repos(settings: Settings, args: argparse.Namespace) -> int:
401
+ from readthrough.profile import profile_sources
402
+
403
+ if not settings.repos:
404
+ _say("No repos yet. Onboard one with `readthrough onboard owner/name`.")
405
+ return 0
406
+ default = settings.entry(settings.default_repo) if settings.default_repo else None
407
+ for name, cfg in zip(settings.names(), settings.all(), strict=True):
408
+ sources = profile_sources(cfg)
409
+ built = (
410
+ dt.datetime.fromtimestamp(cfg.data_path.stat().st_mtime, tz=dt.UTC).astimezone().strftime("%Y-%m-%d %H:%M")
411
+ if cfg.data_path.exists()
412
+ else "never"
413
+ )
414
+ star = "*" if default is not None and default is settings.entry(cfg.slug) else " "
415
+ _say(f"{star} {name:32} {'onboarded' if cfg.onboarded else 'NOT ONBOARDED':13} built {built:16} "
416
+ f"profile: {sources[0].label if sources else 'in-repo file or none'}"
417
+ + (f" (as {cfg.account})" if cfg.account else "")) # fmt: skip
418
+ return 0
419
+
420
+
421
+ def cmd_default(settings: Settings, args: argparse.Namespace) -> int:
422
+ cfg = settings.config_for(args.target)
423
+ if settings.entry(cfg.slug) is None:
424
+ log.error("%s isn't configured", args.target)
425
+ return 1
426
+ settings.default_repo = settings.display_name(cfg.slug)
427
+ settings.save()
428
+ _say(f"Default repo: {settings.default_repo}")
429
+ return 0
430
+
431
+
432
+ def cmd_remove(settings: Settings, args: argparse.Namespace) -> int:
433
+ cfg = settings.config_for(args.target)
434
+ if not settings.remove(cfg.slug):
435
+ log.error("%s isn't configured", args.target)
436
+ return 1
437
+ settings.save()
438
+ if args.purge and cfg.repo_dir.exists():
439
+ if cfg.worktrees_dir.exists():
440
+ for wt in cfg.worktrees_dir.glob("pr-*"):
441
+ if wt.name[3:].isdigit():
442
+ review.remove_worktree(cfg, int(wt.name[3:]))
443
+ shutil.rmtree(cfg.repo_dir, ignore_errors=True)
444
+ _say(f"Removed {cfg.repo} and deleted {cfg.repo_dir}")
445
+ else:
446
+ _say(f"Removed {cfg.repo} from the config. Its data is still in {cfg.repo_dir} (--purge deletes it).")
447
+ return 0
448
+
449
+
450
+ def cmd_profile(settings: Settings, args: argparse.Namespace) -> int:
451
+ from readthrough.profile import load_profile, profile_sources
452
+
453
+ if args.action == "check" and args.file:
454
+ try:
455
+ p = load_profile(Path(args.file))
456
+ except ProfileError as exc:
457
+ log.error("%s", exc)
458
+ return 1
459
+ _say(f"{args.file}: a valid profile for {p.repo} ({len(p.layers)} layers, {len(p.components)} components)")
460
+ return 0
461
+ cfg = settings.config_for(args.repo)
462
+ forge = forges.make(cfg)
463
+ sources = profile_sources(cfg, forge)
464
+ if not sources:
465
+ log.error("No profile for %s. Run `readthrough onboard %s`.", cfg.repo, cfg.repo)
466
+ return 1
467
+ if args.action == "sources":
468
+ for i, s in enumerate(sources):
469
+ _say(f"{'->' if i == 0 else ' '} {s.kind:9} {s.label}")
470
+ return 0
471
+ source = sources[0]
472
+ if args.action == "path":
473
+ _say(source.label)
474
+ return 0
475
+ if args.action == "export":
476
+ _say(source.read())
477
+ return 0
478
+ profile = source.load()
479
+ if args.action == "check":
480
+ from readthrough import onboard
481
+
482
+ facts = onboard.gather(forge, clone=cfg.clone, sample=cfg.tuning.onboarding.merged_sample)
483
+ cov = onboard.measure(profile, facts, raw=_raw_profile(source), min_coverage=cfg.tuning.onboarding.min_coverage)
484
+ _say(onboard.report(cov, profile, onboard.author_table(profile, facts)))
485
+ return 1 if cov.problems() else 0
486
+ _say(f"{profile.title} ({profile.repo}), from {profile.origin}")
487
+ _say(f"Layers: {', '.join(layer.label for layer in profile.layers)}")
488
+ _say(f"Components: {', '.join(c.label for c in profile.components)}")
489
+ if profile.contracts_source:
490
+ _say(f"Contracts: {profile.contracts_source}")
491
+ if profile.review_guidance_file:
492
+ _say(f"Review guidance file: {profile.review_guidance_file}")
493
+ if profile.review_guidance:
494
+ _say("Review guidance:\n" + profile.review_guidance.strip())
495
+ if profile.test_cmd:
496
+ _say("Test command: " + profile.test_cmd.replace("{clone}", str(cfg.clone or "<clone>")))
497
+ return 0
498
+
499
+
500
+ # ---------------------------------------------------------------- machine setup
501
+
502
+
503
+ def cmd_install(settings: Settings, args: argparse.Namespace) -> int:
504
+ home = settings.home if args.home_set else None
505
+ if args.what == "skill":
506
+ for dest in _skill_dirs(settings, args):
507
+ dest.mkdir(parents=True, exist_ok=True)
508
+ (dest / "SKILL.md").write_text(_bundled_skill(), encoding="utf-8")
509
+ _say(f"Installed the {SKILL_NAME} skill to {dest}")
510
+ elif args.what == "protocol":
511
+ _say(f"Registered {review.URL_SCHEME}:// -> {system.install_protocol()}")
512
+ _say("Rebuild the dashboards (`readthrough build --all`) so their buttons switch to one-click launch.")
513
+ elif args.what == "schedule":
514
+ command = system.install_schedule(at=args.at, days=args.days, open_mode=args.open, home=home)
515
+ _say(f"Scheduled '{system.TASK_NAME}' ({args.days} at {args.at}): {command}")
516
+ _say(f"Next run: {system.schedule_status().next_run or 'unknown'}")
517
+ elif args.what == "server":
518
+ from readthrough.serve import base_url
519
+
520
+ command = system.install_server_task(home=home)
521
+ _say(f"'{system.SERVER_TASK_NAME}' starts at logon and is starting now: {command}")
522
+ _say(f"Dashboard: {base_url(settings.port)}")
523
+ return 0
524
+
525
+
526
+ def _skill_dirs(settings: Settings, args: argparse.Namespace) -> list[Path]:
527
+ """Where to put the skill: an explicit directory, one agent's, or every installed agent's (else the default's)."""
528
+ if args.dest:
529
+ return [Path(args.dest)]
530
+ if args.agent:
531
+ return [agents.make(args.agent, settings.agent_options).skill_dir]
532
+ available = [a for a in agents.all_agents(settings.agent_options) if a.available()]
533
+ return [a.skill_dir for a in available or [agents.resolve(settings.agent, settings.agent_options)]]
534
+
535
+
536
+ def cmd_uninstall(settings: Settings, args: argparse.Namespace) -> int:
537
+ if args.what == "skill":
538
+ removed = False
539
+ for dest in _skill_dirs(settings, args):
540
+ removed = dest.exists() or removed
541
+ shutil.rmtree(dest, ignore_errors=True)
542
+ elif args.what == "protocol":
543
+ removed = system.uninstall_protocol()
544
+ elif args.what == "server":
545
+ removed = system.uninstall_schedule(system.SERVER_TASK_NAME)
546
+ else:
547
+ removed = system.uninstall_schedule()
548
+ _say("removed" if removed else "nothing to remove")
549
+ return 0
550
+
551
+
552
+ def cmd_config(settings: Settings, args: argparse.Namespace) -> int:
553
+ from readthrough.tuning import changed_from_defaults, defaults_text
554
+
555
+ if args.defaults:
556
+ _say(defaults_text())
557
+ return 0
558
+ if args.check:
559
+ # Loading already validated everything; reaching here means the file is fine.
560
+ _say(f"{settings.path}: valid ({len(settings.repos)} repos)")
561
+ return 0
562
+ if args.edit:
563
+ if not settings.path.exists():
564
+ settings.save()
565
+ _open(settings.path)
566
+ return 0
567
+ _say(f"{'config file':16} {settings.path} ({'exists' if settings.path.exists() else 'not created yet'})")
568
+ _say(f"{'default repo':16} {settings.default_repo or '-'}")
569
+ _say(f"{'port':16} {settings.port}")
570
+ _say(f"{'refresh minutes':16} {settings.refresh_minutes}")
571
+ changed = changed_from_defaults(settings.tuning)
572
+ _say(f"{'tuning':16} " + ("; ".join(f"{sec}: {', '.join(f'{k}={v}' for k, v in vals.items())}" for sec, vals in changed.items())
573
+ if changed else "all defaults (see `readthrough config --defaults`)")) # fmt: skip
574
+ configs = [settings.config_for(args.repo)] if args.repo else settings.all()
575
+ for cfg in configs:
576
+ _say(f"\n[{cfg.repo}]")
577
+ for key in ("clone", "remote", "account", "profile", "onboarded", "session_minutes", "limit",
578
+ "internal_authors", "external_authors", "study_model", "agent_args"): # fmt: skip
579
+ _say(f" {key:16} {getattr(cfg, key)}")
580
+ repo_changed = {k: v for k, v in changed_from_defaults(cfg.tuning).items() if changed.get(k) != v}
581
+ if repo_changed:
582
+ _say(
583
+ f" {'tuning':16} "
584
+ + "; ".join(
585
+ f"{sec}: {', '.join(f'{k}={v}' for k, v in vals.items())}" for sec, vals in repo_changed.items()
586
+ )
587
+ )
588
+ _say(f" {'data':16} {cfg.repo_dir}")
589
+ return 0
590
+
591
+
592
+ def cmd_doctor(settings: Settings, args: argparse.Namespace) -> int:
593
+ if args.bundle:
594
+ return _doctor_bundle(settings, args)
595
+ problems = 0
596
+
597
+ def check(ok: bool | None, label: str, detail: str, fix: str = "") -> None:
598
+ """ok=None marks something optional."""
599
+ nonlocal problems
600
+ problems += ok is False
601
+ mark = {True: "ok ", False: "XX ", None: "-- "}[ok]
602
+ hint = ("\n fix: " if ok is False else "\n optional: ") + fix if fix and not ok else ""
603
+ _say(f"{mark} {label:14} {detail}{hint}")
604
+
605
+ _say("This machine")
606
+ accounts = signed_in_accounts()
607
+ check(bool(accounts), "gh", f"signed in as {', '.join(accounts)}" if accounts else "not signed in", "gh auth login")
608
+ agent = agents.resolve(settings.agent, settings.agent_options)
609
+ check(agent.available(), "agent", agents.describe(settings.agent, settings.agent_options), agent.install_hint)
610
+ for other in agents.all_agents(settings.agent_options):
611
+ if other.available() or other.name == agent.name:
612
+ skill = other.skill_dir / "SKILL.md"
613
+ current = skill.exists() and skill.read_text(encoding="utf-8") == _bundled_skill()
614
+ check(current if other.available() else None, f"skill ({other.name})",
615
+ str(skill) if skill.exists() else "not installed", f"readthrough install skill --agent {other.name}") # fmt: skip
616
+ registered = system.registered_protocol_command()
617
+ check(
618
+ registered == system.handler_command(),
619
+ "protocol",
620
+ registered or "not registered",
621
+ "readthrough install protocol",
622
+ )
623
+ sched = system.schedule_status()
624
+ check(sched.installed, "schedule",
625
+ f"{sched.state}, next {sched.next_run}, last result {sched.last_result}" if sched.installed else "not installed",
626
+ "readthrough install schedule") # fmt: skip
627
+ from readthrough import assistants, terminals
628
+ from readthrough.serve import base_url, server_alive
629
+
630
+ live = server_alive(settings.port)
631
+ health = (live or {}).get("status") or {}
632
+ server_task = system.schedule_status(system.SERVER_TASK_NAME)
633
+ detail = f"running at {base_url(settings.port)}" if live else "not running"
634
+ check(
635
+ True if live else None,
636
+ "server",
637
+ detail + (" (starts at logon)" if server_task.installed else ""),
638
+ "readthrough install server",
639
+ )
640
+ assistant = assistants.resolve(
641
+ settings.assistant, runtime=settings.runtime, runtime_options=settings.runtime_options
642
+ )
643
+ chosen = ", chosen automatically" if settings.assistant == assistants.AUTO else ""
644
+ if not assistant.available:
645
+ check(
646
+ False, "assistant", f"{assistant.name}: {assistant.reason}", 'set assistant = "rules", or install [study]'
647
+ )
648
+ elif assistant.name == "rules" and settings.assistant == assistants.AUTO:
649
+ check(
650
+ None,
651
+ "assistant",
652
+ f"rules{chosen}",
653
+ "install the [study] extra, or set an API key, for an assistant that reads the code",
654
+ )
655
+ else:
656
+ check(True, "assistant", f"{assistant.name}{chosen}")
657
+ if assistant.available and assistant.name != "rules":
658
+ from readthrough import runtimes
659
+
660
+ name, ok, why = runtimes.resolve(settings.runtime, settings.runtime_options)
661
+ auto = ", chosen automatically" if settings.runtime == assistants.AUTO else ""
662
+ if ok:
663
+ check(True, "runtime", f"{runtimes.make(name, settings.runtime_options).describe()}{auto}")
664
+ else:
665
+ check(False, "runtime", f"{name}: {why}", "set runtime = ... in config.toml, or an API key")
666
+ terminal = terminals.describe(settings.terminal)
667
+ check(not terminal.startswith("No terminal"), "terminal", terminal, "set terminal = ... in config.toml")
668
+
669
+ configs = [settings.config_for(args.repo)] if args.repo else settings.all()
670
+ if not configs:
671
+ _say("\nNo repos yet. Onboard one with `readthrough onboard owner/name`.")
672
+ for cfg in configs:
673
+ _doctor_repo(cfg, check, accounts, health.get(cfg.slug))
674
+ return 1 if problems else 0
675
+
676
+
677
+ def _doctor_repo(cfg: Config, check: Any, accounts: list[str], live: dict[str, Any] | None = None) -> None:
678
+ from readthrough.profile import profile_sources
679
+
680
+ forge = forges.make(cfg)
681
+ _say(f"\n{cfg.repo}" + (f" ({forge.label})" if forge.name != forges.DEFAULT else ""))
682
+ if cfg.account:
683
+ check(cfg.account in accounts, "account", cfg.account, f"gh auth login (as {cfg.account})")
684
+ auth = forge.describe_auth()
685
+ check(None if auth.startswith("anonymous") else True, "auth", auth) # anonymous is fine for a public repo
686
+ try:
687
+ forge.repo_info()
688
+ check(True, "access", "can read the repo")
689
+ except ForgeError as exc:
690
+ fix = (
691
+ "pick a gh account that can read it: readthrough onboard REPO --account LOGIN"
692
+ if "accounts" in forge.capabilities
693
+ else forge.sign_in_hint()
694
+ )
695
+ check(False, "access", exc.reason[:120], fix)
696
+ clone_ok = bool(cfg.clone and (cfg.clone / ".git").exists())
697
+ check(
698
+ clone_ok if cfg.clone else None,
699
+ "clone",
700
+ str(cfg.clone or "not set"),
701
+ f"readthrough onboard {cfg.repo} --clone PATH",
702
+ )
703
+ if clone_ok and cfg.clone is not None:
704
+ remotes = run(["git", "-C", str(cfg.clone), "remote"], check=False).split()
705
+ remote = cfg.remote or remote_for(cfg.clone, cfg.repo, cfg.forge)
706
+ check(
707
+ remote in remotes,
708
+ "remote",
709
+ f"{remote} in {remotes}",
710
+ f"git -C {cfg.clone} remote add {remote} {forge.web_url()}",
711
+ )
712
+ sources = profile_sources(cfg)
713
+ check(
714
+ bool(sources) or None,
715
+ "profile",
716
+ sources[0].label if sources else f"none local (an in-repo {forge.config_dir}/readthrough.toml may apply)",
717
+ )
718
+ check(bool(cfg.onboarded), "onboarded", cfg.onboarded or "no", f"readthrough onboard {cfg.repo}")
719
+ if cfg.data_path.exists():
720
+ age = time.time() - cfg.data_path.stat().st_mtime
721
+ limit_h = cfg.tuning.freshness.doctor_build_hours
722
+ check(age < limit_h * 3600, "last build", f"{age / 3600:.1f} h ago", f"readthrough --repo {cfg.repo} build")
723
+ data = json.loads(cfg.data_path.read_text(encoding="utf-8"))
724
+ for w in data.get("warnings") or []:
725
+ check(None, "warning", w["message"])
726
+ drift = data.get("drift")
727
+ if drift:
728
+ check(
729
+ False,
730
+ "map",
731
+ f"only {drift['coverage']:.0%} of open-PR churn maps to a component",
732
+ f"readthrough onboard {cfg.repo} --update",
733
+ )
734
+ elif cfg.onboarded:
735
+ check(False, "last build", "never", f"readthrough --repo {cfg.repo} build --open")
736
+ if usage.ledger_path(cfg).exists():
737
+ month = dt.datetime.now(dt.UTC) - dt.timedelta(days=30)
738
+ summary = usage.summarize(usage.load(cfg), since=month)
739
+ payers = ", ".join(f"{p} ({n})" for p, n in sorted(summary["by_payer"].items()))
740
+ check(
741
+ None,
742
+ "model usage",
743
+ f"last 30 days: {usage.describe(summary)}" + (f"; billed to {payers}" if payers else ""),
744
+ )
745
+ if live and live.get("error"):
746
+ err = live["error"]
747
+ check(False, "server", f"{live['consecutive_failures']} failed refresh(es) in a row; last at {err['at']} "
748
+ f"during '{err['step']}' [error {err['id']}]: {err['message']}", f"look for error {err['id']} in readthrough.log") # fmt: skip
749
+
750
+
751
+ def _doctor_bundle(settings: Settings, args: argparse.Namespace) -> int:
752
+ """Everything needed to debug a problem, in one zip: config, recent logs, versions, and live health."""
753
+ import platform
754
+ import zipfile
755
+
756
+ from readthrough.serve import server_alive
757
+
758
+ out = settings.home / "bundles" / f"readthrough-debug-{dt.datetime.now().astimezone():%Y%m%d-%H%M%S}.zip"
759
+ out.parent.mkdir(parents=True, exist_ok=True)
760
+
761
+ def version(cmd: list[str]) -> str:
762
+ try:
763
+ return run(cmd, timeout=20).strip().splitlines()[0]
764
+ except (ForgeError, IndexError) as exc:
765
+ return f"unavailable ({exc})"
766
+
767
+ # The checkout this runs from, when it's an editable install; a wheel install just reports "unavailable".
768
+ sha = version(["git", "-C", str(Path(__file__).resolve().parents[2]), "rev-parse", "--short", "HEAD"])
769
+ info = {
770
+ "readthrough": __version__, "git_commit": sha, "python": sys.version, "platform": platform.platform(),
771
+ "gh": version(["gh", "--version"]), "copilot": version(["copilot", "--version"]), "claude": version(["claude", "--version"]),
772
+ "gh_accounts": signed_in_accounts(), "home": str(settings.home), "config": str(settings.path),
773
+ "repos": [{"name": c.slug, "onboarded": c.onboarded, "built": cfg_built(c)} for c in settings.all()],
774
+ } # fmt: skip
775
+ with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
776
+ z.writestr("versions.json", json.dumps(info, indent=2))
777
+ if settings.path.exists():
778
+ z.write(settings.path, "config.toml") # holds no secrets: tokens stay in gh's own store
779
+ for log_file in sorted(settings.home.glob("readthrough.log*")):
780
+ z.write(log_file, log_file.name)
781
+ z.writestr("health.json", json.dumps(server_alive(settings.port) or {"server": "not running"}, indent=2))
782
+ for cfg in settings.all():
783
+ if cfg.data_path.exists():
784
+ data = json.loads(cfg.data_path.read_text(encoding="utf-8"))
785
+ summary = {k: data.get(k) for k in ("schema", "version", "generated", "warnings", "stats", "drift")}
786
+ z.writestr(f"repos/{cfg.slug.replace('/', '__')}.json", json.dumps(summary, indent=2))
787
+ _say(
788
+ f"Wrote {out}\nIt has your config, recent logs, versions, and server health; no tokens. Attach it to a bug report."
789
+ )
790
+ return 0
791
+
792
+
793
+ def cfg_built(cfg: Config) -> str | None:
794
+ if not cfg.data_path.exists():
795
+ return None
796
+ return (
797
+ dt.datetime.fromtimestamp(cfg.data_path.stat().st_mtime, tz=dt.UTC).astimezone().isoformat(timespec="seconds")
798
+ )
799
+
800
+
801
+ # ---------------------------------------------------------------- parser
802
+
803
+
804
+ def build_parser(prog: str = "readthrough") -> argparse.ArgumentParser:
805
+ parser = argparse.ArgumentParser(prog=prog, description="Lay out a repo's open PRs and study them in depth.")
806
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
807
+ parser.add_argument("--home", type=Path, help="data directory (default ~/.readthrough)")
808
+ parser.add_argument("--repo", metavar="OWNER/NAME",
809
+ help="which repo (default: the default repo, or the only one); FORGE/OWNER/NAME when a name is on several forges") # fmt: skip
810
+ parser.add_argument("-v", "--verbose", action="store_true")
811
+ sub = parser.add_subparsers(dest="command", required=True, metavar="<command>")
812
+
813
+ p = sub.add_parser("onboard", help="map a repo's architecture so readthrough can lay out its PRs")
814
+ p.add_argument("target", nargs="?", metavar="OWNER/NAME")
815
+ p.add_argument("--forge", choices=forges.names(), default=None,
816
+ help=f"where the repo lives (default: {forges.DEFAULT}; a FORGE/OWNER/NAME target says it too)") # fmt: skip
817
+ p.add_argument("--clone", help="your local clone (default: looks in ~/src and ~/repos)")
818
+ p.add_argument("--remote", help="git remote that points at the repo (default: detected)")
819
+ p.add_argument("--account", help="gh account to read the repo as (for repos only one of your accounts can see)")
820
+ p.add_argument("--draft", action="store_true", help="draft a profile even if a shared or in-repo one exists")
821
+ p.add_argument("--update", action="store_true", help="redraft your local profile (keeps a backup)")
822
+ p.add_argument(
823
+ "--assisted",
824
+ action="store_true",
825
+ help="have the configured model read the repo and draft the profile (see `runtime`)",
826
+ )
827
+ p.add_argument("--preview", action="store_true", help="build the dashboard with this profile and open it")
828
+ p.add_argument("--accept", action="store_true", help="finish onboarding once the checks pass")
829
+ p.add_argument("--force", action="store_true", help="accept despite problems; or replace an existing draft")
830
+ p.add_argument("--no-diffs", action="store_true", help="--preview without diffs (faster)")
831
+ p.set_defaults(func=cmd_onboard)
832
+
833
+ sub.add_parser("repos", help="list configured repos").set_defaults(func=cmd_repos)
834
+ p = sub.add_parser("default", help="set the repo commands use when you leave out --repo")
835
+ p.add_argument("target", metavar="OWNER/NAME")
836
+ p.set_defaults(func=cmd_default)
837
+ p = sub.add_parser("remove", help="stop tracking a repo")
838
+ p.add_argument("target", metavar="OWNER/NAME")
839
+ p.add_argument("--purge", action="store_true", help="also delete its data, worktrees, and study logs")
840
+ p.set_defaults(func=cmd_remove)
841
+
842
+ p = sub.add_parser("profile", help="show, check, or export the repo's architecture profile")
843
+ p.add_argument("action", nargs="?", default="show", choices=("show", "check", "sources", "path", "export"))
844
+ p.add_argument("--file", help="check: validate this TOML file instead of the repo's profile")
845
+ p.set_defaults(func=cmd_profile)
846
+
847
+ p = sub.add_parser("build", help="fetch PRs and regenerate the dashboard and briefs")
848
+ p.add_argument("--all", action="store_true", help="every onboarded repo")
849
+ p.add_argument("--no-diffs", action="store_true", help="skip diffs (faster, no line heuristics)")
850
+ p.add_argument("--open", nargs="?", const="always", default="never", choices=("always", "auto", "never"),
851
+ help="open the dashboard afterwards; 'auto' opens only when something changed that needs you") # fmt: skip
852
+ p.set_defaults(func=cmd_build)
853
+
854
+ sub.add_parser("open", help="open the dashboard (the live one if the server is running)").set_defaults(
855
+ func=cmd_open
856
+ )
857
+
858
+ p = sub.add_parser("serve", help="run the live dashboard for every onboarded repo on localhost")
859
+ p.add_argument("--port", type=int, help="port (default from config, 8765)")
860
+ p.add_argument("--interval", type=int, help="minutes between refreshes (default from config, 10)")
861
+ p.add_argument("--no-diffs", action="store_true", help="skip diffs (faster, no line heuristics)")
862
+ p.add_argument("--open", action="store_true", help="open the dashboard once it's up")
863
+ p.set_defaults(func=cmd_serve)
864
+
865
+ p = sub.add_parser("brief", help="print a PR's study brief")
866
+ p.add_argument("pr", type=int)
867
+ p.add_argument("--path", action="store_true", help="print only the file path")
868
+ p.set_defaults(func=cmd_brief)
869
+
870
+ p = sub.add_parser("ledger", help="record (or show) what you did with a PR")
871
+ p.add_argument("pr", type=int)
872
+ p.add_argument("--status", choices=ledger.STATUSES)
873
+ p.add_argument("--note")
874
+ p.add_argument("--clear", action="store_true", help="forget the status (keeps the note and session)")
875
+ p.set_defaults(func=cmd_ledger)
876
+
877
+ p = sub.add_parser("study", help="show or add to a PR's study log (evidence of understanding)")
878
+ p.add_argument("pr", type=int)
879
+ p.add_argument("--prediction", help="what you expect the PR to do, written before reading it")
880
+ p.add_argument("--teachback", help="your summary of the whole PR, as if briefing a teammate")
881
+ p.add_argument("--note", help="a short insight to keep with the brief")
882
+ p.add_argument("--finding", metavar="SEVERITY:SUMMARY", help="e.g. 'major: retries swallow the original error'")
883
+ p.add_argument("--at", metavar="PATH:LINE", help="location for --finding")
884
+ p.add_argument(
885
+ "--by",
886
+ choices=("you", study.MODEL),
887
+ default="you",
888
+ help="who wrote a --note or --finding: you, or a model (a review agent)",
889
+ )
890
+ p.set_defaults(func=cmd_study)
891
+
892
+ p = sub.add_parser("review", help="start or resume the deep-review session for a PR (the configured review agent)")
893
+ p.add_argument("pr", type=int)
894
+ p.add_argument("--fresh", action="store_true", help="start a new session instead of resuming")
895
+ p.add_argument("--here", action="store_true", help="run in this terminal instead of opening a new one")
896
+ p.add_argument("--vscode", action="store_true", help="open in VS Code's Agents window instead of the CLI")
897
+ p.add_argument("--print", action="store_true", help="print the command instead of running it")
898
+ p.set_defaults(func=cmd_review)
899
+
900
+ p = sub.add_parser("worktree", help="check out a PR in its own git worktree")
901
+ p.add_argument("pr", type=int)
902
+ p.add_argument("--base", default="main")
903
+ p.add_argument("--remove", action="store_true")
904
+ p.set_defaults(func=cmd_worktree)
905
+
906
+ p = sub.add_parser("handle-url", help=argparse.SUPPRESS)
907
+ p.add_argument("url")
908
+ p.set_defaults(func=cmd_handle_url)
909
+
910
+ for name, func in (("install", cmd_install), ("uninstall", cmd_uninstall)):
911
+ p = sub.add_parser(
912
+ name,
913
+ help=f"{name} the review skill, the readthrough:// link handler, the daily refresh, or the live server",
914
+ )
915
+ p.add_argument("what", choices=("skill", "protocol", "schedule", "server"))
916
+ p.add_argument("--agent", choices=agents.AGENTS.names(),
917
+ help="skill: only this agent's skill directory (default: every installed agent's)") # fmt: skip
918
+ p.add_argument("--dest", help="skill: an explicit directory instead")
919
+ if name == "install":
920
+ p.add_argument("--at", default="08:30", help="schedule: time of day, HH:MM (default 08:30)")
921
+ p.add_argument("--days", choices=("daily", "weekdays"), default="weekdays")
922
+ p.add_argument("--open", choices=("always", "auto", "never"), default="auto",
923
+ help="schedule: when to open the dashboard (default auto)") # fmt: skip
924
+ p.set_defaults(func=func)
925
+
926
+ p = sub.add_parser("config", help="show the effective configuration")
927
+ p.add_argument("--edit", action="store_true", help="open config.toml")
928
+ p.add_argument("--defaults", action="store_true", help="print every tunable setting with its default and meaning")
929
+ p.add_argument("--check", action="store_true", help="validate config.toml and exit")
930
+ p.set_defaults(func=cmd_config)
931
+
932
+ p = sub.add_parser("doctor", help="check that everything is set up")
933
+ p.add_argument("--bundle", action="store_true", help="write a zip of config, logs, and versions for a bug report")
934
+ p.set_defaults(func=cmd_doctor)
935
+ return parser
936
+
937
+
938
+ def main(argv: list[str] | None = None, *, prog: str = "readthrough") -> None:
939
+ args = build_parser(prog).parse_args(argv)
940
+ args.home_set = args.home is not None
941
+ try:
942
+ settings = load_settings(args.home)
943
+ except ConfigError as exc:
944
+ print(exc, file=sys.stderr)
945
+ sys.exit(1)
946
+ _setup_logging(settings, verbose=args.verbose, command=args.command)
947
+ try:
948
+ code = args.func(settings, args)
949
+ except (ForgeError, ProfileError, RuntimeError, ValueError, NotImplementedError) as exc:
950
+ log.error("%s", exc)
951
+ code = 1
952
+ except Exception as exc:
953
+ error_id = logs.new_id()
954
+ log.exception("Unexpected error [error %s]", error_id, extra={"error_id": error_id})
955
+ print(f"readthrough hit an unexpected error ({type(exc).__name__}) [error {error_id}]. "
956
+ f"`readthrough doctor --bundle` makes a zip to attach to a bug report.", file=sys.stderr) # fmt: skip
957
+ code = 2
958
+ sys.exit(code)