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,738 @@
1
+ """Check runs by commit and workflow attempts on the default branch."""
2
+
3
+ import asyncio
4
+ from collections.abc import Collection
5
+ from dataclasses import dataclass, replace
6
+ from datetime import datetime
7
+ from typing import Any
8
+ from urllib.parse import quote
9
+
10
+ import httpx
11
+
12
+ from plotroom.adapters.github import GitHubRateLimited, GitHubUnavailable
13
+ from plotroom.adapters.github.junit import JUnitReader
14
+ from plotroom.adapters.github.kodus_review import parse_review_check
15
+ from plotroom.adapters.github.read import (
16
+ GitHubNotFound,
17
+ GitHubReadClient,
18
+ Row,
19
+ number,
20
+ obj,
21
+ rows,
22
+ string,
23
+ )
24
+ from plotroom.core.github_projection import MAIN_CI_WINDOW, GitHubRecord, GitHubResource
25
+ from plotroom.core.kodus_review import KODUS_CHECK_FINGERPRINT, KodusReviewPolicy
26
+ from plotroom.core.merge_flakes import (
27
+ has_test_identity,
28
+ is_failure,
29
+ prior_check_failures,
30
+ same_head_recovery,
31
+ )
32
+
33
+ MAX_EXCERPT = 500
34
+ MAX_FAILURE_HISTORY = 100
35
+ JUNIT_MISS_REFRESHES = 4
36
+ JUNIT_UNAVAILABLE_REFRESHES = 2
37
+ MAX_JUNIT_LOOKUP_SECONDS = 4.0
38
+ PENDING_WORKFLOW_STATUSES = frozenset(
39
+ {"expected", "in_progress", "pending", "queued", "requested", "waiting"}
40
+ )
41
+ TEST_PASSED = "plotroom:test-outcome=passed"
42
+ JUNIT_IDENTITY = ("app_id", "suite_id")
43
+
44
+
45
+ @dataclass
46
+ class JUnitBudget:
47
+ """Bound uncached optional lookup time and work within a detail poll."""
48
+
49
+ attempts_left: int = 8
50
+ seconds_left: float = 8.0
51
+
52
+ @property
53
+ def exhausted(self) -> bool:
54
+ return self.attempts_left <= 0 or self.seconds_left <= 0
55
+
56
+ def claim(self) -> float | None:
57
+ if self.exhausted:
58
+ return None
59
+ self.attempts_left -= 1
60
+ return min(self.seconds_left, MAX_JUNIT_LOOKUP_SECONDS)
61
+
62
+
63
+ def _status(row: Row) -> dict[str, Any]:
64
+ fields: dict[str, Any] = {
65
+ "id": number(row["id"]),
66
+ "name": string(row["name"]),
67
+ "status": string(row["status"]),
68
+ }
69
+ if row["conclusion"] is not None:
70
+ fields["conclusion"] = string(row["conclusion"])
71
+ return fields
72
+
73
+
74
+ def _state(fields: Row) -> str:
75
+ return f"{fields['status']}/{fields.get('conclusion', '')}"
76
+
77
+
78
+ def _retain_junit_identity(check: GitHubRecord, cached: GitHubRecord | None, app_slug: Any) -> bool:
79
+ """Keep the identity of an exact check with temporarily incomplete metadata."""
80
+ details = check.details
81
+ if (
82
+ cached is None
83
+ or cached.fields != check.fields
84
+ or details.get("completed_at") is None
85
+ or cached.details.get("junit_eligible") is not True
86
+ or app_slug not in (None, "github-actions")
87
+ ):
88
+ return False
89
+ prior: Row = cached.details.get("junit_prior_identity", cached.details)
90
+ if any(
91
+ key not in prior or details.get(key, prior[key]) != prior[key] for key in JUNIT_IDENTITY
92
+ ):
93
+ return False
94
+ details["junit_prior_identity"] = {key: prior[key] for key in JUNIT_IDENTITY}
95
+ return True
96
+
97
+
98
+ def _junit_waiting_polls(cached: GitHubRecord | None) -> int:
99
+ value = cached.details.get("junit_deferred_polls") if cached is not None else None
100
+ return value if type(value) is int and value > 0 else 0
101
+
102
+
103
+ def _junit_visit_order(cached: GitHubRecord | None) -> tuple[int, int]:
104
+ state = cached.details.get("junit_state") if cached is not None else None
105
+ tier = {"deferred": 0, "retry_deferred": 1}.get(state, 2) if isinstance(state, str) else 2
106
+ return tier, -_junit_waiting_polls(cached)
107
+
108
+
109
+ async def fetch_checks(
110
+ api: GitHubReadClient,
111
+ client: httpx.AsyncClient,
112
+ token: str,
113
+ sha: str,
114
+ previous: GitHubResource | None = None,
115
+ *,
116
+ include_junit: bool = True,
117
+ recovery_check_ids: Collection[int] = (),
118
+ junit_budget: JUnitBudget | None = None,
119
+ allow_junit_lookup: bool = True,
120
+ kodus_review: KodusReviewPolicy | None = None,
121
+ ) -> GitHubResource:
122
+ checks: list[GitHubRecord] = []
123
+ junit = JUnitReader(api, client, token) if include_junit else None
124
+ junit_pending: list[tuple[GitHubRecord, GitHubRecord | None, str, bool, bool]] = []
125
+ prior = (
126
+ {
127
+ (record.fields["id"], record.details.get("completed_at")): record
128
+ for record in previous.records
129
+ }
130
+ if previous and previous.complete
131
+ else {}
132
+ )
133
+ async for row in api.pages(
134
+ client,
135
+ token,
136
+ f"/commits/{quote(sha, safe='')}/check-runs",
137
+ key="check_runs",
138
+ params={"filter": "all"},
139
+ verify_total=True,
140
+ ):
141
+ fields: Row = {**_status(row), "head_sha": sha}
142
+ if row.get("head_sha", sha) != sha:
143
+ raise ValueError("GitHub returned a check for a different head")
144
+ pulls = [number(pull["number"]) for pull in rows(row.get("pull_requests", []))]
145
+ details: Row = {"pull_numbers": pulls}
146
+ if row.get("html_url"):
147
+ details["run_url"] = string(row["html_url"])
148
+ app = obj(row["app"]) if row.get("app") is not None else None
149
+ app_slug = app.get("slug") if app is not None else None
150
+ if app is not None and app.get("id") is not None:
151
+ details["app_id"] = number(app["id"])
152
+ suite = obj(row["check_suite"]) if row.get("check_suite") is not None else None
153
+ if suite is not None and suite.get("id") is not None:
154
+ details["suite_id"] = number(suite["id"])
155
+ if row.get("completed_at") is not None:
156
+ timestamp = datetime.fromisoformat(string(row["completed_at"]))
157
+ if timestamp.utcoffset() is None:
158
+ raise ValueError("check completion time has no offset")
159
+ details["completed_at"] = timestamp.timestamp()
160
+ if kodus_review is not None and (review := parse_review_check(row, kodus_review)):
161
+ details[KODUS_CHECK_FINGERPRINT] = review.fingerprint
162
+ check = GitHubRecord(
163
+ str(fields["id"]), "check_run", fields, details=details, fact=_state(fields)
164
+ )
165
+ passed = fields["status"] == "completed" and fields.get("conclusion") == "success"
166
+ if is_failure(check) or passed:
167
+ cached = prior.get((fields["id"], details.get("completed_at")))
168
+ evidence = "passed_tests" if passed else "annotations"
169
+ actions_check = junit is not None and app_slug == "github-actions"
170
+ has_junit_metadata = (
171
+ actions_check
172
+ and all(key in details for key in JUNIT_IDENTITY)
173
+ and row.get("head_sha") == sha
174
+ )
175
+ prior_junit_identity = (
176
+ junit is not None
177
+ and not has_junit_metadata
178
+ and _retain_junit_identity(check, cached, app_slug)
179
+ )
180
+ if has_junit_metadata or prior_junit_identity:
181
+ details["junit_eligible"] = True
182
+ output = row.get("output")
183
+ count = obj(output).get("annotations_count") if isinstance(output, dict) else None
184
+ # A known zero is an evidence result. An unavailable, malformed or
185
+ # truncated annotation read leaves the field unset and cannot fall back.
186
+ if type(count) is int and 0 <= count <= 300:
187
+ if (
188
+ cached
189
+ and cached.details.get("annotation_count") == count
190
+ and not cached.details.get("junit_evidence")
191
+ and not prior_junit_identity
192
+ and evidence in cached.details
193
+ ):
194
+ details[evidence] = cached.details[evidence]
195
+ else:
196
+ try:
197
+ details[evidence] = await _annotations(
198
+ api, client, token, fields["id"], count, passed=passed
199
+ )
200
+ except GitHubRateLimited:
201
+ raise
202
+ except GitHubUnavailable, httpx.RequestError, KeyError, ValueError, TypeError:
203
+ # The check verdict is readable even if its evidence was unavailable.
204
+ pass
205
+ if evidence in details:
206
+ details["annotation_count"] = count
207
+ if passed and (has_junit_metadata or prior_junit_identity):
208
+ can_read = has_junit_metadata and evidence in details
209
+ junit_pending.append((check, cached, evidence, passed, can_read))
210
+ elif (
211
+ not passed
212
+ and (actions_check or prior_junit_identity)
213
+ and evidence in details
214
+ and not any(
215
+ has_test_identity(entry["path"], entry["test_id"])
216
+ for entry in details[evidence]
217
+ )
218
+ ):
219
+ junit_pending.append((check, cached, evidence, False, has_junit_metadata))
220
+ checks.append(check)
221
+ if len({check.key for check in checks}) != len(checks):
222
+ raise ValueError("GitHub returned duplicate check IDs")
223
+ if junit_pending and junit is not None:
224
+ budget = junit_budget if junit_budget is not None else JUnitBudget()
225
+ failures = [
226
+ *(prior_check_failures(previous) if previous is not None else ()),
227
+ *(check for check in checks if is_failure(check)),
228
+ ]
229
+ # Give waiting first reads and retries a turn before newly expired cooldowns.
230
+ junit_pending.sort(key=lambda entry: _junit_visit_order(entry[1]))
231
+ for check, cached, evidence, passed, can_read in junit_pending:
232
+ if (
233
+ not passed
234
+ or check.fields["id"] in recovery_check_ids
235
+ or any(same_head_recovery(failure, check) for failure in failures)
236
+ ):
237
+ if not can_read:
238
+ _unverified_junit(check.details, evidence, passed=passed, state="unavailable")
239
+ continue
240
+ await _read_junit(
241
+ junit,
242
+ budget,
243
+ check,
244
+ cached,
245
+ evidence,
246
+ passed=passed,
247
+ allow_lookup=allow_junit_lookup,
248
+ )
249
+ history = dict(previous.attributes.get("prior_failures", {})) if previous else {}
250
+ for check in checks:
251
+ if is_failure(check):
252
+ # On a failed evidence read, replace the old occurrence with the incomplete
253
+ # observation. Only a complete current list may use this history.
254
+ history[check.key] = {"fields": check.fields, "details": check.details}
255
+ history = dict(
256
+ sorted(history.items(), key=lambda item: item[1]["fields"]["id"])[-MAX_FAILURE_HISTORY:]
257
+ )
258
+ return GitHubResource(tuple(checks), attributes={"prior_failures": history})
259
+
260
+
261
+ async def _read_junit(
262
+ reader: JUnitReader,
263
+ budget: JUnitBudget,
264
+ check: GitHubRecord,
265
+ cached: GitHubRecord | None,
266
+ evidence: str,
267
+ *,
268
+ passed: bool,
269
+ allow_lookup: bool,
270
+ ) -> None:
271
+ details = check.details
272
+ pass_annotations: list[Row] = details[evidence] if passed else []
273
+ previously_attempted = False
274
+ if (
275
+ cached is not None
276
+ and cached.fields == check.fields
277
+ and details.get("completed_at") is not None
278
+ and all(
279
+ cached.details.get(key) == details[key]
280
+ for key in ("app_id", "suite_id", "annotation_count")
281
+ )
282
+ ):
283
+ if (
284
+ cached.details.get("junit_evidence") is True
285
+ and evidence in cached.details
286
+ and cached.details.get("junit_pass_annotations", []) == pass_annotations
287
+ ):
288
+ details[evidence] = cached.details[evidence]
289
+ details["junit_evidence"] = True
290
+ if pass_annotations:
291
+ details["junit_pass_annotations"] = pass_annotations
292
+ return
293
+ remaining = cached.details.get("junit_miss_remaining")
294
+ if type(remaining) is int and 0 < remaining <= JUNIT_MISS_REFRESHES:
295
+ details["junit_miss_remaining"] = remaining - 1
296
+ return
297
+ remaining = cached.details.get("junit_unavailable_remaining")
298
+ if type(remaining) is int and 0 < remaining <= JUNIT_UNAVAILABLE_REFRESHES:
299
+ details["junit_unavailable_remaining"] = remaining - 1
300
+ _unverified_junit(details, evidence, passed=passed, state="unavailable")
301
+ return
302
+ previously_attempted = (
303
+ cached.details.get("junit_evidence") is True
304
+ or "junit_miss_remaining" in cached.details
305
+ or "junit_unavailable_remaining" in cached.details
306
+ or cached.details.get("junit_state") == "retry_deferred"
307
+ )
308
+ timeout = budget.claim() if allow_lookup else None
309
+ if timeout is None:
310
+ state = "retry_deferred" if previously_attempted else "deferred"
311
+ details["junit_deferred_polls"] = _junit_waiting_polls(cached) + 1
312
+ _unverified_junit(details, evidence, passed=passed, state=state)
313
+ return
314
+ clock = asyncio.get_running_loop().time
315
+ start = clock()
316
+ try:
317
+ async with asyncio.timeout(timeout):
318
+ report = await reader.evidence(check.fields, details["suite_id"], passed=passed)
319
+ except GitHubRateLimited:
320
+ raise
321
+ except (
322
+ GitHubUnavailable,
323
+ httpx.RequestError,
324
+ httpx.InvalidURL,
325
+ TimeoutError,
326
+ KeyError,
327
+ ValueError,
328
+ TypeError,
329
+ ):
330
+ details["junit_unavailable_remaining"] = JUNIT_UNAVAILABLE_REFRESHES
331
+ _unverified_junit(details, evidence, passed=passed, state="unavailable")
332
+ return
333
+ finally:
334
+ budget.seconds_left -= clock() - start
335
+ if report is None:
336
+ # Recheck after a few polls so a late upload still becomes evidence.
337
+ details["junit_miss_remaining"] = JUNIT_MISS_REFRESHES
338
+ else:
339
+ details[evidence] = _merged_passes(pass_annotations, report) if passed else report
340
+ details["junit_evidence"] = True
341
+ if pass_annotations:
342
+ details["junit_pass_annotations"] = pass_annotations
343
+
344
+
345
+ def _unverified_junit(details: Row, evidence: str, *, passed: bool, state: str) -> None:
346
+ # Keep independently verified pass annotations. Deferred or unavailable
347
+ # JUnit cannot establish an empty failure report or an empty pass set.
348
+ details["junit_state"] = state
349
+ if not passed or not details.get(evidence):
350
+ details.pop(evidence, None)
351
+
352
+
353
+ def _merged_passes(annotations: list[Row], report: list[Row]) -> list[Row]:
354
+ by_identity: dict[tuple[str, str], Row] = {}
355
+ for entry in [*annotations, *report]:
356
+ path, test_id = entry["path"], entry["test_id"]
357
+ if has_test_identity(path, test_id):
358
+ by_identity.setdefault((path, test_id), entry)
359
+ return list(by_identity.values())
360
+
361
+
362
+ async def _annotations(
363
+ api: GitHubReadClient,
364
+ client: httpx.AsyncClient,
365
+ token: str,
366
+ check_id: int,
367
+ count: int,
368
+ *,
369
+ passed: bool,
370
+ ) -> list[Row]:
371
+ if not count:
372
+ return []
373
+ annotations = [
374
+ row async for row in api.pages(client, token, f"/check-runs/{check_id}/annotations")
375
+ ]
376
+ if len(annotations) != count:
377
+ raise ValueError("incomplete check run annotations")
378
+ evidence: list[Row] = []
379
+ for row in annotations:
380
+ level = string(row["annotation_level"])
381
+ expected = (
382
+ level == "notice" and row.get("message") == TEST_PASSED
383
+ if passed
384
+ else level == "failure"
385
+ )
386
+ if expected:
387
+ entry = {
388
+ "path": string(row["path"]),
389
+ "test_id": string(row["title"]) if row.get("title") else "",
390
+ }
391
+ if not passed:
392
+ entry["excerpt"] = string(row["message"])[:MAX_EXCERPT]
393
+ evidence.append(entry)
394
+ return evidence
395
+
396
+
397
+ def comparison_paths(files: Any) -> set[str]:
398
+ paths: set[str] = set()
399
+ for row in rows(files):
400
+ paths.add(string(row["filename"]))
401
+ if "previous_filename" in row:
402
+ paths.add(string(row["previous_filename"]))
403
+ elif row["status"] == "renamed":
404
+ raise ValueError("missing previous path in commit comparison")
405
+ if "" in paths:
406
+ raise ValueError("empty path in commit comparison")
407
+ return paths
408
+
409
+
410
+ async def fetch_comparison(
411
+ api: GitHubReadClient, client: httpx.AsyncClient, token: str, base: str, head: str
412
+ ) -> GitHubResource:
413
+ # Comparisons cap their file list at 300. An exact-cap result cannot prove absence.
414
+ # Bound the work for intervening commits and inspect each to catch reverted edits.
415
+ pair = f"{quote(base, safe='')}...{quote(head, safe='')}"
416
+ result = obj(await api.get(client, token, f"/compare/{pair}", {"page": 1, "per_page": 10}))
417
+ commits = rows(result["commits"])
418
+ if (
419
+ result["status"] != "ahead"
420
+ or obj(result["base_commit"])["sha"] != base
421
+ or obj(result["merge_base_commit"])["sha"] != base
422
+ or not 1 <= len(commits) <= 10
423
+ or result["total_commits"] != len(commits)
424
+ or commits[-1]["sha"] != head
425
+ or len(result["files"]) >= 300
426
+ ):
427
+ return GitHubResource((), complete=False)
428
+ paths = comparison_paths(result["files"])
429
+ if len(commits) > 1:
430
+ for commit in commits:
431
+ sha = string(commit["sha"])
432
+ files: list[Row] = []
433
+ async for file in api.pages(
434
+ client,
435
+ token,
436
+ f"/commits/{quote(sha, safe='')}",
437
+ key="files",
438
+ verify_terminal=True,
439
+ ):
440
+ files.append(file)
441
+ if len(files) >= 300:
442
+ return GitHubResource((), complete=False)
443
+ paths.update(comparison_paths(files))
444
+ return GitHubResource((), attributes={"paths": sorted(paths)})
445
+
446
+
447
+ async def fetch_main(
448
+ api: GitHubReadClient,
449
+ client: httpx.AsyncClient,
450
+ token: str,
451
+ image_jobs: tuple[str, ...],
452
+ previous: GitHubResource | None,
453
+ ) -> GitHubResource:
454
+ branch, sha = await fetch_default_branch_head(api, client, token)
455
+ old = (
456
+ {row.key: row for row in previous.records}
457
+ if previous and previous.attributes.get("branch") == branch
458
+ else {}
459
+ )
460
+ runs: dict[str, GitHubRecord] = {}
461
+ async for row in api.pages(
462
+ client, token, "/actions/runs", key="workflow_runs", params={"branch": branch}, recent=True
463
+ ):
464
+ fields = _status(row)
465
+ attempt = number(row["run_attempt"])
466
+ run_id = fields["id"]
467
+ key = f"{run_id}/{attempt}"
468
+ cached = old.get(key)
469
+ main_branch_run = _main_run_attribution(row, api.repository.lower(), branch) is True
470
+ if (
471
+ cached is not None
472
+ and fields["status"] == "completed"
473
+ and cached.fact == _state(fields)
474
+ and cached.details.get("workflow_id") == row.get("workflow_id")
475
+ and cached.details.get("main_branch_run") is main_branch_run
476
+ ):
477
+ runs[key] = cached
478
+ else:
479
+ runs[key] = await _workflow_run(api, client, token, row, main_branch_run)
480
+ preceding = f"{run_id}/{attempt - 1}"
481
+ if attempt > 1 and fields["status"] != "completed" and preceding not in old:
482
+ try:
483
+ earlier = obj(
484
+ await api.get(client, token, f"/actions/runs/{run_id}/attempts/{attempt - 1}")
485
+ )
486
+ except GitHubNotFound:
487
+ continue
488
+ if number(earlier["id"]) != run_id or number(earlier["run_attempt"]) != attempt - 1:
489
+ raise ValueError("GitHub returned a different workflow attempt")
490
+ earlier_on_main = _main_run_attribution(earlier, api.repository.lower(), branch)
491
+ runs[preceding] = await _workflow_run(
492
+ api, client, token, earlier, earlier_on_main is True
493
+ )
494
+ # A rerun replaces the provider's list row for the previous attempt. Keep a bounded
495
+ # recent history so a pending rerun cannot erase the previous completed verdict.
496
+ merged = sorted(
497
+ {**old, **runs}.values(),
498
+ key=lambda run: (run.details["created_at"], run.fields["id"], run.fields["attempt"]),
499
+ reverse=True,
500
+ )
501
+ projected = tuple(
502
+ replace(
503
+ run,
504
+ details={
505
+ **run.details,
506
+ "image_jobs": [job for job in run.fields["jobs"] if job["name"] in image_jobs],
507
+ },
508
+ )
509
+ for run in merged[:100]
510
+ )
511
+ return GitHubResource(projected, attributes={"branch": branch, "head_sha": sha})
512
+
513
+
514
+ async def _workflow_run(
515
+ api: GitHubReadClient, client: httpx.AsyncClient, token: str, row: Row, main_branch_run: bool
516
+ ) -> GitHubRecord:
517
+ jobs = await _workflow_jobs(api, client, token, number(row["id"]), number(row["run_attempt"]))
518
+ record = _workflow_record(row, jobs)
519
+ return replace(record, details={**record.details, "main_branch_run": main_branch_run})
520
+
521
+
522
+ async def fetch_default_branch_head(
523
+ api: GitHubReadClient, client: httpx.AsyncClient, token: str
524
+ ) -> tuple[str, str]:
525
+ metadata = obj(await api.get(client, token, ""))
526
+ branch = string(metadata["default_branch"])
527
+ branch_tip = obj(await api.get(client, token, f"/branches/{quote(branch, safe='')}"))
528
+ return branch, string(obj(branch_tip["commit"])["sha"])
529
+
530
+
531
+ async def fetch_main_ci(
532
+ api: GitHubReadClient,
533
+ client: httpx.AsyncClient,
534
+ token: str,
535
+ workflow: str,
536
+ previous: GitHubResource | None,
537
+ main: GitHubResource | None,
538
+ ) -> GitHubResource:
539
+ branch, sha = (
540
+ (main.attributes["branch"], main.attributes["head_sha"])
541
+ if main is not None
542
+ else await fetch_default_branch_head(api, client, token)
543
+ )
544
+ if not branch or not sha:
545
+ raise ValueError("GitHub returned an invalid default branch")
546
+ repository = api.repository.lower()
547
+ old = (
548
+ {row.key: row for row in previous.records}
549
+ if previous is not None
550
+ and previous.complete
551
+ and previous.attributes.get("branch") == branch
552
+ and previous.attributes.get("workflow") == workflow
553
+ else {}
554
+ )
555
+ records: dict[str, GitHubRecord] = {}
556
+ workflow_ids: set[int] = set()
557
+ seen_runs: set[int] = set()
558
+ async for row in api.pages(
559
+ client,
560
+ token,
561
+ f"/actions/workflows/{quote(workflow, safe='')}/runs",
562
+ key="workflow_runs",
563
+ params={"branch": branch},
564
+ verify_total=True,
565
+ ):
566
+ record = _configured_run(row, repository, branch)
567
+ if record is None:
568
+ continue
569
+ run_id, attempt = number(row["id"]), number(row["run_attempt"])
570
+ workflow_id = number(row["workflow_id"])
571
+ workflow_ids.add(workflow_id)
572
+ if (
573
+ run_id in seen_runs
574
+ or len(workflow_ids) != 1
575
+ or (workflow.isdecimal() and int(workflow) != workflow_id)
576
+ ):
577
+ raise ValueError("GitHub returned inconsistent workflow evidence")
578
+ seen_runs.add(run_id)
579
+ if record.fields["status"] != "completed":
580
+ if attempt == 1:
581
+ continue
582
+ # The list replaces a run's last attempt as soon as its rerun is queued.
583
+ # Recover the prior completed attempt before considering any older run.
584
+ attempt -= 1
585
+ earlier = old.get(f"{run_id}/{attempt}")
586
+ if not _same_completed_attempt(earlier, record, attempt):
587
+ prior = obj(
588
+ await api.get(client, token, f"/actions/runs/{run_id}/attempts/{attempt}")
589
+ )
590
+ earlier = _configured_run(prior, repository, branch)
591
+ if earlier is None or not _same_completed_attempt(earlier, record, attempt):
592
+ raise ValueError("GitHub could not establish the prior completed workflow attempt")
593
+ record = earlier
594
+ key = record.key
595
+ conclusion = record.fields["conclusion"]
596
+ if conclusion in {"success", "startup_failure"}:
597
+ records[key] = record
598
+ break
599
+ cached = old.get(key)
600
+ if (
601
+ cached is not None
602
+ and cached.fact == record.fact
603
+ and _same_completed_attempt(cached, record, attempt)
604
+ and cached.details.get("jobs_complete") is True
605
+ ):
606
+ record = cached
607
+ elif conclusion not in {"cancelled", "skipped"}:
608
+ try:
609
+ jobs = await _workflow_jobs(api, client, token, run_id, attempt, verify_total=True)
610
+ except GitHubRateLimited:
611
+ raise
612
+ except GitHubUnavailable, httpx.RequestError, KeyError, TypeError, ValueError:
613
+ record = replace(record, details={**record.details, "jobs_complete": False})
614
+ else:
615
+ record = replace(
616
+ record,
617
+ fields={**record.fields, "jobs": jobs},
618
+ details={**record.details, "jobs_complete": True},
619
+ )
620
+ records[key] = record
621
+ if len(records) == MAIN_CI_WINDOW:
622
+ break
623
+ return GitHubResource(
624
+ tuple(records.values()),
625
+ attributes={"branch": branch, "head_sha": sha, "workflow": workflow},
626
+ )
627
+
628
+
629
+ def _main_run_attribution(row: Row, repository: str, branch: str) -> bool | None:
630
+ event = row.get("event")
631
+ if isinstance(event, str) and (event.startswith("pull_request") or event == "merge_group"):
632
+ return False
633
+ observed_branch = row.get("head_branch")
634
+ if isinstance(observed_branch, str) and observed_branch and observed_branch != branch:
635
+ return False
636
+ repositories: list[str | None] = []
637
+ for key in ("repository", "head_repository"):
638
+ value = row.get(key)
639
+ name = obj(value).get("full_name") if isinstance(value, dict) else None
640
+ repositories.append(name.lower() if isinstance(name, str) and name else None)
641
+ if any(name is not None and name != repository for name in repositories):
642
+ return False
643
+ if (
644
+ not isinstance(event, str)
645
+ or not event.isascii()
646
+ or not event.isidentifier()
647
+ or event != event.lower()
648
+ or observed_branch != branch
649
+ or None in repositories
650
+ ):
651
+ return None
652
+ return True
653
+
654
+
655
+ def _configured_run(row: Row, repository: str, branch: str) -> GitHubRecord | None:
656
+ attribution = _main_run_attribution(row, repository, branch)
657
+ if attribution is False:
658
+ return None
659
+ if attribution is None or not string(row["head_sha"]):
660
+ raise ValueError("GitHub could not establish the workflow run's repository and trigger")
661
+ status, conclusion = string(row["status"]), row["conclusion"]
662
+ if not (
663
+ isinstance(conclusion, str) and bool(conclusion)
664
+ if status == "completed"
665
+ else status in PENDING_WORKFLOW_STATUSES and conclusion is None
666
+ ):
667
+ raise ValueError("GitHub returned invalid workflow attempt status")
668
+ record = _workflow_record(row, [])
669
+ return replace(
670
+ record,
671
+ details={
672
+ **record.details,
673
+ "repository": repository,
674
+ "event": row["event"],
675
+ "main_branch_run": True,
676
+ },
677
+ )
678
+
679
+
680
+ def _same_completed_attempt(
681
+ earlier: GitHubRecord | None, current: GitHubRecord, attempt: int
682
+ ) -> bool:
683
+ return (
684
+ earlier is not None
685
+ and earlier.fields.get("status") == "completed"
686
+ and isinstance(earlier.fields.get("conclusion"), str)
687
+ and bool(earlier.fields["conclusion"])
688
+ and earlier.fields.get("attempt") == attempt
689
+ and earlier.fields.get("id") == current.fields["id"]
690
+ and earlier.fields.get("head_sha") == current.fields["head_sha"]
691
+ and type(earlier.details.get("workflow_id")) is int
692
+ and earlier.details["workflow_id"] == current.details["workflow_id"]
693
+ and earlier.details.get("repository") == current.details["repository"]
694
+ and earlier.details.get("event") == current.details["event"]
695
+ )
696
+
697
+
698
+ async def _workflow_jobs(
699
+ api: GitHubReadClient,
700
+ client: httpx.AsyncClient,
701
+ token: str,
702
+ run_id: int,
703
+ attempt: int,
704
+ *,
705
+ verify_total: bool = False,
706
+ ) -> list[Row]:
707
+ jobs: list[Row] = []
708
+ async for job in api.pages(
709
+ client,
710
+ token,
711
+ f"/actions/runs/{run_id}/attempts/{attempt}/jobs",
712
+ key="jobs",
713
+ verify_total=verify_total,
714
+ ):
715
+ projected = _status(job)
716
+ if job.get("check_run_url"):
717
+ url = string(job["check_run_url"])
718
+ prefix = f"{api.endpoint}/check-runs/"
719
+ if url.startswith(prefix) and url.removeprefix(prefix).isascii():
720
+ check_id = url.removeprefix(prefix)
721
+ if check_id.isdecimal() and len(check_id) < 20:
722
+ projected["check_run_id"] = number(int(check_id))
723
+ jobs.append(projected)
724
+ if len({job["id"] for job in jobs}) != len(jobs):
725
+ raise ValueError("GitHub returned duplicate workflow jobs")
726
+ return jobs
727
+
728
+
729
+ def _workflow_record(row: Row, jobs: list[Row]) -> GitHubRecord:
730
+ fields = _status(row)
731
+ run_id, attempt = fields["id"], number(row["run_attempt"])
732
+ fields.update({"head_sha": string(row["head_sha"]), "attempt": attempt, "jobs": jobs})
733
+ details: Row = {"created_at": string(row["created_at"])}
734
+ if row.get("workflow_id") is not None:
735
+ details["workflow_id"] = number(row["workflow_id"])
736
+ return GitHubRecord(
737
+ f"{run_id}/{attempt}", "workflow_run", fields, details=details, fact=_state(fields)
738
+ )