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,724 @@
1
+ """Read-only merge readiness rules over a committed GitHub projection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timedelta
9
+ from typing import TYPE_CHECKING, Any, Literal, cast
10
+
11
+ from plotroom.core.events import format_time
12
+ from plotroom.core.github import ACTIVE_PULL_DETAIL_BUDGET, PULL_REQUESTS, FetchCursor, PullRequest
13
+ from plotroom.core.github_projection import (
14
+ CHECKS,
15
+ COMMIT_STATUS_BUCKETS,
16
+ COMMIT_STATUSES,
17
+ KODUS_REVIEW,
18
+ LABELS,
19
+ MAIN,
20
+ MAIN_CI,
21
+ MAIN_CI_WINDOW,
22
+ PULL_TEXT,
23
+ THREADS,
24
+ GitHubRecord,
25
+ GitHubResource,
26
+ checks_for_head,
27
+ unresolved_threads,
28
+ )
29
+ from plotroom.core.kodus_review import KodusReviewPolicy, trusted_current_check
30
+ from plotroom.core.merge_flakes import FAILURES as MAIN_FAILURES
31
+ from plotroom.core.merge_flakes import EventLookup, main_check_is_flake
32
+ from plotroom.core.merge_lane import MergeLaneIndex, merge_lane_evidence
33
+ from plotroom.core.merge_overlap import (
34
+ ALLOW_OVERLAP,
35
+ PULL_COMPARISON,
36
+ overlap_label_is_bound,
37
+ pinned_overlap,
38
+ )
39
+
40
+ if TYPE_CHECKING:
41
+ from plotroom.core.lanes import Lane
42
+ from plotroom.core.unit_of_work import UnitOfWork
43
+ from plotroom.ports.store import Transaction
44
+
45
+ type ExitClass = Literal[0, 1, 2, 3, 4, 5]
46
+ type VerdictKind = Literal["MERGE", "REFUSE"]
47
+ type MainVerdictKind = Literal["green", "red", "none", "unreadable"]
48
+
49
+ _PENDING_STATUSES = frozenset(
50
+ {"expected", "in_progress", "pending", "queued", "requested", "waiting"}
51
+ )
52
+ _PASS_CONCLUSIONS = frozenset({"success", "neutral", "cancelled", "skipped"})
53
+ _FAIL_CONCLUSIONS = frozenset({"action_required", "error", "failure", "timed_out"})
54
+ _MAIN_JOB_CONCLUSIONS = _PASS_CONCLUSIONS | _FAIL_CONCLUSIONS | {"stale", "startup_failure"}
55
+ # Match the clerk's word boundary and literal space with ASCII keyword case folding.
56
+ _CLOSING_KEYWORD = re.compile(
57
+ r"(?ai:\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)) #[0-9]+"
58
+ )
59
+ KEYWORDS_OK = "keywords-ok"
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class GatePolicy:
64
+ min_checks: int | None = None
65
+ ignore_checks: tuple[str, ...] = ()
66
+ max_age: timedelta = timedelta(minutes=2)
67
+ pull_max_age: timedelta | None = None
68
+ ci_workflow: str | None = None
69
+ fix_label: str | None = None
70
+ authorized_label_logins: tuple[str, ...] = ()
71
+ skip_label: str | None = None
72
+ merge_method: Literal["merge", "squash", "rebase"] = "merge"
73
+ controller_merges: bool = False
74
+ kodus_review: KodusReviewPolicy | None = None
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class GateSnapshot:
79
+ pull: PullRequest | None
80
+ checks: GitHubResource | None
81
+ pull_cursor: FetchCursor | None = None
82
+ github_unavailable: bool = False
83
+ threads: GitHubResource | None = None
84
+ main_ci: GitHubResource | None = None
85
+ labels: GitHubResource | None = None
86
+ main_flakes: frozenset[tuple[str, int]] = frozenset()
87
+ freeze_reason: str | None = None
88
+ main: GitHubResource | None = None
89
+ comparison: GitHubResource | None = None
90
+ lane: Lane | None = None
91
+ earlier_pull: int | None = None
92
+ ambiguous_lane: bool = False
93
+ pull_text: GitHubResource | None = None
94
+ kodus_review: GitHubResource | None = None
95
+ commit_statuses: GitHubResource | None = None
96
+ detail_capacity_exceeded: bool = False
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class GateReason:
101
+ code: str
102
+ detail: str
103
+ exit_class: ExitClass = 2
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class GateVerdict:
108
+ verdict: VerdictKind
109
+ reasons: tuple[GateReason, ...]
110
+ exit_class: ExitClass
111
+ head_sha: str | None
112
+ as_of: str | None
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class MainVerdict:
117
+ kind: MainVerdictKind
118
+ detail: str
119
+ branch: str | None = None
120
+ head_sha: str | None = None
121
+
122
+
123
+ def observation_time(value: str) -> datetime | None:
124
+ try:
125
+ timestamp = datetime.fromisoformat(value)
126
+ except ValueError:
127
+ return None
128
+ return timestamp if timestamp.utcoffset() is not None else None
129
+
130
+
131
+ def fresh(value: str, now: datetime, max_age: timedelta) -> bool:
132
+ observed = observation_time(value)
133
+ return observed is not None and timedelta() <= now - observed <= max_age
134
+
135
+
136
+ def _projection_reason(
137
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime
138
+ ) -> GateReason | None:
139
+ if type(policy.min_checks) is not int or policy.min_checks < 1:
140
+ return GateReason("minimum_checks_unconfigured", "set the minimum to at least one check", 1)
141
+ pull, cursor = snapshot.pull, snapshot.pull_cursor
142
+ if snapshot.github_unavailable or pull is None or not pull.head_sha:
143
+ return GateReason("pr_unavailable", "could not read the pull request head", 1)
144
+ if not pull.complete:
145
+ return GateReason("pr_incomplete", "pull request evidence is incomplete")
146
+ if pull.state != "open":
147
+ return GateReason("pr_not_open", "pull request is not open")
148
+ # The incremental cursor confirms that polling is current. Individual rows may be
149
+ # older until a full reconciliation includes them again.
150
+ pull_max_age = policy.pull_max_age if cursor is not None else None
151
+ if not fresh(pull.as_of, now, pull_max_age or policy.max_age) or (
152
+ cursor is not None and not fresh(cursor.as_of, now, policy.max_age)
153
+ ):
154
+ return GateReason("pr_stale", "pull request evidence is stale")
155
+ return None
156
+
157
+
158
+ def _check_buckets(checks: GitHubResource, head_sha: str) -> list[tuple[str, str]] | None:
159
+ latest = checks_for_head(checks, head_sha)
160
+ if latest is None:
161
+ return None
162
+ buckets: list[tuple[str, str]] = []
163
+ for check in latest:
164
+ status, conclusion = check.fields.get("status"), check.fields.get("conclusion")
165
+ if not isinstance(status, str) or (
166
+ conclusion is not None and not isinstance(conclusion, str)
167
+ ):
168
+ return None
169
+ if status in _PENDING_STATUSES and conclusion is None:
170
+ bucket = "pending"
171
+ elif status != "completed":
172
+ return None
173
+ elif conclusion == "stale":
174
+ bucket = "pending"
175
+ elif conclusion in _PASS_CONCLUSIONS:
176
+ bucket = "pass"
177
+ elif conclusion in _FAIL_CONCLUSIONS:
178
+ bucket = "fail"
179
+ else:
180
+ return None
181
+ buckets.append((check.fields["name"], bucket))
182
+ return buckets
183
+
184
+
185
+ def _commit_status_buckets(statuses: GitHubResource) -> list[tuple[str, str]] | None:
186
+ # The provider lists statuses newest first. Keep other creators' reports
187
+ # even when they reuse a context name.
188
+ latest: dict[tuple[str, int], tuple[str, str]] = {}
189
+ seen: set[int] = set()
190
+ for row in statuses.records:
191
+ context, state = row.fields.get("context"), row.fields.get("state")
192
+ identifier, creator = row.fields.get("id"), row.fields.get("creator_id")
193
+ if (
194
+ row.kind != "commit_status"
195
+ or type(identifier) is not int
196
+ or not 0 < identifier <= 2**63 - 1
197
+ or identifier in seen
198
+ or row.key != str(identifier)
199
+ or type(creator) is not int
200
+ or not 0 < creator <= 2**63 - 1
201
+ or not isinstance(context, str)
202
+ or not context.strip()
203
+ or not isinstance(state, str)
204
+ or state not in COMMIT_STATUS_BUCKETS
205
+ ):
206
+ return None
207
+ seen.add(identifier)
208
+ latest.setdefault((context.casefold(), creator), (context, COMMIT_STATUS_BUCKETS[state]))
209
+ return list(latest.values())
210
+
211
+
212
+ def _rule_checks(snapshot: GateSnapshot, policy: GatePolicy, now: datetime) -> GateReason | None:
213
+ pull, checks = snapshot.pull, snapshot.checks
214
+ if pull is None or checks is None or not checks.complete:
215
+ return GateReason("checks_unreadable", "could not read the checks")
216
+ if not fresh(checks.as_of, now, policy.max_age):
217
+ return GateReason("checks_stale", "check evidence is stale")
218
+ buckets = _check_buckets(checks, pull.head_sha)
219
+ if buckets is None:
220
+ return GateReason("checks_unreadable", "could not read the checks")
221
+ statuses = snapshot.commit_statuses
222
+ unreadable = GateReason("commit_statuses_unreadable", "could not read the commit statuses")
223
+ if (
224
+ statuses is None
225
+ or not statuses.complete
226
+ or statuses.attributes.get("repository") != pull.repository
227
+ or statuses.attributes.get("head_sha") != pull.head_sha
228
+ or type(statuses.attributes.get("checks_generation")) is not int
229
+ or statuses.attributes["checks_generation"] != checks.generation
230
+ ):
231
+ return unreadable
232
+ if not fresh(statuses.as_of, now, policy.max_age):
233
+ return GateReason("commit_statuses_stale", "commit status evidence is stale")
234
+ status_buckets = _commit_status_buckets(statuses)
235
+ if status_buckets is None:
236
+ return unreadable
237
+ check_names = {name for name, _ in buckets}
238
+ status_names = {context.casefold() for context, _ in status_buckets}
239
+ buckets.extend(status_buckets)
240
+ pending = sum(bucket == "pending" for _, bucket in buckets)
241
+ if pending:
242
+ return GateReason("checks_pending", f"{pending} checks pending")
243
+ minimum = policy.min_checks
244
+ total = len(check_names) + len(status_names - {name.casefold() for name in check_names})
245
+ if minimum is not None and total < minimum:
246
+ return GateReason(
247
+ "checks_below_minimum",
248
+ f"only {total} checks have reported (at least {minimum} expected)",
249
+ )
250
+ failures = sorted(
251
+ {name for name, bucket in buckets if bucket == "fail" and name not in policy.ignore_checks}
252
+ )
253
+ if failures:
254
+ return GateReason("checks_failing", f"failing: {'; '.join(failures)}")
255
+ return None
256
+
257
+
258
+ def _rule_review_threads(
259
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime
260
+ ) -> GateReason | None:
261
+ pull, threads = snapshot.pull, snapshot.threads
262
+ incomplete = GateReason("review_threads_incomplete", "could not read the review threads")
263
+ if (
264
+ pull is None
265
+ or threads is None
266
+ or not threads.complete
267
+ or threads.attributes.get("head_sha") != pull.head_sha
268
+ or type(threads.attributes.get("pull_version")) is not int
269
+ or threads.attributes["pull_version"] != pull.version
270
+ or not fresh(threads.as_of, now, policy.max_age)
271
+ ):
272
+ return incomplete
273
+ if len({thread.key for thread in threads.records}) != len(threads.records) or any(
274
+ thread.kind != "review_thread"
275
+ or not thread.key
276
+ or thread.fields.get("id") != thread.key
277
+ or thread.fields.get("number") != pull.number
278
+ or type(thread.fields.get("resolved")) is not bool
279
+ for thread in threads.records
280
+ ):
281
+ return incomplete
282
+ unresolved = unresolved_threads(threads)
283
+ if unresolved:
284
+ return GateReason("review_threads_unresolved", f"{len(unresolved)} unresolved threads")
285
+ return None
286
+
287
+
288
+ def failed_main_jobs(run: GitHubRecord) -> tuple[int | None, ...] | None:
289
+ """Return failed Check Runs IDs, retaining an unlinked job as an unmatched failure."""
290
+ if run.details.get("jobs_complete") is not True:
291
+ return None
292
+ jobs = run.fields.get("jobs")
293
+ if not isinstance(jobs, list):
294
+ return None
295
+ failed: list[int | None] = []
296
+ for entry in cast("list[Any]", jobs):
297
+ if not isinstance(entry, dict):
298
+ return None
299
+ job = cast("dict[str, Any]", entry)
300
+ conclusion = job.get("conclusion")
301
+ if (
302
+ job.get("status") != "completed"
303
+ or not isinstance(conclusion, str)
304
+ or conclusion not in _MAIN_JOB_CONCLUSIONS
305
+ ):
306
+ return None
307
+ if conclusion in MAIN_FAILURES:
308
+ identifier = job.get("check_run_id")
309
+ failed.append(identifier if type(identifier) is int and identifier > 0 else None)
310
+ linked = [identifier for identifier in failed if identifier is not None]
311
+ if len(set(linked)) != len(linked):
312
+ return None
313
+ return tuple(failed)
314
+
315
+
316
+ async def read_main_flakes(
317
+ view: EventLookup, repository: str, main: GitHubResource | None
318
+ ) -> frozenset[tuple[str, int]]:
319
+ if main is None or not main.complete:
320
+ return frozenset()
321
+ failures: set[tuple[str, int]] = {
322
+ (head, check_id)
323
+ for run in main.records[:MAIN_CI_WINDOW]
324
+ if isinstance(head := run.fields.get("head_sha"), str) and head
325
+ for check_id in failed_main_jobs(run) or ()
326
+ if check_id is not None
327
+ }
328
+ return frozenset(
329
+ [
330
+ (head, check_id)
331
+ for head, check_id in sorted(failures)
332
+ if await main_check_is_flake(view, repository, head, check_id)
333
+ ]
334
+ )
335
+
336
+
337
+ async def load_gate_snapshot(
338
+ reader: Transaction | UnitOfWork,
339
+ repository: str | None,
340
+ number: int,
341
+ *,
342
+ lane_index: MergeLaneIndex | None = None,
343
+ ) -> GateSnapshot:
344
+ """Read all gate inputs from one consistent transaction."""
345
+ freeze_reason = await reader.deploy_freeze()
346
+ if repository is None:
347
+ return GateSnapshot(None, None, freeze_reason=freeze_reason)
348
+ pull = await reader.pull_request(repository, number)
349
+ scope = str(number)
350
+ cursor = await reader.fetch_cursor(repository, PULL_REQUESTS)
351
+ checks = (
352
+ await reader.github_resource(repository, CHECKS, pull.head_sha)
353
+ if pull is not None
354
+ else None
355
+ )
356
+ main_ci = await reader.github_resource(repository, MAIN_CI, "")
357
+ lane, earlier_pull, ambiguous_lane = (
358
+ lane_index.evidence(pull)
359
+ if lane_index is not None
360
+ else await merge_lane_evidence(reader, pull)
361
+ )
362
+ return GateSnapshot(
363
+ pull,
364
+ checks,
365
+ cursor,
366
+ threads=await reader.github_resource(repository, THREADS, scope),
367
+ main_ci=main_ci,
368
+ labels=await reader.github_resource(repository, LABELS, scope),
369
+ main_flakes=await read_main_flakes(reader, repository, main_ci),
370
+ freeze_reason=freeze_reason,
371
+ main=await reader.github_resource(repository, MAIN, ""),
372
+ comparison=await reader.github_resource(repository, PULL_COMPARISON, scope),
373
+ lane=lane,
374
+ earlier_pull=earlier_pull,
375
+ ambiguous_lane=ambiguous_lane,
376
+ pull_text=await reader.github_resource(repository, PULL_TEXT, scope),
377
+ kodus_review=await reader.github_resource(repository, KODUS_REVIEW, scope),
378
+ commit_statuses=await reader.github_resource(repository, COMMIT_STATUSES, pull.head_sha)
379
+ if pull is not None
380
+ else None,
381
+ detail_capacity_exceeded=await reader.detail_capacity_exceeded(repository),
382
+ )
383
+
384
+
385
+ def determine_main_verdict(
386
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime
387
+ ) -> MainVerdict:
388
+ """Read the newest usable run in the configured workflow's completed history."""
389
+ main = snapshot.main_ci
390
+ if policy.ci_workflow is None:
391
+ return MainVerdict("none", "the CI workflow is not configured")
392
+ unreadable = MainVerdict("unreadable", "could not list the CI runs")
393
+ if (
394
+ main is None
395
+ or not main.complete
396
+ or main.attributes.get("workflow") != policy.ci_workflow
397
+ or not fresh(main.as_of, now, policy.max_age)
398
+ ):
399
+ return unreadable
400
+ branch, tip = main.attributes.get("branch"), main.attributes.get("head_sha")
401
+ if not isinstance(branch, str) or not branch or not isinstance(tip, str) or not tip:
402
+ return unreadable
403
+ for run in main.records[:MAIN_CI_WINDOW]:
404
+ head, conclusion = run.fields.get("head_sha"), run.fields.get("conclusion")
405
+ identifier = run.fields.get("id")
406
+ if (
407
+ run.kind != "workflow_run"
408
+ or run.fields.get("status") != "completed"
409
+ or not isinstance(head, str)
410
+ or not head
411
+ or not isinstance(conclusion, str)
412
+ or not conclusion
413
+ or type(identifier) is not int
414
+ or identifier < 1
415
+ ):
416
+ return unreadable
417
+ detail = f"{conclusion} {head[:8]}"
418
+ if conclusion in {"cancelled", "skipped"}:
419
+ continue
420
+ if conclusion == "success":
421
+ return MainVerdict("green", detail, branch, tip)
422
+ if conclusion == "startup_failure":
423
+ return MainVerdict("red", detail, branch, tip)
424
+ failures = failed_main_jobs(run)
425
+ if failures is None:
426
+ return MainVerdict(
427
+ "unreadable",
428
+ f"the jobs of run {identifier} could not be read ({head[:8]})",
429
+ branch,
430
+ tip,
431
+ )
432
+ if any(check is None or (head, check) not in snapshot.main_flakes for check in failures):
433
+ return MainVerdict("red", detail, branch, tip)
434
+ return MainVerdict("none", "no completed CI run with a verdict", branch, tip)
435
+
436
+
437
+ def _bound_pull_evidence(
438
+ resource: GitHubResource, pull: PullRequest, policy: GatePolicy, now: datetime
439
+ ) -> bool:
440
+ attributes = resource.attributes
441
+ return (
442
+ resource.complete
443
+ and fresh(resource.as_of, now, policy.max_age)
444
+ and attributes.get("head_sha") == pull.head_sha
445
+ and type(attributes.get("pull_version")) is int
446
+ and attributes["pull_version"] == pull.version
447
+ and attributes.get("pull_updated_at") == pull.updated_at
448
+ )
449
+
450
+
451
+ def current_label_evidence(
452
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime
453
+ ) -> GitHubResource | None:
454
+ pull, labels = snapshot.pull, snapshot.labels
455
+ if (
456
+ pull is None
457
+ or labels is None
458
+ or not _bound_pull_evidence(labels, pull, policy, now)
459
+ or not isinstance(labels.attributes.get("labels"), dict)
460
+ or not isinstance(labels.attributes.get("label_provenance"), dict)
461
+ ):
462
+ return None
463
+ return labels
464
+
465
+
466
+ def authorized_label(
467
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime, label: str | None
468
+ ) -> int | None:
469
+ labels = current_label_evidence(snapshot, policy, now)
470
+ if label is None or labels is None:
471
+ return None
472
+ active = cast("dict[str, Any]", labels.attributes["labels"])
473
+ provenance = cast("dict[str, Any]", labels.attributes["label_provenance"])
474
+ raw_event = provenance.get(label)
475
+ if not isinstance(raw_event, dict):
476
+ return None
477
+ event = cast("dict[str, Any]", raw_event)
478
+ if event.get("actor_type") != "User":
479
+ return None
480
+ login, event_id = event.get("login"), event.get("event_id")
481
+ if (
482
+ not isinstance(login, str)
483
+ or login != active.get(label)
484
+ or login.lower() not in policy.authorized_label_logins
485
+ or type(event_id) is not int
486
+ or event_id < 1
487
+ ):
488
+ return None
489
+ return event_id
490
+
491
+
492
+ def _rule_main(snapshot: GateSnapshot, policy: GatePolicy, now: datetime) -> GateReason | None:
493
+ verdict = determine_main_verdict(snapshot, policy, now)
494
+ if verdict.kind == "green":
495
+ return None
496
+ branch = verdict.branch or "main"
497
+ if verdict.kind == "red":
498
+ if authorized_label(snapshot, policy, now, policy.fix_label) is not None:
499
+ return None
500
+ return GateReason("main_red", f"{branch}'s latest CI verdict is red: {verdict.detail}", 5)
501
+ return GateReason("main_no_verdict", f"{branch} has no usable CI verdict: {verdict.detail}")
502
+
503
+
504
+ STALE_CI = "stale_ci"
505
+
506
+
507
+ def _rule_overlap(snapshot: GateSnapshot, policy: GatePolicy, now: datetime) -> GateReason | None:
508
+ pull, main, comparison = snapshot.pull, snapshot.main, snapshot.comparison
509
+ verdict = determine_main_verdict(snapshot, policy, now)
510
+ branch, tip = verdict.branch, verdict.head_sha
511
+ unreadable = GateReason(
512
+ "overlap_unreadable", "could not compare the PR with the default branch"
513
+ )
514
+ if (
515
+ pull is None
516
+ or branch is None
517
+ or tip is None
518
+ or main is None
519
+ or not main.complete
520
+ or not fresh(main.as_of, now, policy.max_age)
521
+ or main.attributes.get("branch") != branch
522
+ or main.attributes.get("head_sha") != tip
523
+ or comparison is None
524
+ or not fresh(comparison.as_of, now, policy.max_age)
525
+ ):
526
+ return unreadable
527
+ overlap = pinned_overlap(comparison, pull, branch, tip)
528
+ if overlap is None:
529
+ return unreadable
530
+ merge_base, paths = overlap
531
+ if not paths:
532
+ return None
533
+ event = authorized_label(snapshot, policy, now, ALLOW_OVERLAP)
534
+ if event is not None and overlap_label_is_bound(snapshot.labels, pull, event):
535
+ return None
536
+ detail = (
537
+ f"{branch} changed these PR files since the PR's base {merge_base[:8]} "
538
+ "(stale CI: update the branch and run CI again):"
539
+ )
540
+ return GateReason(STALE_CI, "\n".join((detail, *(f" {path}" for path in paths))), 3)
541
+
542
+
543
+ def _rule_closing_keywords(
544
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime
545
+ ) -> GateReason | None:
546
+ pull, text = snapshot.pull, snapshot.pull_text
547
+ unreadable = GateReason("pull_text_unreadable", "could not read the PR body and commits")
548
+ if pull is None or text is None or not _bound_pull_evidence(text, pull, policy, now):
549
+ return unreadable
550
+ body = text.attributes.get("body")
551
+ expected = text.attributes.get("commit_count")
552
+ messages = text.attributes.get("commit_messages")
553
+ if (
554
+ not isinstance(body, str)
555
+ or not isinstance(messages, list)
556
+ or type(expected) is not int
557
+ or expected < 1
558
+ or len(cast("list[object]", messages)) != expected
559
+ or any(not isinstance(message, str) for message in cast("list[object]", messages))
560
+ ):
561
+ return unreadable
562
+ has_closing_keyword = _CLOSING_KEYWORD.search(body) is not None or any(
563
+ _CLOSING_KEYWORD.search(message) for message in cast("list[str]", messages)
564
+ )
565
+ if has_closing_keyword and authorized_label(snapshot, policy, now, KEYWORDS_OK) is None:
566
+ return GateReason("closing_keywords", "closing keywords would close issues", 4)
567
+ return None
568
+
569
+
570
+ type GateRule = Callable[[GateSnapshot, GatePolicy, datetime], GateReason | None]
571
+ GATE_RULES: tuple[GateRule, ...] = (
572
+ _rule_checks,
573
+ _rule_review_threads,
574
+ _rule_main,
575
+ _rule_overlap,
576
+ _rule_closing_keywords,
577
+ )
578
+
579
+
580
+ def _rule_kodus_review(
581
+ snapshot: GateSnapshot, policy: GatePolicy, now: datetime
582
+ ) -> GateReason | None:
583
+ review_policy = policy.kodus_review
584
+ if review_policy is None:
585
+ return None
586
+ missing = GateReason("kodus_review_unverified", "could not verify completed Kodus review")
587
+ pull, review, checks = snapshot.pull, snapshot.kodus_review, snapshot.checks
588
+ if (
589
+ pull is None
590
+ or review is None
591
+ or checks is None
592
+ or not _bound_pull_evidence(review, pull, policy, now)
593
+ ):
594
+ return missing
595
+ proof = review.attributes
596
+ check_id = proof.get("check_id")
597
+ fingerprint = proof.get("check_fingerprint")
598
+ if (
599
+ proof.get("repository") != pull.repository
600
+ or type(proof.get("pull_number")) is not int
601
+ or proof["pull_number"] != pull.number
602
+ or type(proof.get("pull_id")) is not int
603
+ or proof["pull_id"] < 1
604
+ or type(proof.get("app_id")) is not int
605
+ or proof["app_id"] != review_policy.app_id
606
+ or proof.get("app_slug") != review_policy.app_slug
607
+ or proof.get("check_name") != review_policy.check_name
608
+ or type(check_id) is not int
609
+ or check_id < 1
610
+ or not isinstance(fingerprint, str)
611
+ or not fingerprint
612
+ ):
613
+ return missing
614
+ if proof.get("mode") == "reviewed" and trusted_current_check(
615
+ review_policy, checks, pull.head_sha, check_id, fingerprint, "success"
616
+ ):
617
+ return None
618
+ opening = review_policy.opening_head(pull.repository, pull.number)
619
+ if (
620
+ proof.get("mode") == "cadence-skip"
621
+ and snapshot.threads is not None
622
+ and proof.get("answered_threads")
623
+ == sorted(thread.key for thread in snapshot.threads.records)
624
+ and opening is not None
625
+ and proof["pull_id"] == opening.pull_id
626
+ and proof.get("created_at") == opening.created_at
627
+ and proof.get("opening_sha") == opening.head_sha
628
+ and opening.head_sha != pull.head_sha
629
+ and type(proof.get("opening_check_id")) is int
630
+ and proof["opening_check_id"] > 0
631
+ and proof["opening_check_id"] != check_id
632
+ and trusted_current_check(
633
+ review_policy, checks, pull.head_sha, check_id, fingerprint, "skipped"
634
+ )
635
+ ):
636
+ return None
637
+ return missing
638
+
639
+
640
+ def active_skip_label(snapshot: GateSnapshot, policy: GatePolicy, now: datetime) -> bool:
641
+ labels = current_label_evidence(snapshot, policy, now)
642
+ return (
643
+ policy.skip_label is not None
644
+ and labels is not None
645
+ and (policy.skip_label in labels.attributes["labels"])
646
+ )
647
+
648
+
649
+ def evaluate_gate(
650
+ snapshot: GateSnapshot,
651
+ policy: GatePolicy,
652
+ now: datetime,
653
+ *,
654
+ expected_head_sha: str | None = None,
655
+ expected_main_sha: str | None = None,
656
+ ) -> GateVerdict:
657
+ """Return the first refusal in clerk order and the oldest included observation."""
658
+ pull, cursor, checks = snapshot.pull, snapshot.pull_cursor, snapshot.checks
659
+ head = (pull.head_sha or None) if pull is not None else None
660
+ timestamps = (
661
+ timestamp
662
+ for observation in (
663
+ pull,
664
+ cursor,
665
+ checks,
666
+ snapshot.commit_statuses,
667
+ snapshot.threads,
668
+ snapshot.main_ci,
669
+ snapshot.labels,
670
+ snapshot.main,
671
+ snapshot.comparison,
672
+ snapshot.pull_text,
673
+ snapshot.kodus_review if policy.kodus_review is not None else None,
674
+ )
675
+ if observation is not None
676
+ if (timestamp := observation_time(observation.as_of)) is not None
677
+ )
678
+ watermark = min(timestamps, default=None)
679
+ as_of = None if watermark is None else format_time(watermark)
680
+ if snapshot.freeze_reason is not None:
681
+ reason = GateReason("deploy_window", snapshot.freeze_reason)
682
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
683
+ if (reason := _projection_reason(snapshot, policy, now)) is not None:
684
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
685
+ if expected_head_sha is not None and head != expected_head_sha:
686
+ reason = GateReason("head_moved", "the pull request head moved")
687
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
688
+ if pull is not None and pull.draft:
689
+ reason = GateReason("draft_pr", "the pull request is a draft")
690
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
691
+ if active_skip_label(snapshot, policy, now):
692
+ reason = GateReason("skip_label", "the pull request has the skip label")
693
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
694
+ if expected_main_sha is not None and (
695
+ determine_main_verdict(snapshot, policy, now).head_sha != expected_main_sha
696
+ ):
697
+ reason = GateReason("main_moved", "the default branch moved", 1)
698
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
699
+ if snapshot.detail_capacity_exceeded:
700
+ reason = GateReason(
701
+ "detail_capacity_exceeded",
702
+ f"more than {ACTIVE_PULL_DETAIL_BUDGET} open PRs exceed merge detail polling capacity",
703
+ )
704
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
705
+ for rule in GATE_RULES:
706
+ if (reason := rule(snapshot, policy, now)) is not None:
707
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
708
+ if policy.skip_label is not None and current_label_evidence(snapshot, policy, now) is None:
709
+ reason = GateReason("skip_label_unreadable", "could not read the skip label")
710
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
711
+ if pull is not None and pull.draft is None:
712
+ reason = GateReason("draft_unreadable", "could not read the pull request draft state")
713
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
714
+ if snapshot.ambiguous_lane:
715
+ reason = GateReason("ambiguous_merge_lane", "multiple lanes match the pull request branch")
716
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
717
+ if snapshot.earlier_pull is not None:
718
+ reason = GateReason(
719
+ "duplicate_lane_pr", f"PR #{snapshot.earlier_pull} is already open for this lane"
720
+ )
721
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
722
+ if (reason := _rule_kodus_review(snapshot, policy, now)) is not None:
723
+ return GateVerdict("REFUSE", (reason,), reason.exit_class, head, as_of)
724
+ return GateVerdict("MERGE", (), 0, head, as_of)