plotroom 0.1.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 (150) hide show
  1. plotroom/__init__.py +0 -0
  2. plotroom/__main__.py +8 -0
  3. plotroom/_secret_file.py +8 -0
  4. plotroom/adapters/__init__.py +0 -0
  5. plotroom/adapters/claude_desktop.py +219 -0
  6. plotroom/adapters/embedding_http.py +175 -0
  7. plotroom/adapters/github/__init__.py +337 -0
  8. plotroom/adapters/github/app_credential.py +209 -0
  9. plotroom/adapters/github/ci.py +738 -0
  10. plotroom/adapters/github/commit_statuses.py +63 -0
  11. plotroom/adapters/github/deployments.py +213 -0
  12. plotroom/adapters/github/details.py +867 -0
  13. plotroom/adapters/github/issue_details.py +368 -0
  14. plotroom/adapters/github/junit.py +210 -0
  15. plotroom/adapters/github/junit_xml.py +162 -0
  16. plotroom/adapters/github/kodus_review.py +347 -0
  17. plotroom/adapters/github/pr_details.py +192 -0
  18. plotroom/adapters/github/pull_comparison.py +108 -0
  19. plotroom/adapters/github/read.py +530 -0
  20. plotroom/adapters/github/ticket_tree.py +336 -0
  21. plotroom/adapters/mcp/__init__.py +5 -0
  22. plotroom/adapters/mcp/proxy.py +722 -0
  23. plotroom/adapters/mcp/server.py +931 -0
  24. plotroom/adapters/openrouter.py +151 -0
  25. plotroom/adapters/store_sqlite/__init__.py +6 -0
  26. plotroom/adapters/store_sqlite/actions_sql.py +148 -0
  27. plotroom/adapters/store_sqlite/asks_sql.py +153 -0
  28. plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
  29. plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
  30. plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
  31. plotroom/adapters/store_sqlite/claims_sql.py +54 -0
  32. plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
  33. plotroom/adapters/store_sqlite/github_sql.py +331 -0
  34. plotroom/adapters/store_sqlite/goals_sql.py +57 -0
  35. plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
  36. plotroom/adapters/store_sqlite/items_sql.py +129 -0
  37. plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
  38. plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
  39. plotroom/adapters/store_sqlite/migrate.py +194 -0
  40. plotroom/adapters/store_sqlite/migrations/env.py +36 -0
  41. plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
  42. plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
  43. plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
  44. plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
  45. plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
  46. plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
  47. plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
  48. plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
  49. plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
  50. plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
  51. plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
  52. plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
  53. plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
  54. plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
  55. plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
  56. plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
  57. plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
  58. plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
  59. plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
  60. plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
  61. plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
  62. plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
  63. plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
  64. plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
  65. plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
  66. plotroom/adapters/store_sqlite/routes_sql.py +26 -0
  67. plotroom/adapters/store_sqlite/search_sql.py +116 -0
  68. plotroom/adapters/store_sqlite/store.py +623 -0
  69. plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
  70. plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
  71. plotroom/adapters/switchboard.py +152 -0
  72. plotroom/adapters/usage_fixture.py +11 -0
  73. plotroom/adapters/work_items_bmad.py +256 -0
  74. plotroom/adapters/work_items_github_issues.py +323 -0
  75. plotroom/app/__init__.py +0 -0
  76. plotroom/app/bridge.py +162 -0
  77. plotroom/app/clerk_import.py +349 -0
  78. plotroom/app/cli.py +290 -0
  79. plotroom/app/clock.py +12 -0
  80. plotroom/app/config.py +984 -0
  81. plotroom/app/daemon_start.py +453 -0
  82. plotroom/app/lock.py +77 -0
  83. plotroom/app/logging.py +93 -0
  84. plotroom/app/portfile.py +218 -0
  85. plotroom/app/runtime.py +518 -0
  86. plotroom/app/serve.py +671 -0
  87. plotroom/app/session_intake.py +51 -0
  88. plotroom/app/sqlite_floor.py +35 -0
  89. plotroom/app/tokens.py +265 -0
  90. plotroom/core/__init__.py +0 -0
  91. plotroom/core/actions.py +67 -0
  92. plotroom/core/ask_checks.py +124 -0
  93. plotroom/core/asks.py +123 -0
  94. plotroom/core/branch_updates.py +207 -0
  95. plotroom/core/bridge.py +112 -0
  96. plotroom/core/briefs.py +83 -0
  97. plotroom/core/budgets.py +182 -0
  98. plotroom/core/catalog.py +464 -0
  99. plotroom/core/checklists.py +151 -0
  100. plotroom/core/claims.py +296 -0
  101. plotroom/core/clerk_import.py +379 -0
  102. plotroom/core/commands.py +85 -0
  103. plotroom/core/deploy_window.py +21 -0
  104. plotroom/core/envelope.py +20 -0
  105. plotroom/core/events.py +227 -0
  106. plotroom/core/github.py +306 -0
  107. plotroom/core/github_projection.py +310 -0
  108. plotroom/core/goal_language.py +374 -0
  109. plotroom/core/goal_projection.py +146 -0
  110. plotroom/core/human_queue.py +119 -0
  111. plotroom/core/intake.py +106 -0
  112. plotroom/core/kodus_review.py +53 -0
  113. plotroom/core/lanes.py +281 -0
  114. plotroom/core/ledger.py +808 -0
  115. plotroom/core/merge_controller.py +344 -0
  116. plotroom/core/merge_flakes.py +422 -0
  117. plotroom/core/merge_gate.py +724 -0
  118. plotroom/core/merge_lane.py +70 -0
  119. plotroom/core/merge_overlap.py +76 -0
  120. plotroom/core/next_items.py +60 -0
  121. plotroom/core/operator_goals.py +103 -0
  122. plotroom/core/outbox.py +70 -0
  123. plotroom/core/pull_overlaps.py +152 -0
  124. plotroom/core/reports.py +62 -0
  125. plotroom/core/roles.py +100 -0
  126. plotroom/core/routing.py +55 -0
  127. plotroom/core/run_reports.py +53 -0
  128. plotroom/core/search.py +266 -0
  129. plotroom/core/search_sources.py +94 -0
  130. plotroom/core/snapshot.py +204 -0
  131. plotroom/core/trigger_actions.py +89 -0
  132. plotroom/core/triggers.py +550 -0
  133. plotroom/core/unit_of_work.py +541 -0
  134. plotroom/core/watchers.py +35 -0
  135. plotroom/core/work_items.py +23 -0
  136. plotroom/core/writer.py +164 -0
  137. plotroom/ports/__init__.py +6 -0
  138. plotroom/ports/clock.py +12 -0
  139. plotroom/ports/github_write.py +72 -0
  140. plotroom/ports/search.py +197 -0
  141. plotroom/ports/session_reader.py +23 -0
  142. plotroom/ports/store.py +323 -0
  143. plotroom/ports/usage_meter.py +35 -0
  144. plotroom/ports/work_items.py +22 -0
  145. plotroom/py.typed +0 -0
  146. plotroom-0.1.0.dist-info/METADATA +230 -0
  147. plotroom-0.1.0.dist-info/RECORD +150 -0
  148. plotroom-0.1.0.dist-info/WHEEL +4 -0
  149. plotroom-0.1.0.dist-info/entry_points.txt +2 -0
  150. plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,368 @@
