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,300 @@
1
+ """Forgejo and Gitea (Codeberg is Forgejo), through their REST API, which the two share.
2
+
3
+ The token comes from ``FORGEJO_TOKEN`` if set, else calls are anonymous, which is enough for public repos.
4
+ There is no first-party CLI with a stable token command to lean on (``tea`` keeps its own logins), so the
5
+ environment variable is the way in for private repos.
6
+
7
+ Forgejo has reviews with states like GitHub's and required status checks in branch protection, so most
8
+ of the record maps directly. It has no "author association"; that's derived from whether the author is a
9
+ collaborator or the owner, which needs read access to collaborators and is otherwise reported as
10
+ unavailable rather than guessed.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ from dataclasses import dataclass
17
+ from typing import Any
18
+ from urllib.parse import quote
19
+
20
+ from readthrough.ci import failing_names
21
+ from readthrough.faults import AuthError, ForgeError, NotFound
22
+ from readthrough.forges import FORGES, CiContext, Forge, Rest, credential, link_next
23
+ from readthrough.logs import pool_map
24
+ from readthrough.model import (
25
+ Author,
26
+ Capability,
27
+ ChangedFile,
28
+ Check,
29
+ Issue,
30
+ MergedPullRequest,
31
+ PullRequest,
32
+ Review,
33
+ Thread,
34
+ known,
35
+ unavailable,
36
+ )
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+ REVIEW_STATES = {"APPROVED": "APPROVED", "REQUEST_CHANGES": "CHANGES_REQUESTED", "COMMENT": "COMMENTED",
41
+ "PENDING": "PENDING", "REQUEST_REVIEW": "PENDING"} # fmt: skip
42
+ STATUS = {"success": "SUCCESS", "failure": "FAILURE", "error": "ERROR", "pending": None, "warning": "NEUTRAL"}
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class ForgejoOptions:
47
+ host: str = "codeberg.org"
48
+ credential_env: str = "FORGEJO_TOKEN"
49
+
50
+
51
+ @FORGES.add("forgejo", "Forgejo and Gitea (Codeberg), through their REST API", options=ForgejoOptions)
52
+ class Forgejo(Forge):
53
+ name = "forgejo"
54
+ label = "Forgejo"
55
+ config_dir = ".forgejo"
56
+ capabilities = frozenset({"diffs", "required_checks", "default_branch_ci"})
57
+ access = "the Forgejo/Gitea REST API over HTTPS"
58
+ credentials = ("FORGEJO_TOKEN if set", "else anonymously (public repos)")
59
+
60
+ def __init__(self, repo: str, options: Any = None, tuning: Any = None, *, account: str | None = None) -> None:
61
+ super().__init__(repo, options or ForgejoOptions(), tuning, account=account)
62
+ self.host: str = self.options.host
63
+ env = self.options.credential_env
64
+ self.rest = Rest(
65
+ f"https://{self.host}/api/v1/",
66
+ lambda: credential(env=env, cli=None, cli_name="", scheme="token"),
67
+ self.tuning,
68
+ )
69
+ self.owner, self.repo_name = repo.split("/")
70
+ self._default_branch: str | None = None
71
+ self._collaborators: Capability[set[str]] | None = None
72
+
73
+ @classmethod
74
+ def validate_repo(cls, repo: str) -> str | None:
75
+ parts = repo.split("/")
76
+ if len(parts) != 2 or not all(parts):
77
+ return f"{repo!r} isn't owner/name"
78
+ return cls.bad_segment(parts)
79
+
80
+ def web_url(self) -> str:
81
+ return f"https://{self.host}/{self.repo}"
82
+
83
+ def pr_url(self, number: int) -> str:
84
+ return f"{self.web_url()}/pulls/{number}"
85
+
86
+ def pr_ref(self, number: int) -> str:
87
+ return f"pull/{number}/head"
88
+
89
+ def file_url(self, path: str, branch: str) -> str:
90
+ return f"{self.web_url()}/src/branch/{branch}/{path}"
91
+
92
+ def new_file_url(self, path: str, branch: str) -> str | None:
93
+ return f"{self.web_url()}/_new/{quote(branch, safe='')}/?filename={quote(path)}"
94
+
95
+ def describe_auth(self) -> str:
96
+ return self.rest.cred.source
97
+
98
+ # ---- REST helpers
99
+
100
+ def _get(self, path: str, **params: Any) -> Any:
101
+ resp = self.retrying(f"GET {path}", lambda: self.rest.call("GET", path, params=params))
102
+ return resp.json() if resp else None
103
+
104
+ def _get_or_none(self, path: str, **params: Any) -> Any:
105
+ resp = self.retrying(f"GET {path}", lambda: self.rest.call("GET", path, params=params, absent=(NotFound,)))
106
+ return resp.json() if resp else None
107
+
108
+ def _pages(self, path: str, *, limit: int, **params: Any) -> list[Any]:
109
+ items: list[Any] = []
110
+ url: str | None = self.rest.url(path, {**params, "limit": min(50, limit)})
111
+ while url and len(items) < limit:
112
+ resp = self.retrying(f"GET {path}", lambda u=url: self.rest.call("GET", u))
113
+ if resp is None:
114
+ break
115
+ page = resp.json() or []
116
+ items.extend(page)
117
+ url = link_next(resp.headers) if page else None
118
+ return items[:limit]
119
+
120
+ def _branch(self) -> str:
121
+ if self._default_branch is None:
122
+ self._default_branch = self.repo_info()["default_branch"] or "main"
123
+ return self._default_branch
124
+
125
+ @property
126
+ def _r(self) -> str:
127
+ return f"repos/{self.owner}/{self.repo_name}"
128
+
129
+ # ---- the repo
130
+
131
+ def repo_info(self) -> dict[str, Any]:
132
+ info = self._get(self._r)
133
+ return {"full_name": info.get("full_name"), "default_branch": info.get("default_branch"),
134
+ "private": bool(info.get("private")), "description": info.get("description")} # fmt: skip
135
+
136
+ def tree(self, branch: str) -> tuple[list[str], bool]:
137
+ paths: list[str] = []
138
+ page, limit = 1, self.tuning.max_tree_files
139
+ while True:
140
+ data = self._get(
141
+ f"{self._r}/git/trees/{quote(branch, safe='')}", recursive="true", page=page, per_page=1000
142
+ )
143
+ paths += [e["path"] for e in data.get("tree") or [] if e.get("type") == "blob"]
144
+ more = bool(data.get("truncated")) and data.get("total_count", 0) > page * 1000
145
+ if more and len(paths) < limit:
146
+ page += 1
147
+ continue
148
+ return paths[:limit], not more and len(paths) <= limit
149
+
150
+ def read_file(self, path: str) -> str | None:
151
+ resp = self.retrying(f"GET raw {path}", lambda: self.rest.call(
152
+ "GET", f"{self._r}/raw/{quote(path)}", params={"ref": self._branch()}, headers={"Accept": "*/*"}, absent=(NotFound,),
153
+ )) # fmt: skip
154
+ return resp.text if resp else None
155
+
156
+ def list_dir(self, path: str) -> list[str]:
157
+ items = self._get_or_none(f"{self._r}/contents/{quote(path)}", ref=self._branch()) or []
158
+ return [e["name"] for e in items if isinstance(e, dict) and e.get("type") == "file"]
159
+
160
+ def _association(self, login: str) -> Capability[str]:
161
+ if login.lower() == self.owner.lower():
162
+ return known("OWNER")
163
+ if self._collaborators is None:
164
+ try:
165
+ names = {c["login"].lower() for c in self._pages(f"{self._r}/collaborators", limit=500)}
166
+ self._collaborators = known(names)
167
+ except (AuthError, NotFound):
168
+ self._collaborators = unavailable("collaborators aren't visible without a token")
169
+ except ForgeError as exc:
170
+ self._collaborators = unavailable(exc.reason)
171
+ if not self._collaborators.known:
172
+ return unavailable(self._collaborators.reason)
173
+ return known("COLLABORATOR" if login.lower() in (self._collaborators.value or set()) else "CONTRIBUTOR")
174
+
175
+ # ---- pull requests
176
+
177
+ def fetch_prs(self, limit: int) -> tuple[str, list[PullRequest], int]:
178
+ raw = self._pages(f"{self._r}/pulls", limit=limit, state="open", sort="recentupdate")
179
+ resp = self.rest.call("GET", f"{self._r}/pulls", params={"state": "open", "limit": 1}, absent=(ForgeError,))
180
+ total = int(resp.headers.get("x-total-count", len(raw))) if resp else len(raw)
181
+ me = self._get_or_none("user") if self.rest.cred.token else None
182
+ viewer = (me or {}).get("login") or ""
183
+ return viewer, pool_map(self._complete, raw, self.tuning.concurrency), total
184
+
185
+ def _complete(self, pr: dict[str, Any]) -> PullRequest:
186
+ n = pr["number"]
187
+ files_raw = self._pages(f"{self._r}/pulls/{n}/files", limit=self.tuning.max_files_per_pr)
188
+ files = [ChangedFile(f["filename"], f.get("additions", 0), f.get("deletions", 0),
189
+ {"added": "ADDED", "deleted": "DELETED", "renamed": "RENAMED"}.get(f.get("status", ""), "MODIFIED"))
190
+ for f in files_raw] # fmt: skip
191
+ reviews_raw = self._pages(f"{self._r}/pulls/{n}/reviews", limit=100)
192
+ latest: dict[str, Review] = {}
193
+ for r in reviews_raw:
194
+ state = REVIEW_STATES.get(r.get("state") or "", "COMMENTED")
195
+ if r.get("user") and state != "PENDING" and not r.get("dismissed"):
196
+ latest[r["user"]["login"]] = Review(r["user"]["login"], state, r.get("submitted_at"))
197
+ reviews = list(latest.values())
198
+ threads = self._threads(n, reviews_raw)
199
+ head_sha = (pr.get("head") or {}).get("sha") or ""
200
+ checks: Capability[list[Check]]
201
+ try:
202
+ checks = known(self._checks(head_sha) if head_sha else [])
203
+ except ForgeError as exc:
204
+ checks = unavailable(exc.reason)
205
+ last_commit = None
206
+ if head_sha:
207
+ commit = self._get_or_none(f"{self._r}/git/commits/{head_sha}") or {}
208
+ last_commit = ((commit.get("commit") or {}).get("committer") or {}).get("date")
209
+ states = {r.state for r in reviews}
210
+ decision = ("CHANGES_REQUESTED" if "CHANGES_REQUESTED" in states else "APPROVED" if "APPROVED" in states
211
+ else "REVIEW_REQUIRED") # fmt: skip
212
+ mergeable = "UNKNOWN" if pr.get("mergeable") is None else ("MERGEABLE" if pr["mergeable"] else "CONFLICTING")
213
+ user = pr.get("user") or {}
214
+ return PullRequest(
215
+ number=n, title=pr["title"], url=pr["html_url"], body=pr.get("body") or "", draft=bool(pr.get("draft")),
216
+ created=pr["created_at"], updated=pr["updated_at"],
217
+ additions=int(pr["additions"]) if pr.get("additions") is not None else sum(f.additions for f in files),
218
+ deletions=int(pr["deletions"]) if pr.get("deletions") is not None else sum(f.deletions for f in files),
219
+ changed_files=pr.get("changed_files") or len(files), head=head_sha, base=(pr.get("base") or {}).get("ref") or "main",
220
+ author=Author(user.get("login") or "ghost", bot=bool(user.get("is_bot") or user.get("login", "").endswith("[bot]"))),
221
+ files=files, labels=[label["name"] for label in pr.get("labels") or []],
222
+ requested=[u["login"] for u in pr.get("requested_reviewers") or [] if u],
223
+ reviews=reviews, comments=int(pr.get("comments") or 0), last_commit=last_commit,
224
+ issues=[Issue(0, "", "")][:0], association=self._association(user.get("login") or ""),
225
+ decision=known(decision), mergeable=known(mergeable), threads=threads, checks=checks,
226
+ truncated={"files": (len(files), pr["changed_files"])} if pr.get("changed_files", 0) > len(files) else {},
227
+ ) # fmt: skip
228
+
229
+ def _threads(self, number: int, reviews_raw: list[dict[str, Any]]) -> Capability[list[Thread]]:
230
+ """Review comments, which Forgejo serves per review; a comment with a ``resolver`` is resolved."""
231
+ cap = self.tuning.max_review_threads_per_pr
232
+ threads: list[Thread] = []
233
+ try:
234
+ for review in reviews_raw:
235
+ if not review.get("comments_count") or len(threads) >= cap:
236
+ continue
237
+ comments = self._get_or_none(f"{self._r}/pulls/{number}/reviews/{review['id']}/comments") or []
238
+ threads += [
239
+ Thread(c["user"]["login"], c.get("body") or "", c.get("body_html") or "", c.get("path"),
240
+ c.get("position"), bool(c.get("resolver")), False)
241
+ for c in comments if c.get("user")
242
+ ] # fmt: skip
243
+ except ForgeError as exc:
244
+ return unavailable(exc.reason)
245
+ return known(threads[:cap])
246
+
247
+ def _checks(self, ref: str) -> list[Check]:
248
+ """Commit statuses on ``ref``: a history, with every rerun; ``ci.latest_checks`` keeps the newest per name."""
249
+ statuses = self._pages(f"{self._r}/commits/{quote(ref, safe='')}/statuses", limit=200)
250
+ checks = []
251
+ for s in statuses:
252
+ url = s.get("target_url") or None
253
+ if url and url.startswith("/"):
254
+ url = f"https://{self.host}{url}"
255
+ checks.append(Check(s["context"], "COMPLETED" if s.get("status") != "pending" else "PENDING",
256
+ STATUS.get(s.get("status") or ""), url, s.get("created_at"))) # fmt: skip
257
+ return checks
258
+
259
+ def merged_prs(self, count: int) -> tuple[str, list[MergedPullRequest]]:
260
+ raw = self._pages(f"{self._r}/pulls", limit=count, state="closed", sort="recentupdate")
261
+ merged = []
262
+ for pr in raw:
263
+ if not pr.get("merged"):
264
+ continue
265
+ files_raw = self._pages(f"{self._r}/pulls/{pr['number']}/files", limit=100)
266
+ user = pr.get("user") or {}
267
+ merged.append(MergedPullRequest(
268
+ pr["number"], Author(user.get("login") or "ghost", bool(user.get("is_bot"))),
269
+ self._association(user.get("login") or ""),
270
+ [ChangedFile(f["filename"], f.get("additions", 0), f.get("deletions", 0)) for f in files_raw],
271
+ )) # fmt: skip
272
+ return self._branch(), merged
273
+
274
+ def fetch_diff(self, number: int) -> str:
275
+ resp = self.retrying(f"pr diff #{number}", lambda: self.rest.call(
276
+ "GET", f"{self._r}/pulls/{number}.diff", headers={"Accept": "text/plain"},
277
+ )) # fmt: skip
278
+ return resp.text if resp else ""
279
+
280
+ # ---- CI
281
+
282
+ def ci_context(self, bases: set[str]) -> CiContext:
283
+ branch = self._branch()
284
+ required: dict[str, Capability[set[str]]] = {}
285
+ try:
286
+ protections = self._get_or_none(f"{self._r}/branch_protections") or []
287
+ for base in bases:
288
+ names = {ctx for p in protections if p.get("branch_name") == base or p.get("rule_name") == base
289
+ for ctx in p.get("status_check_contexts") or []} # fmt: skip
290
+ required[base] = known(names)
291
+ except AuthError:
292
+ required = {b: unavailable("branch protection isn't visible without a token") for b in bases}
293
+ except ForgeError as exc:
294
+ required = {b: unavailable(exc.reason) for b in bases}
295
+ failing: Capability[set[str]]
296
+ try:
297
+ failing = known(failing_names(self._checks(branch)))
298
+ except ForgeError as exc:
299
+ failing = unavailable(exc.reason)
300
+ return CiContext(required, failing, branch)