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/build.py ADDED
@@ -0,0 +1,616 @@
1
+ """The build pipeline: fetch, analyze, write briefs, data.json, and the dashboard."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import json
7
+ import logging
8
+ import secrets
9
+ import time
10
+ from dataclasses import dataclass, field
11
+ from importlib.resources import files
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from readthrough import __version__, forges, ledger, logs, review, study
16
+ from readthrough.analyze import analyze, compute_overlaps, count_lines, plan_sessions, rule_descriptions, whats_new
17
+ from readthrough.brief import build_brief
18
+ from readthrough.config import Config
19
+ from readthrough.faults import ForgeError, TooLarge
20
+ from readthrough.files import write_atomic
21
+ from readthrough.forges import Forge
22
+ from readthrough.logs import pool_map
23
+ from readthrough.membership import internal_members
24
+ from readthrough.model import Capability, ChangedFile, PullRequest, known, unavailable
25
+ from readthrough.profile import Profile, resolve_profile
26
+ from readthrough.rules import Contract, Instruction, contracts_for, parse_instruction
27
+ from readthrough.system import registered_protocol_command
28
+ from readthrough.tuning import Tuning
29
+
30
+ # data.json's layout. Bump it when a field changes meaning or is removed (adding fields doesn't need it),
31
+ # so a newer data file is never misread by an older dashboard or server.
32
+ DATA_SCHEMA = 2
33
+ log = logging.getLogger(__name__)
34
+
35
+
36
+ @dataclass
37
+ class Snapshot:
38
+ """Everything fetched from the forge for one build. Analysis is a pure function of this and the profile."""
39
+
40
+ viewer: str
41
+ prs: list[PullRequest]
42
+ contracts: dict[str, Contract]
43
+ instructions: list[Instruction]
44
+ required_checks: dict[str, Capability[set[str]]]
45
+ main_failing: Capability[set[str]]
46
+ diffs: dict[int, str]
47
+ now: dt.datetime
48
+ members: set[str] = field(default_factory=set)
49
+ warnings: list[dict[str, Any]] = field(default_factory=list)
50
+ diff_problems: dict[int, str] = field(default_factory=dict)
51
+ stats: dict[str, Any] = field(default_factory=dict)
52
+
53
+
54
+ class BuildFailed(RuntimeError):
55
+ """A build that couldn't finish. Says which step failed, and carries an error id shown in the dashboard."""
56
+
57
+ def __init__(self, repo: str, step: str, cause: BaseException, error_id: str, seconds: float) -> None:
58
+ reason = cause.args[0] if isinstance(cause, ForgeError) and cause.args else f"{type(cause).__name__}: {cause}"
59
+ super().__init__(f"{step}: {reason}")
60
+ self.repo, self.step, self.cause, self.error_id, self.seconds = repo, step, cause, error_id, seconds
61
+ self.reason = reason
62
+ self.expected = isinstance(cause, ForgeError)
63
+
64
+
65
+ class Warnings(list):
66
+ """What a build had to do without. Each is logged once and shown in the dashboard."""
67
+
68
+ def add(self, code: str, message: str, details: list[str] | None = None) -> None:
69
+ details = details or []
70
+ log.warning(
71
+ "%s%s", message, f" ({'; '.join(details[:5])}{' …' if len(details) > 5 else ''})" if details else ""
72
+ )
73
+ self.append({"code": code, "message": message, "details": details[:20]})
74
+
75
+
76
+ def fetch_snapshot(
77
+ cfg: Config,
78
+ profile: Profile,
79
+ *,
80
+ with_diffs: bool = True,
81
+ forge: Forge | None = None,
82
+ steps: logs.Steps | None = None,
83
+ ) -> Snapshot:
84
+ """Fetch everything for a build. Only the PR list is essential; other inputs degrade to a warning."""
85
+ forge = forge or forges.make(cfg)
86
+ steps = steps or logs.Steps(log)
87
+ warnings = Warnings()
88
+ for note in profile.notes:
89
+ warnings.add("profile", note)
90
+ now = dt.datetime.now(dt.UTC)
91
+ with steps.step("fetching PRs"):
92
+ log.info("Fetching open %ss from %s%s", forge.pr_noun, forge.label, f" as {cfg.account}" if cfg.account else "")
93
+ viewer, prs, total = forge.fetch_prs(cfg.limit)
94
+ if total > len(prs):
95
+ warnings.add(
96
+ "limit",
97
+ f"Showing the {len(prs)} most recently active of {total} open {forge.pr_noun}s. Raise `limit` for this repo to see more.",
98
+ )
99
+ capped = [
100
+ f"#{p.number} {', '.join(f'{k} {have} of {of}' for k, (have, of) in p.truncated.items())}"
101
+ for p in prs
102
+ if p.truncated
103
+ ]
104
+ if capped:
105
+ warnings.add(
106
+ "truncated",
107
+ f"{len(capped)} {forge.pr_noun}s are too big to fetch completely, so their map placement and checks are partial",
108
+ capped,
109
+ )
110
+
111
+ with steps.step("fetching CI context"):
112
+ try:
113
+ context = forge.ci_context({p.base for p in prs})
114
+ problems = sorted({c.reason for c in (*context.required.values(), context.main_failing) if not c.known})
115
+ except ForgeError as exc:
116
+ context = forges.CiContext({}, unavailable(exc.reason), "main")
117
+ problems = [exc.reason]
118
+ if problems:
119
+ warnings.add(
120
+ "ci",
121
+ "Couldn't read required checks or the default branch's CI, so CI states are less precise",
122
+ problems,
123
+ )
124
+ with steps.step("fetching rules"):
125
+ log.info("Fetching architecture contracts and instruction files from %s", context.default_branch)
126
+ contracts, instructions, problems = fetch_rules(forge, profile, branch=context.default_branch)
127
+ if problems:
128
+ warnings.add(
129
+ "rules",
130
+ f"Couldn't fetch {len(problems)} rule or contract files; the rules shown may be incomplete",
131
+ problems,
132
+ )
133
+ diffs: dict[int, str] = {}
134
+ diff_problems: dict[int, str] = {}
135
+ fetched = 0
136
+ if with_diffs and "diffs" not in forge.capabilities:
137
+ warnings.add("diffs", f"{forge.label} has no API for whole-change diffs, so line heuristics never run here")
138
+ diff_problems = dict.fromkeys((p.number for p in prs), "unsupported")
139
+ elif with_diffs:
140
+ with steps.step("fetching diffs"):
141
+ diffs, failures, fetched = forge.diffs(prs, cfg.cache_dir)
142
+ log.info(
143
+ "Diffs: %d downloaded, %d from cache, %d unavailable", fetched, len(diffs) - fetched, len(failures)
144
+ )
145
+ diff_problems = {n: ("too-large" if isinstance(e, TooLarge) else e.reason) for n, e in failures.items()}
146
+ errors = [f"#{n}: {e.reason}" for n, e in failures.items() if not isinstance(e, TooLarge)]
147
+ if errors:
148
+ warnings.add(
149
+ "diffs",
150
+ f"Couldn't fetch {len(errors)} diffs; their line heuristics are missing until the next refresh",
151
+ errors,
152
+ )
153
+ counted = count_from_diffs(prs, diffs)
154
+ if counted:
155
+ log.info(
156
+ "Counted changed lines from the diffs of %d %ss the forge gave no counts for",
157
+ counted,
158
+ forge.pr_noun,
159
+ )
160
+ _gap_warnings(warnings, prs, forge) # after the diffs: they may have filled the line counts
161
+ with steps.step("checking memberships"):
162
+ members, failed = fetch_members(
163
+ forge, profile, prs, cfg.cache_dir / "members.json", cfg.tuning.authors.membership_cache_days
164
+ )
165
+ if failed:
166
+ warnings.add(
167
+ "members",
168
+ f"Couldn't check {len(failed)} team or org memberships; those authors use the profile's other rules this time",
169
+ failed,
170
+ )
171
+ stats = {"prs": len(prs), "open": total, "diffs_downloaded": fetched, "diffs_cached": len(diffs) - fetched}
172
+ return Snapshot(
173
+ viewer,
174
+ prs,
175
+ contracts,
176
+ instructions,
177
+ context.required,
178
+ context.main_failing,
179
+ diffs,
180
+ now,
181
+ members,
182
+ warnings,
183
+ diff_problems,
184
+ stats,
185
+ )
186
+
187
+
188
+ def count_from_diffs(prs: list[PullRequest], diffs: dict[int, str]) -> int:
189
+ """Fill in per-file and per-PR line counts from the fetched diffs for PRs whose forge reported none.
190
+
191
+ Azure DevOps has no count anywhere in its API, but its diff is assembled from the files themselves, so the
192
+ counts fall out of it. Returns how many PRs were filled; the rest keep their ``line_counts`` gap.
193
+ """
194
+ filled = 0
195
+ for pr in prs:
196
+ text = diffs.get(pr.number)
197
+ if pr.line_counts.known or text is None:
198
+ continue
199
+ counts = count_lines(text)
200
+ pr.files = [ChangedFile(f.path, *counts.get(f.path, (0, 0)), f.change) for f in pr.files]
201
+ pr.additions = sum(f.additions for f in pr.files)
202
+ pr.deletions = sum(f.deletions for f in pr.files)
203
+ pr.line_counts = known(True)
204
+ filled += 1
205
+ return filled
206
+
207
+
208
+ def _gap_warnings(warnings: Warnings, prs: list[PullRequest], forge: Forge) -> None:
209
+ """One warning per kind of thing the forge couldn't tell us, so the gap is visible beyond the PR signals."""
210
+ gaps: dict[tuple[str, str], list[str]] = {}
211
+ for pr in prs:
212
+ for name, cap in pr.gaps():
213
+ gaps.setdefault((name, cap.kind), []).append(f"#{pr.number}: {cap.reason}")
214
+ for (name, kind), details in sorted(gaps.items()):
215
+ if kind == "unsupported":
216
+ warnings.add(
217
+ f"gap-{name}",
218
+ f"{forge.label} can't tell us the {name.replace('_', ' ')}; related signals and lanes use a neutral default",
219
+ )
220
+ else:
221
+ warnings.add(
222
+ f"gap-{name}",
223
+ f"Couldn't read the {name.replace('_', ' ')} for {len(details)} {forge.pr_noun}s this time",
224
+ details,
225
+ )
226
+
227
+
228
+ def fetch_rules(
229
+ forge: Forge, profile: Profile, *, branch: str = "main"
230
+ ) -> tuple[dict[str, Contract], list[Instruction], list[str]]:
231
+ """The profile's architecture contracts and the repo's instruction files, from the default branch.
232
+
233
+ Also returns what couldn't be fetched, so the build can carry on with the rest and say what's missing.
234
+ """
235
+ problems: list[str] = []
236
+ doc = None
237
+ if profile.contracts_source:
238
+ try:
239
+ doc = forge.read_file(profile.contracts_source)
240
+ except ForgeError as exc:
241
+ problems.append(f"{profile.contracts_source}: {exc.reason}")
242
+ contracts = contracts_for(profile, doc)
243
+ if not profile.instructions_dir:
244
+ return contracts, [], problems
245
+ try:
246
+ names = [n for n in forge.list_dir(profile.instructions_dir) if n.endswith(".md")]
247
+ except ForgeError as exc:
248
+ problems.append(f"{profile.instructions_dir}/: {exc.reason}")
249
+ return contracts, [], problems
250
+
251
+ def fetch(name: str) -> str | None:
252
+ try:
253
+ return forge.read_file(f"{profile.instructions_dir}/{name}")
254
+ except ForgeError as exc:
255
+ problems.append(f"{name}: {exc.reason}")
256
+ return None
257
+
258
+ texts = pool_map(fetch, names, forge.tuning.concurrency)
259
+ instructions = [
260
+ parse_instruction(n, t, forge.file_url(f"{profile.instructions_dir}/{n}", branch))
261
+ for n, t in zip(names, texts, strict=True)
262
+ if t is not None
263
+ ]
264
+ return contracts, [i for i in instructions if i.patterns], problems
265
+
266
+
267
+ def fetch_members(
268
+ forge: Forge, profile: Profile, prs: list[PullRequest], cache_path: Path, ttl_days: float = 7.0
269
+ ) -> tuple[set[str], list[str]]:
270
+ a = profile.authors
271
+ if not (a.internal_teams or a.internal_orgs):
272
+ return set(), []
273
+ if "memberships" not in forge.capabilities:
274
+ return set(), [f"{forge.label} can't answer team or org membership questions"]
275
+ logins = {p.author.login for p in prs if not p.author.bot}
276
+ return internal_members(
277
+ forge,
278
+ teams=a.internal_teams,
279
+ orgs=a.internal_orgs,
280
+ logins=logins - {""},
281
+ cache_path=cache_path,
282
+ ttl_days=ttl_days,
283
+ )
284
+
285
+
286
+ def analyze_snapshot(
287
+ snap: Snapshot, profile: Profile, *, budget: int = 60, ledger_entries: dict[str, Any] | None = None,
288
+ tuning: Tuning | None = None, forge: Forge | None = None,
289
+ ) -> dict[str, Any]: # fmt: skip
290
+ """Lanes, signals, overlaps, the burn-down plan, and a brief per PR (which names the forge, GitHub by default)."""
291
+ ledger_entries = ledger_entries or {}
292
+ items = [
293
+ analyze(
294
+ p,
295
+ profile=profile,
296
+ viewer=snap.viewer,
297
+ instructions=snap.instructions,
298
+ diff_text=snap.diffs.get(p.number),
299
+ now=snap.now,
300
+ required_checks=snap.required_checks,
301
+ main_failing=snap.main_failing.get(set()),
302
+ members=snap.members,
303
+ planning=tuning.planning if tuning else None,
304
+ payload=tuning.payload if tuning else None,
305
+ )
306
+ for p in snap.prs
307
+ ]
308
+ by_number = {p.number: p for p in snap.prs}
309
+ for it in items:
310
+ _partial_flags(it, by_number[it["number"]], snap.diff_problems.get(it["number"]))
311
+ overlaps = compute_overlaps(items, profile)
312
+ titles = {it["number"]: it["title"] for it in items}
313
+ by_name = {i.name: i for i in snap.instructions}
314
+ briefs: dict[int, str] = {}
315
+ for it in items:
316
+ related = sorted(
317
+ (
318
+ (o["b"] if o["a"] == it["number"] else o["a"], o["files"])
319
+ for o in overlaps
320
+ if it["number"] in (o["a"], o["b"])
321
+ ),
322
+ key=lambda r: -len(r[1]),
323
+ )
324
+ it["related"] = [n for n, _ in related]
325
+ briefs[it["number"]] = build_brief(
326
+ it, profile=profile, contracts=snap.contracts, instructions=by_name, related=related, titles=titles,
327
+ ledger_entry=ledger_entries.get(str(it["number"])), forge_label=forge.label if forge else "GitHub",
328
+ files_tab=forge.files_tab if forge else "/files",
329
+ ) # fmt: skip
330
+ return {
331
+ "items": items,
332
+ "overlaps": overlaps,
333
+ "sessions": plan_sessions(items, profile, budget=budget),
334
+ "briefs": briefs,
335
+ }
336
+
337
+
338
+ def _partial_flags(item: dict[str, Any], pr: PullRequest, diff_problem: str | None) -> None:
339
+ """Say on the PR itself when its data is incomplete, so nobody mistakes "no signals" for "nothing to see"."""
340
+ if diff_problem == "too-large":
341
+ item["flags"].append({"id": "diff-too-large", "kind": "info",
342
+ "msg": f"Diff too large to serve ({pr.changed_files} files): line heuristics skipped"}) # fmt: skip
343
+ elif diff_problem == "unsupported":
344
+ item["flags"].append({"id": "diff-unsupported", "kind": "info",
345
+ "msg": "This forge serves no whole-change diff: line heuristics can't run"}) # fmt: skip
346
+ elif diff_problem:
347
+ item["flags"].append(
348
+ {"id": "diff-unavailable", "kind": "info", "msg": f"Diff couldn't be fetched this time: {diff_problem}"}
349
+ )
350
+ if pr.truncated:
351
+ parts = ", ".join(f"{have} of {of} {name}" for name, (have, of) in pr.truncated.items())
352
+ item["flags"].append(
353
+ {
354
+ "id": "partial",
355
+ "kind": "info",
356
+ "msg": f"Only partly fetched ({parts}): placement and checks may be incomplete",
357
+ }
358
+ )
359
+ item["truncated"] = {k: list(v) for k, v in pr.truncated.items()}
360
+
361
+
362
+ def build(
363
+ cfg: Config, *, with_diffs: bool = True, profile: Profile | None = None, draft: bool = False, write: bool = True
364
+ ) -> dict[str, Any]:
365
+ """Fetch, analyze, and write data.json, the dashboard, and briefs.
366
+
367
+ ``draft`` marks an onboarding preview. ``write=False`` only returns the payload, leaving the repo's
368
+ files alone, so a draft profile can be previewed without disturbing the live dashboard.
369
+
370
+ Every log line inside is tagged with the repo and a build id. A failure is logged once (one line for
371
+ expected GitHub errors, a traceback otherwise) and raised as ``BuildFailed``.
372
+ """
373
+ build_id = logs.new_id()
374
+ with logs.context(cfg.repo, build_id):
375
+ steps = logs.Steps(log)
376
+ started = time.monotonic()
377
+ log.info("build started%s", "" if write else " (preview)")
378
+ try:
379
+ payload = _build(cfg, steps, with_diffs=with_diffs, profile=profile, draft=draft, write=write)
380
+ except Exception as exc:
381
+ failed = BuildFailed(cfg.repo, steps.current, exc, logs.new_id(), time.monotonic() - started)
382
+ extra = {"error_id": failed.error_id, "step": failed.step, "duration_s": round(failed.seconds, 1)}
383
+ message = "build failed after %.1fs at step '%s' [error %s]: %s"
384
+ args = (failed.seconds, failed.step, failed.error_id, failed.reason)
385
+ if failed.expected:
386
+ log.warning(message, *args, extra=extra)
387
+ else:
388
+ log.exception(message, *args, extra=extra)
389
+ raise failed from exc
390
+ stats = payload["stats"]
391
+ left = ", ".join(f"{v} {k}" for k, v in (stats.get("rate_limit") or {}).items())
392
+ log.info(
393
+ "built in %.1fs: %d PRs, %d diffs downloaded / %d cached, %d warnings%s (%s)",
394
+ time.monotonic() - started, stats["prs"], stats["diffs_downloaded"], stats["diffs_cached"], len(payload["warnings"]),
395
+ f", rate limit left: {left}" if left else "",
396
+ steps.summary(),
397
+ ) # fmt: skip
398
+ return payload
399
+
400
+
401
+ def _build(
402
+ cfg: Config, steps: logs.Steps, *, with_diffs: bool, profile: Profile | None, draft: bool, write: bool
403
+ ) -> dict[str, Any]:
404
+ from readthrough.onboard import drift
405
+
406
+ forge = forges.make(cfg)
407
+ with steps.step("resolving profile"):
408
+ profile = profile or resolve_profile(cfg, forge)
409
+ snap = fetch_snapshot(cfg, profile, with_diffs=with_diffs, forge=forge, steps=steps)
410
+ with steps.step("analyzing"):
411
+ entries = ledger.load(cfg.ledger_path)
412
+ result = analyze_snapshot(
413
+ snap, profile, budget=cfg.session_minutes, ledger_entries=entries, tuning=cfg.tuning, forge=forge
414
+ )
415
+ items = result["items"]
416
+ previous = _load_json(cfg.seen_path) or _load_json(cfg.data_path)
417
+
418
+ steps.current = "writing briefs"
419
+ if write:
420
+ cfg.briefs_dir.mkdir(parents=True, exist_ok=True)
421
+ for old in cfg.briefs_dir.glob("pr-*.md"):
422
+ old.unlink()
423
+ review.session_index(cfg).scan(force=True)
424
+ known = review.agent_set(cfg)
425
+ for it in items:
426
+ entry = entries.get(str(it["number"]))
427
+ primary = review.session_id_for(cfg, it["number"], entry)
428
+ it["session"] = review.session_info(cfg, primary, known=known)
429
+ it["sessions"] = review.pr_sessions(cfg, it["number"], primary, known=known)
430
+ log_entries = study.load(cfg, it["number"])
431
+ it["study"] = study.summarize(log_entries)
432
+ appendix = study.render_appendix(log_entries)
433
+ brief = result["briefs"][it["number"]]
434
+ if write:
435
+ (cfg.briefs_dir / f"pr-{it['number']}.md").write_text(
436
+ brief + ("\n" + appendix if appendix else ""), encoding="utf-8"
437
+ )
438
+
439
+ payload = {
440
+ "schema": DATA_SCHEMA,
441
+ "version": __version__,
442
+ "repo": cfg.repo,
443
+ "slug": cfg.slug,
444
+ "forge": {
445
+ "name": forge.name,
446
+ "label": forge.label,
447
+ "pr_noun": forge.pr_noun,
448
+ "url": forge.web_url(),
449
+ "files_tab": forge.files_tab,
450
+ },
451
+ "viewer": snap.viewer,
452
+ "generated": snap.now.isoformat(),
453
+ "profile": {**profile.to_payload(), "onboarded": cfg.onboarded},
454
+ "rules": rule_descriptions(profile),
455
+ "components": [
456
+ {
457
+ "id": c.id,
458
+ "label": c.label,
459
+ "layer": c.layer,
460
+ "contract": vars(snap.contracts[c.id]) if c.id in snap.contracts else {},
461
+ }
462
+ for c in profile.components
463
+ ],
464
+ "instructions": [{"name": i.name, "patterns": i.patterns, "url": i.url} for i in snap.instructions],
465
+ "prs": items,
466
+ "overlaps": result["overlaps"],
467
+ "sessions": result["sessions"],
468
+ "ledger": entries,
469
+ "news": whats_new(previous, items, entries, snap.viewer),
470
+ "drift": drift(items, cfg.tuning.onboarding.drift_coverage),
471
+ "draft": draft,
472
+ "warnings": snap.warnings,
473
+ "stats": {**snap.stats, "rate_limit": forge.rate_limit()},
474
+ "freshness": {
475
+ "stale_live_hours": cfg.tuning.freshness.stale_live_hours,
476
+ "stale_snapshot_hours": cfg.tuning.freshness.stale_snapshot_hours,
477
+ },
478
+ "links": {
479
+ "protocol": registered_protocol_command() is not None,
480
+ "briefs_dir": str(cfg.briefs_dir.resolve()),
481
+ "clone_uri": cfg.clone.resolve().as_uri() if cfg.clone else None,
482
+ },
483
+ }
484
+ steps.current = "writing the dashboard"
485
+ if write:
486
+ cfg.data_path.parent.mkdir(parents=True, exist_ok=True)
487
+ write_atomic(cfg.data_path, json.dumps(payload, indent=1))
488
+ write_atomic(cfg.dashboard_path, render_html(payload))
489
+ return payload
490
+
491
+
492
+ def _load_json(path: Path) -> dict[str, Any] | None:
493
+ try:
494
+ return json.loads(path.read_text(encoding="utf-8"))
495
+ except (FileNotFoundError, ValueError):
496
+ return None
497
+
498
+
499
+ def mark_seen(cfg: Config, payload: dict[str, Any] | None = None) -> None:
500
+ """Remember what the user last looked at, so "what's new" means new since then, not since the last build.
501
+
502
+ Matters once the live server rebuilds every few minutes: otherwise the banner would only ever
503
+ cover ten minutes, and the morning `--open auto` would never find anything to open for.
504
+ """
505
+ payload = payload or _load_json(cfg.data_path)
506
+ if not payload:
507
+ return
508
+ keep = ("number", "title", "author", "head", "flags")
509
+ seen = {"generated": payload.get("generated"), "prs": [{k: p.get(k) for k in keep} for p in payload.get("prs", [])]}
510
+ write_atomic(cfg.seen_path, json.dumps(seen))
511
+
512
+
513
+ VENDOR_SCRIPTS = (
514
+ "cytoscape.min.js",
515
+ "layout-base.js",
516
+ "cose-base.js",
517
+ "cytoscape-fcose.js",
518
+ "marked.umd.js",
519
+ "purify.min.js",
520
+ "lucide-icons.js",
521
+ )
522
+
523
+
524
+ def _vendor_js() -> str:
525
+ vendor = files("readthrough").joinpath("assets/vendor")
526
+ parts = [vendor.joinpath(name).read_text(encoding="utf-8") for name in VENDOR_SCRIPTS]
527
+ return "\n;\n".join(parts).replace("</script", "<\\/script")
528
+
529
+
530
+ def page_source(name: str) -> str:
531
+ """Assemble a page from its sources in assets/web: markup, shared theme plus page CSS, and page script.
532
+
533
+ The result is still one self-contained file; the split only exists so each part can be edited as what it is.
534
+ """
535
+ web = files("readthrough").joinpath("assets/web")
536
+
537
+ def part(file: str) -> str:
538
+ return web.joinpath(file).read_text(encoding="utf-8").removesuffix("\n")
539
+
540
+ css = "\n".join(p for p in (part("theme.css"), part(f"{name}.css")) if p)
541
+ return (
542
+ part(f"{name}.html")
543
+ .replace("/*__READTHROUGH_CSS__*/", css)
544
+ .replace("/*__READTHROUGH_APP__*/", part(f"{name}.js"))
545
+ )
546
+
547
+
548
+ def render_setup(live: dict[str, Any], nonce: str) -> str:
549
+ """The onboarding and settings page. Only ever served live: it's all API calls."""
550
+ page = page_source("setup")
551
+ icons = files("readthrough").joinpath("assets/vendor/lucide-icons.js").read_text(encoding="utf-8")
552
+ return (
553
+ page.replace("__NONCE__", nonce)
554
+ .replace("/*__READTHROUGH_ICONS__*/", icons.replace("</script", "<\\/script"))
555
+ .replace("/*__READTHROUGH_LIVE__*/null", inline_json(live))
556
+ )
557
+
558
+
559
+ def inline_json(value: Any) -> str:
560
+ r"""JSON that can sit inside a <script> element whatever strings it carries.
561
+
562
+ ``<`` becomes ``\u003c``, which JSON reads as the same character, so neither ``</script>`` nor ``<!--`` (which
563
+ puts the HTML tokenizer into a state where the real ``</script>`` no longer counts) can appear in the page.
564
+ """
565
+ return json.dumps(value).replace("<", "\\u003c")
566
+
567
+
568
+ def render_html(payload: dict[str, Any], *, live: dict[str, Any] | None = None, nonce: str | None = None) -> str:
569
+ """Inline the libraries, the data, and (when served) the live-mode settings into the single-file dashboard.
570
+
571
+ Every script carries a per-render nonce, and the page's CSP only runs scripts with that nonce. PR
572
+ descriptions are third-party HTML, so even if something slipped past sanitizing it could not run.
573
+ """
574
+ nonce = nonce or secrets.token_urlsafe(16)
575
+ return (
576
+ page_source("dashboard")
577
+ .replace("__NONCE__", nonce)
578
+ .replace("/*__READTHROUGH_VENDOR__*/", _vendor_js())
579
+ .replace("/*__READTHROUGH_LIVE__*/null", inline_json(live))
580
+ .replace("/*__READTHROUGH_DATA__*/null", inline_json(payload)) # last: nothing in the data is a placeholder
581
+ )
582
+
583
+
584
+ def session_changes(payload: dict[str, Any], cfg: Config) -> dict[int, dict[str, Any]]:
585
+ """The PRs whose agent sessions differ from what the payload says, and their new values.
586
+
587
+ Only reads: the server runs this on its watcher thread every few seconds and must not hold the payload lock
588
+ while it looks, or every page request waits on it. The agents are resolved once per pass; the lookups
589
+ behind them cost milliseconds each and there is one PR after another.
590
+ """
591
+ review.session_index(cfg).scan()
592
+ known = review.agent_set(cfg)
593
+ changed = {}
594
+ for it in payload["prs"]:
595
+ entry = payload["ledger"].get(str(it["number"]))
596
+ primary = review.session_id_for(cfg, it["number"], entry)
597
+ info = review.session_info(cfg, primary, known=known)
598
+ sessions = review.pr_sessions(cfg, it["number"], primary, known=known)
599
+ if info != it.get("session") or sessions != it.get("sessions"):
600
+ changed[it["number"]] = {"session": info, "sessions": sessions}
601
+ return changed
602
+
603
+
604
+ def apply_session_changes(payload: dict[str, Any], changed: dict[int, dict[str, Any]]) -> None:
605
+ """Write what ``session_changes`` found into the payload (under the server's lock, when there is one)."""
606
+ by_number = {it["number"]: it for it in payload["prs"]}
607
+ for number, fields in changed.items():
608
+ if (it := by_number.get(number)) is not None:
609
+ it.update(fields)
610
+
611
+
612
+ def refresh_sessions(payload: dict[str, Any], cfg: Config) -> dict[int, dict[str, Any]]:
613
+ """Recompute agent session status for every PR in place. Returns only the PRs whose sessions changed."""
614
+ changed = session_changes(payload, cfg)
615
+ apply_session_changes(payload, changed)
616
+ return changed