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,867 @@
1
+ """Poll GitHub's read projections on the project's existing GitHub cadence."""
2
+
3
+ import asyncio
4
+ import logging
5
+ from collections.abc import Awaitable, Callable
6
+ from dataclasses import replace
7
+ from datetime import datetime
8
+ from functools import partial
9
+ from time import monotonic
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ from plotroom.adapters.github import (
15
+ GitHubCredential,
16
+ GitHubRateLimited,
17
+ GitHubUnavailable,
18
+ repository_client,
19
+ )
20
+ from plotroom.adapters.github.ci import (
21
+ JUnitBudget,
22
+ fetch_checks,
23
+ fetch_comparison,
24
+ fetch_default_branch_head,
25
+ fetch_main,
26
+ fetch_main_ci,
27
+ )
28
+ from plotroom.adapters.github.commit_statuses import fetch_commit_statuses
29
+ from plotroom.adapters.github.deployments import poll_deployments
30
+ from plotroom.adapters.github.issue_details import (
31
+ IssueRelationshipReadError,
32
+ fetch_comment_backfill,
33
+ fetch_comments,
34
+ fetch_issue_comments,
35
+ fetch_issue_tree,
36
+ fetch_issues,
37
+ )
38
+ from plotroom.adapters.github.kodus_review import fetch_kodus_review
39
+ from plotroom.adapters.github.pr_details import (
40
+ fetch_files,
41
+ fetch_labels,
42
+ fetch_pull_text,
43
+ fetch_threads,
44
+ )
45
+ from plotroom.adapters.github.pull_comparison import fetch_pull_comparison
46
+ from plotroom.adapters.github.read import GitHubReadClient, obj, string
47
+ from plotroom.core.events import format_time
48
+ from plotroom.core.github import (
49
+ DETAILS,
50
+ PULL_DETAIL_ATTEMPT_PREFIX,
51
+ PULL_REQUESTS,
52
+ FetchCursor,
53
+ FetchRetry,
54
+ PullRequest,
55
+ apply_ask_comment_history,
56
+ apply_comments,
57
+ apply_merge_sha_backfill,
58
+ )
59
+ from plotroom.core.github_projection import (
60
+ ASK_COMMENT_HISTORY,
61
+ CHECKS,
62
+ COMMENT_BACKFILL,
63
+ COMMENTS,
64
+ COMMIT_STATUSES,
65
+ FILES,
66
+ ISSUE_PAGINATION_VERIFIED,
67
+ ISSUE_RELATION_RETRY,
68
+ ISSUE_TREE,
69
+ ISSUES,
70
+ KODUS_REVIEW,
71
+ LABELS,
72
+ MAIN,
73
+ MAIN_CI,
74
+ MAIN_CI_WINDOW,
75
+ PULL_TEXT,
76
+ THREADS,
77
+ GitHubRecord,
78
+ GitHubResource,
79
+ apply_resource,
80
+ ask_history_version,
81
+ main_verdict,
82
+ )
83
+ from plotroom.core.ledger import Ledger
84
+ from plotroom.core.merge_flakes import (
85
+ FLAKE_COMPARISONS,
86
+ MainPair,
87
+ main_pairs,
88
+ main_recovery_check_ids,
89
+ main_runs,
90
+ record_main_flakes,
91
+ record_pull_flakes,
92
+ record_same_head,
93
+ )
94
+ from plotroom.core.merge_gate import GateSnapshot
95
+ from plotroom.core.merge_overlap import PULL_COMPARISON, bind_overlap_labels
96
+ from plotroom.core.unit_of_work import UnitOfWork
97
+ from plotroom.ports.clock import Clock
98
+
99
+ log = logging.getLogger("plotroom.github")
100
+ MAX_NEW_COMPARISONS = 4
101
+ MAX_ASK_HISTORIES = 4
102
+ MAX_MERGE_SHA_READS = 2
103
+ KODUS_REVIEW_READ_TIMEOUT = 5.0
104
+ MERGE_SHA_READ_TIMEOUT = 3
105
+ _READ_ERRORS = (
106
+ GitHubUnavailable,
107
+ httpx.RequestError,
108
+ KeyError,
109
+ ValueError,
110
+ TypeError,
111
+ OverflowError,
112
+ )
113
+
114
+
115
+ class _KodusReviewBudgetExhausted(Exception):
116
+ """There is no time left to attempt another review read."""
117
+
118
+
119
+ async def _pull_revision_current(uow: UnitOfWork, pull: PullRequest) -> bool:
120
+ current = await uow.pull_request(pull.repository, pull.number)
121
+ return current is not None and (
122
+ current.head_sha,
123
+ current.version,
124
+ current.updated_at,
125
+ current.state,
126
+ current.complete,
127
+ ) == (pull.head_sha, pull.version, pull.updated_at, pull.state, pull.complete)
128
+
129
+
130
+ class GitHubDetailPoller:
131
+ def __init__(
132
+ self,
133
+ ledger: Ledger,
134
+ clock: Clock,
135
+ api: GitHubReadClient,
136
+ credential: GitHubCredential,
137
+ image_jobs: tuple[str, ...] = (),
138
+ *,
139
+ include_issue_tree: bool = False,
140
+ ci_workflow: str | None = None,
141
+ on_merge_evidence: Callable[[int], Awaitable[object]] | None = None,
142
+ ) -> None:
143
+ self.ledger = ledger
144
+ self.clock = clock
145
+ self.api = api
146
+ self.credential = credential
147
+ self.image_jobs = image_jobs
148
+ self.include_issue_tree = include_issue_tree
149
+ self.ci_workflow = ci_workflow
150
+ self.on_merge_evidence = on_merge_evidence
151
+ self._comparison_cursor = 0
152
+ self._ask_history_offset = 0
153
+ self._junit_offset = 0
154
+
155
+ async def confirm_gate(self, snapshot: GateSnapshot) -> GateSnapshot | None:
156
+ """Read authoritative evidence on demand for a pinned clerk recheck."""
157
+ try:
158
+ async with (
159
+ asyncio.timeout(20),
160
+ repository_client(self.credential) as client,
161
+ ):
162
+ return await self.read_gate_snapshot(client, snapshot)
163
+ except GitHubRateLimited as exc:
164
+ await self.record_rate_limit(exc)
165
+ return None
166
+ except (
167
+ GitHubUnavailable,
168
+ httpx.RequestError,
169
+ TimeoutError,
170
+ ValueError,
171
+ KeyError,
172
+ TypeError,
173
+ OverflowError,
174
+ ):
175
+ return None
176
+
177
+ async def read_gate_snapshot(
178
+ self, client: httpx.AsyncClient, snapshot: GateSnapshot
179
+ ) -> GateSnapshot | None:
180
+ pull = snapshot.pull
181
+ workflow = self.ci_workflow
182
+ if pull is None or workflow is None or await self.cooling_down():
183
+ return None
184
+ api, token = self.api, await self.credential.token()
185
+ observed_at = format_time(self.clock.now())
186
+ main_ci = await fetch_main_ci(api, client, token, workflow, snapshot.main_ci, None)
187
+ branch = main_ci.attributes["branch"]
188
+ head = main_ci.attributes["head_sha"]
189
+ main = GitHubResource(
190
+ (),
191
+ attributes={"branch": branch, "head_sha": head},
192
+ as_of=observed_at,
193
+ )
194
+ checks = await fetch_checks(
195
+ api,
196
+ client,
197
+ token,
198
+ pull.head_sha,
199
+ snapshot.checks,
200
+ include_junit=False,
201
+ kodus_review=self.ledger.merge_gate_policy.kodus_review,
202
+ )
203
+ try:
204
+ statuses = await fetch_commit_statuses(api, client, token, pull.head_sha)
205
+ except GitHubRateLimited:
206
+ raise
207
+ except _READ_ERRORS:
208
+ statuses = GitHubResource((), complete=False)
209
+ labels = await fetch_labels(api, client, token, pull)
210
+ threads = await fetch_threads(api, client, token, pull)
211
+ text = await fetch_pull_text(api, client, token, pull)
212
+ comparison = await fetch_pull_comparison(
213
+ api,
214
+ client,
215
+ token,
216
+ pull,
217
+ branch,
218
+ head,
219
+ snapshot.comparison,
220
+ )
221
+ review = None
222
+ if self.ledger.merge_gate_policy.kodus_review is not None:
223
+ try:
224
+ review = await self._read_kodus_review(client, token, pull)
225
+ except GitHubRateLimited:
226
+ raise
227
+ except _READ_ERRORS:
228
+ review = GitHubResource((), complete=False)
229
+ current = obj(await api.get(client, token, f"/pulls/{pull.number}"))
230
+ draft = current["draft"]
231
+ identity = obj(current["head"])
232
+ if (
233
+ type(draft) is not bool
234
+ or current["state"] != "open"
235
+ or identity["sha"] != pull.head_sha
236
+ or identity["ref"] != pull.branch
237
+ or string(obj(identity["repo"])["full_name"]).lower() != pull.head_repository
238
+ or format_time(datetime.fromisoformat(string(current["updated_at"]))) != pull.updated_at
239
+ ):
240
+ return None
241
+ if await fetch_default_branch_head(api, client, token) != (branch, head):
242
+ return None
243
+ return replace(
244
+ snapshot,
245
+ pull=replace(pull, draft=draft, as_of=observed_at),
246
+ pull_cursor=None,
247
+ checks=replace(checks, as_of=observed_at),
248
+ commit_statuses=replace(
249
+ statuses,
250
+ attributes={**statuses.attributes, "checks_generation": checks.generation},
251
+ as_of=observed_at,
252
+ ),
253
+ main_ci=replace(main_ci, as_of=observed_at),
254
+ main=main,
255
+ threads=replace(threads, as_of=observed_at),
256
+ labels=replace(bind_overlap_labels(labels, snapshot.labels, pull), as_of=observed_at),
257
+ pull_text=replace(text, as_of=observed_at),
258
+ comparison=replace(comparison, as_of=observed_at),
259
+ kodus_review=replace(review, as_of=observed_at) if review is not None else None,
260
+ )
261
+
262
+ async def cooling_down(self) -> bool:
263
+ repository = self.api.repository
264
+ retry = await self.ledger.fetch_retry(repository, DETAILS)
265
+ pr_retry = await self.ledger.fetch_retry(repository, PULL_REQUESTS)
266
+ now = self.clock.now()
267
+ return any(row and datetime.fromisoformat(row.until) > now for row in (retry, pr_retry))
268
+
269
+ async def record_rate_limit(self, exc: GitHubRateLimited) -> None:
270
+ await self.ledger.set_github_error("GitHub rate limit reached")
271
+ repository = self.api.repository
272
+ retry = await self.ledger.fetch_retry(repository, DETAILS)
273
+ backoff = retry.next_backoff if retry else 60
274
+ until = format_time(exc.retry_at(self.clock.now(), backoff))
275
+ next_retry = FetchRetry(max(until, retry.until) if retry else until, min(backoff * 2, 900))
276
+ await self.ledger.run(
277
+ "system", lambda uow: uow.save_fetch_retry(repository, DETAILS, next_retry)
278
+ )
279
+
280
+ async def poll(self, client: httpx.AsyncClient) -> None:
281
+ repository = self.api.repository
282
+ if await self.cooling_down():
283
+ return
284
+ retry = await self.ledger.fetch_retry(repository, DETAILS)
285
+ try:
286
+ token = await self.credential.token()
287
+ await self._poll_resources(client, token)
288
+ await self._backfill_merge_shas(client, token)
289
+ except GitHubRateLimited as exc:
290
+ await self.record_rate_limit(exc)
291
+ except GitHubUnavailable:
292
+ # The PR poller exposes credential availability in the project snapshot.
293
+ return
294
+ else:
295
+ if retry is not None and await self.ledger.fetch_retry(repository, DETAILS) == retry:
296
+ await self.ledger.run(
297
+ "system", lambda uow: uow.save_fetch_retry(repository, DETAILS, None)
298
+ )
299
+
300
+ async def _backfill_merge_shas(self, client: httpx.AsyncClient, token: str) -> None:
301
+ as_of = format_time(self.clock.now())
302
+ timeout = min(
303
+ MERGE_SHA_READ_TIMEOUT,
304
+ self.ledger.merge_gate_policy.max_age.total_seconds() / (4 * MAX_MERGE_SHA_READS),
305
+ )
306
+ pending = await self.ledger.github_pending_merge_shas(
307
+ self.api.repository, as_of, MAX_MERGE_SHA_READS
308
+ )
309
+ for pull in pending:
310
+ sha = None
311
+ rate_limit = None
312
+ try:
313
+ async with asyncio.timeout(timeout):
314
+ sha = await self.api.pull_merge_sha(client, token, pull)
315
+ except GitHubRateLimited as exc:
316
+ rate_limit = exc
317
+ except (*_READ_ERRORS, TimeoutError, RecursionError):
318
+ pass # Optional evidence remains pending, with no provider payload in logs.
319
+ await self.ledger.run(
320
+ "system",
321
+ partial(
322
+ apply_merge_sha_backfill,
323
+ target=pull,
324
+ merge_sha=sha,
325
+ as_of=as_of,
326
+ ),
327
+ )
328
+ if rate_limit is not None:
329
+ raise rate_limit
330
+
331
+ async def _poll_resources(self, client: httpx.AsyncClient, token: str) -> None:
332
+ api = self.api
333
+ main = await self._refresh(
334
+ MAIN,
335
+ "",
336
+ lambda previous: fetch_main(api, client, token, self.image_jobs, previous),
337
+ )
338
+ main_ci = None
339
+ if (workflow := self.ci_workflow) is not None:
340
+ main_ci = await self._refresh(
341
+ MAIN_CI,
342
+ "",
343
+ lambda previous: fetch_main_ci(api, client, token, workflow, previous, main),
344
+ )
345
+ issues = await self._refresh(
346
+ ISSUES, "", lambda previous: fetch_issues(api, client, token, previous)
347
+ )
348
+ if issues is not None:
349
+ numbers = frozenset(
350
+ row.fields["number"]
351
+ for row in issues.records
352
+ if row.kind in ("issue_opened", "issue_closed")
353
+ )
354
+ await self._poll_comments(client, token, numbers)
355
+ await self._poll_ask_histories(client, token, issues)
356
+ targets: dict[str, list[PullRequest]] = {}
357
+ history = tuple(
358
+ sorted(
359
+ {
360
+ run.key: run
361
+ for run in (*main_runs(main), *main_runs(main_ci, limit=MAIN_CI_WINDOW))
362
+ }.values(),
363
+ key=lambda run: (
364
+ run.details["created_at"],
365
+ run.fields["id"],
366
+ run.fields["attempt"],
367
+ ),
368
+ reverse=True,
369
+ )
370
+ )
371
+ if main is not None:
372
+ targets[main.attributes["head_sha"]] = []
373
+ verdict = main_verdict(main)
374
+ if verdict is not None:
375
+ targets[verdict.fields["head_sha"]] = []
376
+ for run in history:
377
+ targets.setdefault(run.fields["head_sha"], [])
378
+ pulls = await self.ledger.github_pull_targets(api.repository)
379
+ for pull in pulls:
380
+ targets.setdefault(pull.head_sha, []).append(pull)
381
+ checks: dict[str, GitHubResource] = {}
382
+ minimum_checks = self.ledger.merge_gate_policy.min_checks
383
+ status_heads = (
384
+ {pull.head_sha for pull in pulls if pull.state == "open"}
385
+ if minimum_checks is not None and minimum_checks > 0
386
+ else set[str]()
387
+ )
388
+ recoveries = main_recovery_check_ids(history)
389
+ junit_budget = JUnitBudget()
390
+ junit_start = self._junit_offset % max(1, len(targets))
391
+ for index, (sha, candidates) in enumerate(targets.items()):
392
+ attempts_before = junit_budget.attempts_left
393
+ try:
394
+ result = await self._refresh(
395
+ CHECKS,
396
+ sha,
397
+ lambda previous, sha=sha, allow_lookup=index >= junit_start: fetch_checks(
398
+ api,
399
+ client,
400
+ token,
401
+ sha,
402
+ previous,
403
+ recovery_check_ids=recoveries.get(sha, ()),
404
+ junit_budget=junit_budget,
405
+ allow_junit_lookup=allow_lookup,
406
+ kodus_review=self.ledger.merge_gate_policy.kodus_review,
407
+ ),
408
+ pulls=tuple(pull.number for pull in candidates),
409
+ read_statuses=partial(fetch_commit_statuses, api, client, token, sha)
410
+ if sha in status_heads
411
+ else None,
412
+ )
413
+ except GitHubRateLimited:
414
+ for pull in candidates:
415
+ await self._record_pull_attempt(pull, complete=False)
416
+ raise
417
+ if result is not None:
418
+ checks[sha] = result
419
+ if junit_budget.exhausted and junit_budget.attempts_left != attempts_before:
420
+ self._junit_offset = index + 1
421
+ # Finish this head's selected pulls before a later head can stop the pass.
422
+ for pull in candidates:
423
+ await self._poll_pull_details(
424
+ client,
425
+ token,
426
+ pull,
427
+ main,
428
+ result,
429
+ needs_statuses=pull.state == "open" and sha in status_heads,
430
+ )
431
+ if not junit_budget.exhausted:
432
+ self._junit_offset = 0
433
+ await self._poll_main_flakes(client, token, history, checks)
434
+ if self.on_merge_evidence is not None:
435
+ for pull in pulls:
436
+ await self.on_merge_evidence(pull.number)
437
+
438
+ if self.include_issue_tree or await self.ledger.goals_use_blockers():
439
+ if issues is not None:
440
+ await self._refresh(
441
+ ISSUE_TREE,
442
+ "",
443
+ lambda previous: fetch_issue_tree(api, client, token, issues, previous),
444
+ )
445
+ else:
446
+ await self._mark_incomplete(ISSUE_TREE, "")
447
+ await poll_deployments(self.ledger, api, client, token, format_time(self.clock.now()))
448
+ if self.ledger.merge_gate_policy.kodus_review is not None:
449
+ await self._poll_kodus_reviews(client, token, pulls)
450
+
451
+ async def _poll_pull_details(
452
+ self,
453
+ client: httpx.AsyncClient,
454
+ token: str,
455
+ pull: PullRequest,
456
+ main: GitHubResource | None,
457
+ checks: GitHubResource | None,
458
+ *,
459
+ needs_statuses: bool,
460
+ ) -> None:
461
+ api = self.api
462
+ complete = False
463
+ try:
464
+ observations: dict[str, GitHubResource | None] = {}
465
+ for resource, read in (
466
+ (THREADS, fetch_threads),
467
+ (FILES, fetch_files),
468
+ (LABELS, fetch_labels),
469
+ ):
470
+ observations[resource] = await self._refresh(
471
+ resource,
472
+ str(pull.number),
473
+ lambda _, read=read: read(api, client, token, pull),
474
+ pulls=(pull.number,),
475
+ pull=pull,
476
+ )
477
+ if self.ci_workflow is not None:
478
+ if pull.state == "open":
479
+ observations[PULL_COMPARISON] = (
480
+ await self._refresh(
481
+ PULL_COMPARISON,
482
+ str(pull.number),
483
+ lambda previous: fetch_pull_comparison(
484
+ api,
485
+ client,
486
+ token,
487
+ pull,
488
+ main.attributes["branch"],
489
+ main.attributes["head_sha"],
490
+ previous,
491
+ ),
492
+ pull=pull,
493
+ )
494
+ if main is not None and main.complete
495
+ else None
496
+ )
497
+ observations[PULL_TEXT] = await self._refresh(
498
+ PULL_TEXT,
499
+ str(pull.number),
500
+ lambda _: fetch_pull_text(api, client, token, pull),
501
+ pull=pull,
502
+ )
503
+ files = observations[FILES]
504
+ if files is not None and checks is not None:
505
+ await self.ledger.run(
506
+ "system",
507
+ partial(
508
+ record_pull_flakes,
509
+ repository=api.repository,
510
+ pull=pull,
511
+ checks=checks,
512
+ files=files,
513
+ ),
514
+ )
515
+ complete = (
516
+ checks is not None
517
+ and checks.complete
518
+ and all(value is not None and value.complete for value in observations.values())
519
+ )
520
+ finally:
521
+ await self._record_pull_attempt(pull, complete, needs_statuses=needs_statuses)
522
+
523
+ async def _poll_kodus_reviews(
524
+ self, client: httpx.AsyncClient, token: str, pulls: tuple[PullRequest, ...]
525
+ ) -> None:
526
+ deadline = monotonic() + min(
527
+ KODUS_REVIEW_READ_TIMEOUT, self.ledger.merge_gate_policy.max_age.total_seconds() / 4
528
+ )
529
+ attempts: list[tuple[tuple[str, int, int], PullRequest]] = []
530
+ for pull in pulls:
531
+ if pull.state != "open":
532
+ continue
533
+ previous = await self.ledger.github_resource(
534
+ self.api.repository, KODUS_REVIEW, str(pull.number)
535
+ )
536
+ last_attempt = previous.as_of if previous is not None else ""
537
+ generation = previous.generation if previous is not None else 0
538
+ attempts.append(((last_attempt, generation, pull.number), pull))
539
+ # Ordinary PR targets rotate independently. Prioritize the least recently
540
+ # attempted review within each batch so a slow PR cannot monopolize it.
541
+ for _, pull in sorted(attempts, key=lambda target: target[0]):
542
+ try:
543
+ await self._refresh(
544
+ KODUS_REVIEW,
545
+ str(pull.number),
546
+ lambda _, pull=pull: self._read_kodus_review(
547
+ client, token, pull, deadline=deadline
548
+ ),
549
+ pull=pull,
550
+ )
551
+ except _KodusReviewBudgetExhausted:
552
+ break
553
+
554
+ async def _read_kodus_review(
555
+ self,
556
+ client: httpx.AsyncClient,
557
+ token: str,
558
+ pull: PullRequest,
559
+ *,
560
+ deadline: float | None = None,
561
+ ) -> GitHubResource:
562
+ policy = self.ledger.merge_gate_policy.kodus_review
563
+ assert policy is not None
564
+ timeout = KODUS_REVIEW_READ_TIMEOUT
565
+ if deadline is not None:
566
+ timeout = min(timeout, deadline - monotonic())
567
+ if timeout <= 0:
568
+ raise _KodusReviewBudgetExhausted
569
+ try:
570
+ async with asyncio.timeout(timeout):
571
+ return await fetch_kodus_review(self.api, client, token, pull, policy)
572
+ except TimeoutError, RecursionError:
573
+ raise GitHubUnavailable("Kodus review read exceeded its limits") from None
574
+
575
+ async def _poll_main_flakes(
576
+ self,
577
+ client: httpx.AsyncClient,
578
+ token: str,
579
+ history: tuple[GitHubRecord, ...],
580
+ checks: dict[str, GitHubResource],
581
+ ) -> None:
582
+ api = self.api
583
+ pairs = main_pairs(history, checks)
584
+ distinct = {(pair.base, pair.head): pair for pair in pairs if pair.base != pair.head}
585
+ observations: dict[str, GitHubResource | None] = {}
586
+ pending: list[tuple[str, MainPair]] = []
587
+ for pair in distinct.values():
588
+ key = f"{pair.base}...{pair.head}"
589
+ cached = await self.ledger.github_resource(api.repository, FLAKE_COMPARISONS, key)
590
+ if cached is not None and cached.complete:
591
+ observations[key] = cached
592
+ else:
593
+ pending.append((key, pair))
594
+ if pending:
595
+ offset = self._comparison_cursor % len(pending)
596
+ for key, pair in (pending[offset:] + pending[:offset])[:MAX_NEW_COMPARISONS]:
597
+ observations[key] = await self._refresh(
598
+ FLAKE_COMPARISONS,
599
+ key,
600
+ lambda _, pair=pair: fetch_comparison(api, client, token, pair.base, pair.head),
601
+ )
602
+ self._comparison_cursor = offset + MAX_NEW_COMPARISONS
603
+ for pair in pairs:
604
+ comparison = observations.get(f"{pair.base}...{pair.head}")
605
+ await self.ledger.run(
606
+ "system",
607
+ partial(
608
+ record_main_flakes, repository=api.repository, pair=pair, comparison=comparison
609
+ ),
610
+ )
611
+
612
+ async def _record_pull_attempt(
613
+ self, pull: PullRequest, complete: bool, *, needs_statuses: bool = False
614
+ ) -> None:
615
+ async def write(uow: UnitOfWork) -> None:
616
+ if not await _pull_revision_current(uow, pull):
617
+ return
618
+ if complete and needs_statuses:
619
+ checks = await uow.github_resource(pull.repository, CHECKS, pull.head_sha)
620
+ statuses = await uow.github_resource(
621
+ pull.repository, COMMIT_STATUSES, pull.head_sha
622
+ )
623
+ statuses_complete = (
624
+ checks is not None
625
+ and checks.complete
626
+ and statuses is not None
627
+ and statuses.complete
628
+ and statuses.attributes.get("repository") == pull.repository
629
+ and statuses.attributes.get("head_sha") == pull.head_sha
630
+ and statuses.attributes.get("checks_generation") == checks.generation
631
+ )
632
+ else:
633
+ statuses_complete = not needs_statuses
634
+ scope = f"{PULL_DETAIL_ATTEMPT_PREFIX}{pull.number}"
635
+ prior = await uow.fetch_cursor(pull.repository, scope)
636
+ watermark = (
637
+ f"{pull.updated_at}:{pull.version}" if complete and statuses_complete else ""
638
+ )
639
+ await uow.save_fetch_cursor(
640
+ pull.repository,
641
+ scope,
642
+ FetchCursor(
643
+ watermark, format_time(self.clock.now()), prior.generation + 1 if prior else 1
644
+ ),
645
+ )
646
+
647
+ await self.ledger.run("system", write)
648
+
649
+ async def _poll_comments(
650
+ self, client: httpx.AsyncClient, token: str, numbers: frozenset[int]
651
+ ) -> None:
652
+ repository = self.api.repository
653
+ for resource, fetch in (
654
+ (COMMENTS, fetch_comments),
655
+ (COMMENT_BACKFILL, fetch_comment_backfill),
656
+ ):
657
+ baseline = await self.ledger.fetch_cursor(repository, resource)
658
+ position = baseline.watermark if baseline else ""
659
+ if position == "done":
660
+ continue
661
+ try:
662
+ comments, watermark = await fetch(self.api, client, token, position, numbers)
663
+ except GitHubRateLimited:
664
+ raise
665
+ except _READ_ERRORS:
666
+ log.warning(
667
+ "GitHub issue comment refresh failed", extra={"project": self.ledger.project_id}
668
+ )
669
+ continue
670
+ await self.ledger.run(
671
+ "system",
672
+ partial(
673
+ apply_comments,
674
+ repository=repository,
675
+ baseline=baseline,
676
+ comments=comments,
677
+ watermark=watermark,
678
+ as_of=format_time(self.clock.now()),
679
+ cursor_resource=resource,
680
+ ),
681
+ )
682
+
683
+ async def _poll_ask_histories(
684
+ self, client: httpx.AsyncClient, token: str, issues: GitHubResource
685
+ ) -> None:
686
+ if not issues.complete:
687
+ return
688
+ repository = self.api.repository
689
+ pending = await self.ledger.pending_ask_issues(repository)
690
+ targets: list[tuple[int, str, int]] = []
691
+ for row in issues.records:
692
+ if row.kind != "issue_closed" or (number := row.fields["number"]) not in pending:
693
+ continue
694
+ coverage = ask_history_version(row)
695
+ if coverage is None:
696
+ continue
697
+ version, count = coverage
698
+ prior = await self.ledger.github_resource(repository, ASK_COMMENT_HISTORY, str(number))
699
+ if prior is None or prior.attributes.get("version") != version:
700
+ targets.append((number, version, count))
701
+ if not targets:
702
+ return
703
+ targets.sort()
704
+ offset = self._ask_history_offset % len(targets)
705
+ self._ask_history_offset = offset + MAX_ASK_HISTORIES
706
+ for number, version, count in (targets[offset:] + targets[:offset])[:MAX_ASK_HISTORIES]:
707
+ try:
708
+ comments = await fetch_issue_comments(
709
+ self.api, client, token, number, version, count
710
+ )
711
+ except GitHubRateLimited:
712
+ raise
713
+ except _READ_ERRORS:
714
+ log.warning("GitHub ask comment history refresh failed", extra={"issue": number})
715
+ continue
716
+ # Merge the records into the existing comment projection before marking this
717
+ # particular issue version covered. The writer sees the facts and proof together.
718
+ await self.ledger.run(
719
+ "system",
720
+ partial(
721
+ apply_ask_comment_history,
722
+ repository=repository,
723
+ number=number,
724
+ version=version,
725
+ comments=comments,
726
+ as_of=format_time(self.clock.now()),
727
+ ),
728
+ )
729
+
730
+ async def _mark_incomplete(
731
+ self,
732
+ resource: str,
733
+ scope: str,
734
+ pulls: tuple[int, ...] = (),
735
+ *,
736
+ retry_issues: tuple[int, ...] = (),
737
+ pull: PullRequest | None = None,
738
+ ) -> None:
739
+ async def write(uow: UnitOfWork) -> None:
740
+ repository = self.api.repository
741
+ if pull is not None and not await _pull_revision_current(uow, pull):
742
+ return
743
+ attributes: dict[str, Any] = (
744
+ {ISSUE_PAGINATION_VERIFIED: False} if resource == ISSUE_TREE else {}
745
+ )
746
+ if retry_issues:
747
+ previous = await uow.github_resource(repository, resource, scope)
748
+ pending: set[int] = (
749
+ set(previous.attributes.get(ISSUE_RELATION_RETRY, [])) if previous else set()
750
+ )
751
+ attributes[ISSUE_RELATION_RETRY] = sorted(pending.union(retry_issues))
752
+ await apply_resource(
753
+ uow,
754
+ repository,
755
+ resource,
756
+ scope,
757
+ GitHubResource((), complete=False, attributes=attributes),
758
+ format_time(self.clock.now()),
759
+ pulls=pulls,
760
+ )
761
+
762
+ await self.ledger.run("system", write)
763
+
764
+ async def _refresh(
765
+ self,
766
+ resource: str,
767
+ scope: str,
768
+ read: Callable[[GitHubResource | None], Awaitable[GitHubResource]],
769
+ *,
770
+ pulls: tuple[int, ...] = (),
771
+ pull: PullRequest | None = None,
772
+ read_statuses: Callable[[], Awaitable[GitHubResource]] | None = None,
773
+ ) -> GitHubResource | None:
774
+ repository = self.api.repository
775
+ previous = await self.ledger.github_resource(repository, resource, scope)
776
+ started_at = format_time(self.clock.now()) if read_statuses is not None else None
777
+ try:
778
+ result = await read(previous)
779
+ except IssueRelationshipReadError as exc:
780
+ await self._mark_incomplete(resource, scope, pulls, retry_issues=exc.numbers)
781
+ if isinstance(exc.cause, GitHubRateLimited):
782
+ raise exc.cause from exc
783
+ log.warning(
784
+ "GitHub issue relationship refresh failed",
785
+ extra={"project": self.ledger.project_id},
786
+ )
787
+ return None
788
+ except GitHubRateLimited:
789
+ await self._mark_incomplete(resource, scope, pulls, pull=pull)
790
+ raise
791
+ except _READ_ERRORS:
792
+ if previous is None or previous.complete:
793
+ log.warning(
794
+ "GitHub projection refresh failed",
795
+ extra={"project": self.ledger.project_id, "resource": resource},
796
+ )
797
+ if resource in (ISSUE_TREE, KODUS_REVIEW) or previous is None or previous.complete:
798
+ await self._mark_incomplete(resource, scope, pulls, pull=pull)
799
+ return None
800
+
801
+ statuses = None
802
+ if read_statuses is not None:
803
+ try:
804
+ statuses = await read_statuses()
805
+ except GitHubRateLimited:
806
+ await self._mark_incomplete(COMMIT_STATUSES, scope)
807
+ raise
808
+ except _READ_ERRORS:
809
+ statuses = GitHubResource((), complete=False)
810
+ prior_statuses = await self.ledger.github_resource(
811
+ repository, COMMIT_STATUSES, scope
812
+ )
813
+ if prior_statuses is None or prior_statuses.complete:
814
+ log.warning(
815
+ "GitHub projection refresh failed",
816
+ extra={"project": self.ledger.project_id, "resource": COMMIT_STATUSES},
817
+ )
818
+
819
+ async def write(uow: UnitOfWork) -> None:
820
+ if (
821
+ resource == ISSUE_TREE
822
+ and await uow.github_resource(repository, resource, scope) != previous
823
+ ):
824
+ return
825
+ if pull is not None and not await _pull_revision_current(uow, pull):
826
+ return
827
+ observed = result
828
+ if resource == LABELS and pull is not None:
829
+ previous_labels = await uow.github_resource(repository, LABELS, scope)
830
+ observed = bind_overlap_labels(result, previous_labels, pull)
831
+ as_of = started_at or format_time(self.clock.now())
832
+ await apply_resource(
833
+ uow,
834
+ repository,
835
+ resource,
836
+ scope,
837
+ observed,
838
+ as_of,
839
+ pulls=pulls,
840
+ )
841
+ if statuses is not None:
842
+ # Bind the two sources in the same transaction, including when
843
+ # only the Check Runs read succeeded.
844
+ checks = await uow.github_resource(repository, CHECKS, scope)
845
+ assert checks is not None
846
+ await apply_resource(
847
+ uow,
848
+ repository,
849
+ COMMIT_STATUSES,
850
+ scope,
851
+ replace(
852
+ statuses,
853
+ attributes={**statuses.attributes, "checks_generation": checks.generation},
854
+ ),
855
+ as_of,
856
+ )
857
+ if resource == CHECKS:
858
+ await record_same_head(uow, repository, result)
859
+
860
+ await self.ledger.run("system", write)
861
+ return result
862
+
863
+ async def issue_tree(self) -> tuple[dict[str, Any], ...]:
864
+ snapshot = await self.ledger.github_resource(self.api.repository, ISSUE_TREE)
865
+ if snapshot is None or not snapshot.complete:
866
+ raise ValueError("GitHub issue tree is incomplete")
867
+ return tuple(row.details for row in snapshot.records)