1
+ """Read repository issues, comments, milestones and BMad relationships."""
2
+
3
+ from datetime import datetime, timedelta
4
+ from urllib.parse import urlsplit
5
+
6
+ import httpx
7
+
8
+ from plotroom.adapters.github import GitHubRateLimited, GitHubUnavailable
9
+ from plotroom.adapters.github.read import GitHubReadClient, Row, number, obj, rows, string
10
+ from plotroom.core.events import format_time
11
+ from plotroom.core.github_projection import (
12
+ ISSUE_PAGINATION_VERIFIED,
13
+ ISSUE_RELATION_RETRY,
14
+ GitHubRecord,
15
+ GitHubResource,
16
+ )
17
+
18
+ MAX_RELATION_REFRESHES = 24
19
+
20
+
21
+ class IssueRelationshipReadError(GitHubUnavailable):
22
+ """A failed relationship batch whose discarded results need to be refreshed."""
23
+
24
+ def __init__(self, cause: Exception, numbers: tuple[int, ...]) -> None:
25
+ super().__init__(str(cause))
26
+ self.cause = cause
27
+ self.numbers = numbers
28
+
29
+
30
+ def _state(row: Row) -> str:
31
+ state = string(row["state"])
32
+ if state not in ("open", "closed"):
33
+ raise ValueError("invalid issue state")
34
+ return state
35
+
36
+
37
+ def _body(row: Row) -> str:
38
+ return "" if row["body"] is None else string(row["body"])
39
+
40
+
41
+ def _issue(row: Row) -> tuple[GitHubRecord, ...]:
42
+ n = number(row["number"])
43
+ state = _state(row)
44
+ assignees = sorted({string(user["login"]) for user in rows(row["assignees"])})
45
+ milestone = number(obj(row["milestone"])["number"]) if row["milestone"] is not None else None
46
+ reason = row.get("state_reason")
47
+ issue = {
48
+ "resource": "issue",
49
+ "number": n,
50
+ "state": state,
51
+ "state_reason": string(reason) if reason is not None else None,
52
+ "title": string(row["title"]),
53
+ "milestone": milestone,
54
+ "labels": sorted({string(label["name"]) for label in rows(row["labels"])}),
55
+ "updated_at": string(row["updated_at"]),
56
+ }
57
+ count = row.get("comments")
58
+ if type(count) is int and count >= 0:
59
+ issue["comment_count"] = count
60
+ records = [
61
+ GitHubRecord(
62
+ f"issue/{n}",
63
+ f"issue_{'opened' if state == 'open' else 'closed'}",
64
+ {"number": n, "state": state},
65
+ _body(row),
66
+ details=issue,
67
+ fact=state,
68
+ )
69
+ ]
70
+ if assignees:
71
+ records.append(
72
+ GitHubRecord(f"assignees/{n}", "issue_assignees", {"number": n, "assignees": assignees})
73
+ )
74
+ return tuple(records)
75
+
76
+
77
+ async def fetch_issues(
78
+ api: GitHubReadClient,
79
+ client: httpx.AsyncClient,
80
+ token: str,
81
+ previous: GitHubResource | None,
82
+ ) -> GitHubResource:
83
+ records: list[GitHubRecord] = []
84
+ assigned: set[str] = (
85
+ {row.key for row in previous.records if row.kind == "issue_assignees"}
86
+ if previous
87
+ else set()
88
+ )
89
+ seen: set[int] = set()
90
+ async for row in api.pages(
91
+ client,
92
+ token,
93
+ "/issues",
94
+ params={"state": "all"},
95
+ verify_terminal=True,
96
+ verify_boundaries=True,
97
+ ):
98
+ n = number(row["number"])
99
+ if n in seen:
100
+ raise GitHubUnavailable("GitHub repeated an issue number across pages")
101
+ seen.add(n)
102
+ if "pull_request" in row:
103
+ continue
104
+ issue = _issue(row)
105
+ records.extend(issue)
106
+ key = f"assignees/{n}"
107
+ if len(issue) == 1 and key in assigned:
108
+ records.append(GitHubRecord(key, "issue_assignees", {"number": n, "assignees": []}))
109
+ return GitHubResource(tuple(records), attributes={ISSUE_PAGINATION_VERIFIED: True})
110
+
111
+
112
+ def _issue_number(url: str) -> int:
113
+ return number(int(urlsplit(url).path.rsplit("/", 1)[1]))
114
+
115
+
116
+ async def fetch_comments(
117
+ api: GitHubReadClient,
118
+ client: httpx.AsyncClient,
119
+ token: str,
120
+ watermark: str,
121
+ issues: frozenset[int],
122
+ ) -> tuple[tuple[GitHubRecord, ...], str]:
123
+ observed: list[Row] = []
124
+ params = {"sort": "updated", "direction": "desc"}
125
+ if watermark:
126
+ # GitHub's since filter is exclusive and updated_at has second precision.
127
+ params["since"] = format_time(datetime.fromisoformat(watermark) - timedelta(minutes=5))
128
+ async for row in api.pages(
129
+ client, token, "/issues/comments", params=params, recent=not watermark
130
+ ):
131
+ observed.append(row)
132
+ return _comments(observed, issues, watermark)
133
+
134
+
135
+ def _comments(
136
+ observed: list[Row], issues: frozenset[int], latest: str = ""
137
+ ) -> tuple[tuple[GitHubRecord, ...], str]:
138
+ records: dict[str, GitHubRecord] = {}
139
+ for row in observed:
140
+ n = _issue_number(string(row["issue_url"]))
141
+ identifier = number(row["id"])
142
+ updated = format_time(datetime.fromisoformat(string(row["updated_at"])))
143
+ latest = max(latest, updated)
144
+ if n not in issues:
145
+ continue
146
+ fields = {
147
+ "id": identifier,
148
+ "number": n,
149
+ "created_at": string(row["created_at"]),
150
+ "updated_at": updated,
151
+ }
152
+ if row["user"] is not None:
153
+ fields["author"] = string(obj(row["user"])["login"])
154
+ key = str(identifier)
155
+ if key not in records or records[key].fields["updated_at"] <= updated:
156
+ records[key] = GitHubRecord(key, "issue_comment", fields, _body(row))
157
+ return tuple(records.values()), latest
158
+
159
+
160
+ async def fetch_issue_comments(
161
+ api: GitHubReadClient,
162
+ client: httpx.AsyncClient,
163
+ token: str,
164
+ issue: int,
165
+ version: str,
166
+ expected_count: int,
167
+ ) -> tuple[GitHubRecord, ...]:
168
+ observed = [
169
+ row
170
+ async for row in api.pages(client, token, f"/issues/{issue}/comments", verify_terminal=True)
171
+ ]
172
+ if len(observed) != expected_count:
173
+ raise GitHubUnavailable("GitHub issue comment count changed during history fetch")
174
+ issue_path = f"/repos/{api.repository}/issues/{issue}".casefold()
175
+ if any(
176
+ not urlsplit(string(row["issue_url"])).path.casefold().endswith(issue_path)
177
+ for row in observed
178
+ ):
179
+ raise GitHubUnavailable("GitHub returned a comment for a different issue")
180
+ comments, _ = _comments(observed, frozenset({issue}))
181
+ if len(comments) != len(observed):
182
+ raise GitHubUnavailable("GitHub returned duplicate comments in issue history")
183
+ # A replacement during offset pagination can preserve the count while shifting a page.
184
+ current = obj(await api.get(client, token, f"/issues/{issue}"))
185
+ count = current.get("comments")
186
+ if (
187
+ "pull_request" in current
188
+ or number(current["number"]) != issue
189
+ or _state(current) != "closed"
190
+ or type(count) is not int
191
+ or f"{string(current['updated_at'])}/{count}" != version
192
+ ):
193
+ raise GitHubUnavailable("GitHub issue changed during comment history verification")
194
+ return comments
195
+
196
+
197
+ async def fetch_comment_backfill(
198
+ api: GitHubReadClient,
199
+ client: httpx.AsyncClient,
200
+ token: str,
201
+ position: str,
202
+ issues: frozenset[int],
203
+ ) -> tuple[tuple[GitHubRecord, ...], str]:
204
+ # Overlap a page to tolerate older comments being deleted during the backfill.
205
+ page = int(position or "1")
206
+ records: list[Row] = []
207
+ for offset in range(max(1, page - 1), page + 4):
208
+ batch, more = await api.page(
209
+ client,
210
+ token,
211
+ "/issues/comments",
212
+ offset,
213
+ params={"sort": "created", "direction": "asc"},
214
+ )
215
+ records.extend(batch)
216
+ if not more:
217
+ return _comments(records, issues)[0], "done"
218
+ return _comments(records, issues)[0], str(page + 4)
219
+
220
+
221
+ def _related(row: Row, repository: str) -> int | str:
222
+ n = number(row["number"])
223
+ owner_repo = urlsplit(string(row["repository_url"])).path.lower().split("/")[-2:]
224
+ qualified = "/".join(owner_repo)
225
+ return n if qualified == repository else f"{qualified}#{n}"
226
+
227
+
228
+ async def _relations(
229
+ api: GitHubReadClient, client: httpx.AsyncClient, token: str, issue: Row
230
+ ) -> GitHubRecord:
231
+ n = issue["number"]
232
+ related: dict[str, list[int | str]] = {}
233
+ for key, endpoint in (("sub_issues", "sub_issues"), ("blocked_by", "dependencies/blocked_by")):
234
+ references = [
235
+ _related(row, api.repository)
236
+ async for row in api.pages(
237
+ client,
238
+ token,
239
+ f"/issues/{n}/{endpoint}",
240
+ verify_terminal=True,
241
+ verify_boundaries=True,
242
+ )
243
+ ]
244
+ if len(set(references)) != len(references):
245
+ raise GitHubUnavailable("GitHub repeated an issue relationship across pages")
246
+ related[key] = [
247
+ reference
248
+ for reference in references
249
+ if key != "sub_issues" or isinstance(reference, int)
250
+ ]
251
+ return _issue_metadata(issue, related)
252
+
253
+
254
+ def _issue_metadata(issue: Row, related: dict[str, list[int | str]]) -> GitHubRecord:
255
+ n = issue["number"]
256
+ fields = {"number": n, "labels": issue["labels"], **related}
257
+ if issue["milestone"] is not None:
258
+ fields["milestone"] = issue["milestone"]
259
+ return GitHubRecord(
260
+ f"metadata/{n}",
261
+ "issue_metadata",
262
+ fields,
263
+ details={**issue, **related, ISSUE_PAGINATION_VERIFIED: True},
264
+ )
265
+
266
+
267
+ async def fetch_issue_tree(
268
+ api: GitHubReadClient,
269
+ client: httpx.AsyncClient,
270
+ token: str,
271
+ issues: GitHubResource,
272
+ previous: GitHubResource | None,
273
+ ) -> GitHubResource:
274
+ retries: set[int] = (
275
+ set(previous.attributes.get(ISSUE_RELATION_RETRY, [])) if previous else set()
276
+ )
277
+ old = (
278
+ {
279
+ row.key: row
280
+ for row in previous.records
281
+ if row.details.get(ISSUE_PAGINATION_VERIFIED) is True
282
+ and row.fields["number"] not in retries
283
+ }
284
+ if previous
285
+ else {}
286
+ )
287
+ records: list[GitHubRecord] = []
288
+ async for row in api.pages(client, token, "/milestones", params={"state": "all"}):
289
+ n = number(row["number"])
290
+ fields = {"number": n, "state": _state(row), "title": string(row["title"])}
291
+ records.append(
292
+ GitHubRecord(
293
+ f"milestone/{n}",
294
+ "milestone",
295
+ fields,
296
+ details={
297
+ **fields,
298
+ "resource": "milestone",
299
+ },
300
+ )
301
+ )
302
+ pending: list[Row] = []
303
+ reconcile: list[Row] = []
304
+ for record in issues.records:
305
+ if record.details.get("resource") != "issue":
306
+ continue
307
+ issue = {**record.details, "body": record.body}
308
+ cached = old.get(f"metadata/{issue['number']}")
309
+ if cached is None or cached.details["updated_at"] != issue["updated_at"]:
310
+ pending.append(issue)
311
+ else:
312
+ records.append(
313
+ _issue_metadata(
314
+ issue,
315
+ {
316
+ "sub_issues": cached.details["sub_issues"],
317
+ "blocked_by": cached.details["blocked_by"],
318
+ },
319
+ )
320
+ )
321
+ # Relation changes need not change issue timestamps. Reconcile these
322
+ # separately from known issue changes and bound requests per sweep.
323
+ if previous and previous.generation % 8 == issue["number"] % 8:
324
+ reconcile.append(issue)
325
+ reconcile_count = min(len(reconcile), max(1, MAX_RELATION_REFRESHES // 4))
326
+ if previous and len(reconcile) > reconcile_count:
327
+ offset = (previous.generation // 8 * reconcile_count) % len(reconcile)
328
+ reconcile = reconcile[offset:] + reconcile[:offset]
329
+ pending_count = MAX_RELATION_REFRESHES - reconcile_count
330
+ fresh = [issue for issue in pending if issue["number"] not in retries]
331
+ retry_pending = [issue for issue in pending if issue["number"] in retries]
332
+ if previous is not None and retry_pending:
333
+ offset = previous.generation % len(retry_pending)
334
+ retry_pending = retry_pending[offset:] + retry_pending[:offset]
335
+ refresh = (fresh + retry_pending)[:pending_count] + reconcile[:reconcile_count]
336
+ refreshed: set[int] = set()
337
+ failed: set[int] = set()
338
+ for issue in refresh:
339
+ issue_id: int = issue["number"]
340
+ try:
341
+ records.append(await _relations(api, client, token, issue))
342
+ except GitHubRateLimited as exc:
343
+ raise IssueRelationshipReadError(
344
+ exc, tuple(candidate["number"] for candidate in refresh)
345
+ ) from exc
346
+ except (
347
+ GitHubUnavailable,
348
+ httpx.RequestError,
349
+ KeyError,
350
+ ValueError,
351
+ TypeError,
352
+ OverflowError,
353
+ ):
354
+ failed.add(issue_id)
355
+ else:
356
+ refreshed.add(issue_id)
357
+ return GitHubResource(
358
+ tuple(
359
+ row
360
+ for row in records
361
+ if row.fields["number"] not in failed or row.kind != "issue_metadata"
362
+ ),
363
+ complete=len(pending) <= pending_count and not failed,
364
+ attributes={
365
+ ISSUE_RELATION_RETRY: sorted(retries.difference(refreshed) | failed),
366
+ ISSUE_PAGINATION_VERIFIED: True,
367
+ },
368
+ )
@@ -0,0 +1,210 @@
1
+ """Attribute and read an Actions job's reserved JUnit artifact."""
2
+
3
+ import asyncio
4
+ import hashlib
5
+ import re
6
+ from ipaddress import ip_address
7
+
8
+ import httpx
9
+
10
+ from plotroom.adapters.github import GitHubUnavailable
11
+ from plotroom.adapters.github.junit_xml import junit_evidence
12
+ from plotroom.adapters.github.read import GitHubReadClient, Row, number, obj, string
13
+
14
+ MAX_ATTEMPTS = 5
15
+ MAX_JOBS = 300
16
+ MAX_ARCHIVE = 1024 * 1024
17
+ DOWNLOAD_TIMEOUT = 15.0
18
+
19
+
20
+ class JUnitReader:
21
+ """Reuse checked run and attempt metadata within one check-list refresh."""
22
+
23
+ def __init__(self, api: GitHubReadClient, client: httpx.AsyncClient, token: str) -> None:
24
+ self.api = api
25
+ self.client = client
26
+ self.token = token
27
+ self.runs: dict[int, Row] = {}
28
+ self.jobs: dict[tuple[int, int], list[Row]] = {}
29
+
30
+ async def _run(self, suite: int) -> Row:
31
+ if suite not in self.runs:
32
+ runs, more = await self.api.page(
33
+ self.client,
34
+ self.token,
35
+ "/actions/runs",
36
+ 1,
37
+ key="workflow_runs",
38
+ params={"check_suite_id": suite},
39
+ verify_total=True,
40
+ )
41
+ if more or len(runs) != 1 or number(runs[0]["check_suite_id"]) != suite:
42
+ raise ValueError("GitHub could not attribute the check suite to one Actions run")
43
+ self.runs[suite] = runs[0]
44
+ return self.runs[suite]
45
+
46
+ async def _jobs(self, run: int, attempt: int) -> list[Row]:
47
+ key = (run, attempt)
48
+ if key not in self.jobs:
49
+ jobs: list[Row] = []
50
+ async for job in self.api.pages(
51
+ self.client,
52
+ self.token,
53
+ f"/actions/runs/{run}/attempts/{attempt}/jobs",
54
+ key="jobs",
55
+ verify_total=True,
56
+ verify_boundaries=True,
57
+ ):
58
+ jobs.append(job)
59
+ if len(jobs) > MAX_JOBS:
60
+ raise ValueError("Actions attempt exceeded the JUnit job limit")
61
+ if len({number(job["id"]) for job in jobs}) != len(jobs):
62
+ raise ValueError("GitHub returned duplicate Actions jobs")
63
+ self.jobs[key] = jobs
64
+ return self.jobs[key]
65
+
66
+ def _check_id(self, job: Row) -> int:
67
+ prefix = f"{self.api.endpoint}/check-runs/".lower()
68
+ url = string(job["check_run_url"]).lower()
69
+ check_id = url.removeprefix(prefix)
70
+ if url == check_id or not re.fullmatch(r"[1-9][0-9]{0,18}", check_id):
71
+ raise ValueError("GitHub returned an invalid Actions job check link")
72
+ return number(int(check_id))
73
+
74
+ async def _job(self, run: int, attempts: int, check: Row) -> tuple[int, str]:
75
+ matches: list[tuple[int, str]] = []
76
+ for attempt in range(1, attempts + 1):
77
+ jobs = await self._jobs(run, attempt)
78
+ names = [string(job["name"]) for job in jobs]
79
+ for job, name in zip(jobs, names, strict=True):
80
+ if self._check_id(job) != check["id"]:
81
+ continue
82
+ if (
83
+ not name
84
+ or names.count(name) != 1
85
+ or number(job["run_id"]) != run
86
+ or job["head_sha"] != check["head_sha"]
87
+ or number(job.get("run_attempt", attempt)) != attempt
88
+ or job["status"] != "completed"
89
+ or job["conclusion"] != check["conclusion"]
90
+ ):
91
+ raise ValueError("GitHub returned inconsistent Actions job evidence")
92
+ matches.append((attempt, name))
93
+ if len(matches) != 1:
94
+ raise ValueError("GitHub could not attribute the check to one Actions attempt job")
95
+ return matches[0]
96
+
97
+ async def evidence(self, check: Row, suite: int, *, passed: bool) -> list[Row] | None:
98
+ """Return None for verified absence or ineligibility."""
99
+ run = await self._run(suite)
100
+ repository = obj(run["repository"])
101
+ head_repository = obj(run["head_repository"])
102
+ repository_id = number(repository["id"])
103
+ head_id = number(head_repository["id"])
104
+ project_name = self.api.repository.lower()
105
+ head_name = string(head_repository["full_name"]).lower()
106
+ run_id, attempts = number(run["id"]), number(run["run_attempt"])
107
+ sha = check["head_sha"]
108
+ if (
109
+ string(repository["full_name"]).lower() != project_name
110
+ or run["head_sha"] != sha
111
+ or not re.fullmatch(r"[a-z0-9_.-]+/[a-z0-9_.-]+", head_name)
112
+ or (head_name == project_name) != (head_id == repository_id)
113
+ ):
114
+ raise ValueError("Actions run does not match the repository and check head")
115
+ if head_id != repository_id:
116
+ # The run is positively identified as using a foreign head.
117
+ return None
118
+ if attempts > MAX_ATTEMPTS:
119
+ raise ValueError("Actions run exceeded the JUnit attempt limit")
120
+ attempt, job_name = await self._job(run_id, attempts, check)
121
+ name = f"plotroom-junit-{run_id}-{attempt}-{hashlib.sha256(job_name.encode()).hexdigest()}"
122
+ artifacts, more = await self.api.page(
123
+ self.client,
124
+ self.token,
125
+ f"/actions/runs/{run_id}/artifacts",
126
+ 1,
127
+ key="artifacts",
128
+ params={"name": name},
129
+ verify_total=True,
130
+ )
131
+ if more or len(artifacts) > 1:
132
+ raise ValueError("GitHub returned ambiguous JUnit artifacts")
133
+ if not artifacts:
134
+ return None
135
+ artifact = artifacts[0]
136
+ context = obj(artifact["workflow_run"])
137
+ size = number(artifact["size_in_bytes"])
138
+ digest = string(artifact["digest"])
139
+ if (
140
+ artifact["name"] != name
141
+ or artifact["expired"] is not False
142
+ or size > MAX_ARCHIVE
143
+ or number(context["id"]) != run_id
144
+ or number(context["repository_id"]) != repository_id
145
+ or number(context["head_repository_id"]) != repository_id
146
+ or context["head_sha"] != sha
147
+ or not re.fullmatch(r"sha256:[0-9a-f]{64}", digest)
148
+ ):
149
+ raise ValueError("GitHub returned inconsistent JUnit artifact metadata")
150
+ location = await self.api.artifact_location(self.client, self.token, number(artifact["id"]))
151
+ archive = await _download(_download_url(location, self.api.api_url), size)
152
+ if f"sha256:{hashlib.sha256(archive).hexdigest()}" != digest:
153
+ raise ValueError("JUnit artifact digest did not match")
154
+ return junit_evidence(archive, passed=passed)
155
+
156
+
157
+ def _loopback_origin(url: httpx.URL, api: httpx.URL) -> bool:
158
+ if (url.scheme, url.host, url.port) != (api.scheme, api.host, api.port):
159
+ return False
160
+ try:
161
+ return ip_address(api.host).is_loopback
162
+ except ValueError:
163
+ return False
164
+
165
+
166
+ def _download_url(value: str, api_url: str) -> httpx.URL:
167
+ if any(ord(character) <= 32 or ord(character) >= 127 for character in value) or any(
168
+ character in value for character in ("\\", "#")
169
+ ):
170
+ raise ValueError("Invalid JUnit download location")
171
+ url = httpx.URL(value)
172
+ if url.userinfo or url.scheme not in {"https", "http"}:
173
+ raise ValueError("Invalid JUnit download origin")
174
+ if _loopback_origin(url, httpx.URL(api_url)):
175
+ return url
176
+ azure_blob = re.fullmatch(r"[a-z0-9]{3,24}\.blob\.core\.windows\.net", url.host)
177
+ if (
178
+ url.scheme == "https"
179
+ and url.port is None
180
+ and (url.host == "results-receiver.actions.githubusercontent.com" or azure_blob)
181
+ ):
182
+ return url
183
+ raise ValueError("Untrusted JUnit download origin")
184
+
185
+
186
+ async def _download(url: httpx.URL, size: int) -> bytes:
187
+ # A fresh transport has no credentials, cookies, proxies or redirects. Sending
188
+ # directly also keeps the signed location out of the HTTPX request logger.
189
+ request = httpx.Request("GET", url, headers={"Accept-Encoding": "identity"})
190
+ async with (
191
+ asyncio.timeout(DOWNLOAD_TIMEOUT),
192
+ httpx.AsyncHTTPTransport(trust_env=False) as transport,
193
+ ):
194
+ response = await transport.handle_async_request(request)
195
+ try:
196
+ if (
197
+ response.status_code != 200
198
+ or response.headers.get("Content-Encoding", "identity").lower() != "identity"
199
+ ):
200
+ raise GitHubUnavailable("JUnit artifact download was unavailable")
201
+ body = bytearray()
202
+ async for chunk in response.aiter_raw():
203
+ if len(body) + len(chunk) > size:
204
+ raise GitHubUnavailable("JUnit artifact download exceeded its declared size")
205
+ body.extend(chunk)
206
+ if len(body) != size:
207
+ raise GitHubUnavailable("JUnit artifact download was incomplete")
208
+ return bytes(body)
209
+ finally:
210
+ await response.aclose()