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,550 @@
1
+ """Validated predicates and durable trigger evaluation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from collections.abc import Awaitable, Callable, Iterator, Mapping
7
+ from dataclasses import dataclass, field, replace
8
+ from datetime import datetime
9
+ from functools import partial
10
+ from typing import TYPE_CHECKING, Any, Literal, cast
11
+
12
+ from plotroom.core.budgets import reaches_budget_ratio
13
+ from plotroom.core.events import FieldSpec, LedgerError, NewEvent, validate_fields
14
+ from plotroom.core.github_projection import (
15
+ CHECKS,
16
+ ISSUES,
17
+ MAIN,
18
+ THREADS,
19
+ checks_for_head,
20
+ main_verdict,
21
+ unresolved_threads,
22
+ )
23
+ from plotroom.core.reports import DEPLOY_STATUS, validate_deploy_environment, validate_report_sha
24
+ from plotroom.core.roles import role_family
25
+ from plotroom.core.run_reports import RUN_ID, validate_identity
26
+ from plotroom.core.trigger_actions import NOTIFY, validate_action
27
+
28
+ if TYPE_CHECKING:
29
+ from plotroom.core.github import PullRequest
30
+ from plotroom.core.trigger_actions import DeliveryRoute
31
+ from plotroom.core.unit_of_work import UnitOfWork
32
+
33
+ TRIGGER_FIRED = "core.trigger_fired"
34
+ TRIGGER_FIRED_FIELDS = (FieldSpec("trigger_id", "str"),)
35
+ _MAX_DEPTH = 16
36
+ # A valid predicate uses two containers per group, plus the command and leaf objects.
37
+ _MAX_SNAPSHOT_CONTAINERS = 64
38
+
39
+
40
+ def trigger_snapshot_is_too_deep(args: dict[str, Any]) -> bool:
41
+ """Detect trigger arguments that are too deeply nested for a recursive snapshot."""
42
+ parents: list[Iterator[Any]] = [iter(args.values())]
43
+ deepest_visit: dict[int, int] = {}
44
+ while parents:
45
+ try:
46
+ value = next(parents[-1])
47
+ except StopIteration:
48
+ parents.pop()
49
+ continue
50
+ if isinstance(value, dict):
51
+ children = iter(cast("dict[str, Any]", value).values())
52
+ elif isinstance(value, (list, tuple)):
53
+ children = iter(cast("list[Any] | tuple[Any, ...]", value))
54
+ else:
55
+ continue
56
+ depth = len(parents)
57
+ if depth >= _MAX_SNAPSHOT_CONTAINERS:
58
+ return True
59
+ # A deeper visit must still be checked, even when a shallower path reused this container.
60
+ identity = id(cast(object, value))
61
+ if deepest_visit.get(identity, -1) >= depth:
62
+ continue
63
+ deepest_visit[identity] = depth
64
+ parents.append(children)
65
+ return False
66
+
67
+
68
+ type TriggerMode = Literal["once", "every"]
69
+
70
+ type TriggerState = Literal["open", "fired", "canceled"]
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class Trigger:
75
+ id: str
76
+ lane: str | None
77
+ repository: str | None
78
+ predicate: dict[str, Any]
79
+ action_kind: str
80
+ action_payload: dict[str, Any]
81
+ state: TriggerState
82
+ bindings: dict[str, int]
83
+ created_seq: int
84
+ fired_seq: int | None = None
85
+ action_key: str | None = None
86
+ mode: TriggerMode = "once"
87
+ was_true: bool = False
88
+ event_floors: dict[str, int] = field(default_factory=dict[str, int])
89
+ import_note: str | None = None
90
+ notify_on_fire: bool = False
91
+
92
+ def render(self) -> dict[str, Any]:
93
+ result = {
94
+ "id": self.id,
95
+ "lane": self.lane,
96
+ "repository": self.repository,
97
+ "predicate": self.predicate,
98
+ "action": {self.action_kind: self.action_payload},
99
+ "state": self.state,
100
+ "mode": self.mode,
101
+ "bindings": self.bindings,
102
+ "created_seq": self.created_seq,
103
+ "fired_seq": self.fired_seq,
104
+ "action_key": self.action_key,
105
+ }
106
+ if self.import_note is not None:
107
+ result["import_note"] = self.import_note
108
+ return result
109
+
110
+
111
+ @dataclass
112
+ class Evaluation:
113
+ uow: UnitOfWork
114
+ trigger: Trigger
115
+ bindings: dict[str, int]
116
+
117
+ matched: dict[str, int] = field(default_factory=dict[str, int])
118
+
119
+ async def pending_event(self, path: str, kind: str, fields: Mapping[str, str | bool]) -> bool:
120
+ cursor = max(
121
+ self.trigger.fired_seq or self.trigger.created_seq,
122
+ self.trigger.event_floors.get(path, 0),
123
+ )
124
+ event = await self.uow.latest_event(kind, fields=fields, after=cursor)
125
+ if event is None:
126
+ return False
127
+ self.matched[path] = max(self.matched.get(path, 0), event.seq)
128
+ return True
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class PredicateMatch:
133
+ holds: bool
134
+ level_holds: bool
135
+ events: frozenset[str] = frozenset()
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class LeafSpec:
140
+ name: str
141
+ args: tuple[FieldSpec, ...]
142
+ mode: Literal["level", "event"]
143
+ validate: Callable[[dict[str, Any]], None]
144
+ evaluate: Callable[[Evaluation, str, dict[str, Any]], Awaitable[bool]]
145
+ requires_repository: bool = False
146
+
147
+
148
+ class LeafRegistry:
149
+ """Closed at input time: each leaf must have a registered schema and evaluator."""
150
+
151
+ def __init__(self) -> None:
152
+ self._leaves: dict[str, LeafSpec] = {}
153
+
154
+ def register(self, spec: LeafSpec) -> None:
155
+ if spec.name in self._leaves or spec.name in {"all_of", "any_of"}:
156
+ raise ValueError(f"predicate name {spec.name!r} is already registered")
157
+ self._leaves[spec.name] = spec
158
+
159
+ def leaf(self, name: str) -> LeafSpec:
160
+ spec = self._leaves.get(name)
161
+ if spec is None:
162
+ raise LedgerError("invalid", f"unknown predicate leaf {name!r}")
163
+ return spec
164
+
165
+ def validate(self, predicate: Any, *, repository: str | None, depth: int = 0) -> None:
166
+ if depth > _MAX_DEPTH:
167
+ raise LedgerError("invalid", f"predicate nesting exceeds {_MAX_DEPTH} levels")
168
+ if not isinstance(predicate, dict) or len(cast("dict[str, Any]", predicate)) != 1:
169
+ raise LedgerError("invalid", "predicate must be an object naming one leaf or group")
170
+ name, value = next(iter(cast("dict[str, Any]", predicate).items()))
171
+ if name in {"all_of", "any_of"}:
172
+ if not isinstance(value, list) or not value:
173
+ raise LedgerError("invalid", f"{name} requires a nonempty array of predicates")
174
+ for child in cast("list[Any]", value):
175
+ self.validate(child, repository=repository, depth=depth + 1)
176
+ return
177
+ leaf = self.leaf(name)
178
+ if not isinstance(value, dict):
179
+ raise LedgerError("invalid", f"{name} arguments must be an object")
180
+ validate_fields(leaf.args, cast("dict[str, Any]", value), name)
181
+ leaf.validate(cast("dict[str, Any]", value))
182
+ if leaf.requires_repository and repository is None:
183
+ raise LedgerError("invalid", f"{name} requires a configured GitHub repository")
184
+
185
+ async def _holds(
186
+ self, evaluation: Evaluation, predicate: dict[str, Any], path: str = "$"
187
+ ) -> PredicateMatch:
188
+ """Evaluate each branch and track the event leaves that satisfied it."""
189
+ name, value = next(iter(predicate.items()))
190
+ if name not in {"all_of", "any_of"}:
191
+ leaf = self.leaf(name)
192
+ holds = await leaf.evaluate(evaluation, path, value)
193
+ if leaf.mode == "level":
194
+ return PredicateMatch(holds, holds)
195
+ return PredicateMatch(holds, False, frozenset({path}) if holds else frozenset())
196
+ # Evaluate every branch so glob bindings survive independently of the group's result.
197
+ matches = [
198
+ await self._holds(evaluation, child, f"{path}/{index}")
199
+ for index, child in enumerate(cast("list[dict[str, Any]]", value))
200
+ ]
201
+ combine = all if name == "all_of" else any
202
+ holds = combine(match.holds for match in matches)
203
+ events = (
204
+ frozenset(path for match in matches for path in match.events)
205
+ if holds
206
+ else frozenset[str]()
207
+ )
208
+ return PredicateMatch(holds, combine(match.level_holds for match in matches), events)
209
+
210
+ async def evaluate_open(self, uow: UnitOfWork) -> None:
211
+ for trigger in await uow.open_triggers():
212
+ bindings = trigger.bindings.copy()
213
+ evaluation = Evaluation(uow, trigger, bindings)
214
+ match = await self._holds(evaluation, trigger.predicate)
215
+ updated = replace(trigger, bindings=bindings, was_true=match.holds)
216
+ if match.holds and not trigger.was_true:
217
+ updated = await self._fire(uow, updated)
218
+ if trigger.mode == "every":
219
+ # Last fire is the shared cursor. It supersedes any per-leaf cursors.
220
+ updated = replace(updated, was_true=match.level_holds, event_floors={})
221
+ elif match.holds and match.events:
222
+ # During a true plateau, acknowledge only events in satisfied branches.
223
+ floors = {path: evaluation.matched[path] for path in match.events}
224
+ updated = replace(
225
+ updated,
226
+ was_true=match.level_holds,
227
+ event_floors={**trigger.event_floors, **floors},
228
+ )
229
+ if updated != trigger:
230
+ await uow.save_trigger(updated)
231
+
232
+ @staticmethod
233
+ async def _fire(uow: UnitOfWork, trigger: Trigger) -> Trigger:
234
+ uid = trigger.id
235
+ if trigger.mode == "every":
236
+ uid = f"{uid}:{trigger.fired_seq or trigger.created_seq}"
237
+ fired = await uow.append(
238
+ NewEvent("core", TRIGGER_FIRED, uid, {"trigger_id": trigger.id}, lane_id=trigger.lane)
239
+ )
240
+ key = await uow.enqueue_action(fired.event, trigger.action_kind, trigger.action_payload)
241
+ if trigger.notify_on_fire:
242
+ await uow.enqueue_action(fired.event, NOTIFY, {"text": trigger.action_payload["text"]})
243
+ return replace(
244
+ trigger,
245
+ state="fired" if trigger.mode == "once" else "open",
246
+ fired_seq=fired.event.seq,
247
+ action_key=key,
248
+ )
249
+
250
+
251
+ _PR_ARGS = (FieldSpec("number", "int", required=False), FieldSpec("branch_glob", "str", False))
252
+ _NUMBER = FieldSpec("number", "int")
253
+ _SHA = FieldSpec("sha", "str")
254
+ _ENV = FieldSpec("environment", "str")
255
+ _WORKER = FieldSpec("worker", "str")
256
+ _LANE = FieldSpec("lane", "str")
257
+ _BUDGET_RATIO_ARGS = (FieldSpec("run", "str"), FieldSpec("gte", "number"))
258
+
259
+
260
+ def _validate_number(args: dict[str, Any]) -> None:
261
+ if not 0 < args["number"] <= 2**63 - 1:
262
+ raise LedgerError("invalid", "number must be a positive SQLite integer")
263
+
264
+
265
+ def _validate_pr_selector(args: dict[str, Any]) -> None:
266
+ if len(args) != 1:
267
+ raise LedgerError("invalid", "a PR selector requires exactly one number or branch_glob")
268
+ if "number" in args:
269
+ _validate_number(args)
270
+ elif not args["branch_glob"].strip() or "\0" in args["branch_glob"]:
271
+ raise LedgerError("invalid", "branch_glob must be a nonempty branch pattern")
272
+
273
+
274
+ async def _select_pr(evaluation: Evaluation, path: str, args: dict[str, Any]) -> PullRequest | None:
275
+ repository = evaluation.trigger.repository
276
+ if repository is None:
277
+ return None
278
+ number: int | None = args.get("number", evaluation.bindings.get(path))
279
+ if number is None:
280
+ number = await evaluation.uow.first_matching_pull(repository, args["branch_glob"])
281
+ if number is None:
282
+ return None
283
+ evaluation.bindings[path] = number
284
+ pull = await evaluation.uow.pull_request(repository, number)
285
+ return pull if pull is not None and pull.complete else None
286
+
287
+
288
+ async def _pr_merged(evaluation: Evaluation, path: str, args: dict[str, Any]) -> bool:
289
+ pull = await _select_pr(evaluation, path, args)
290
+ return pull is not None and pull.state == "merged"
291
+
292
+
293
+ def _passed(fields: dict[str, Any]) -> bool:
294
+ return fields["status"] == "completed" and fields.get("conclusion") == "success"
295
+
296
+
297
+ async def _pr_green(evaluation: Evaluation, path: str, args: dict[str, Any]) -> bool:
298
+ pull = await _select_pr(evaluation, path, args)
299
+ if pull is None:
300
+ return False
301
+ checks = await evaluation.uow.github_resource(pull.repository, CHECKS, pull.head_sha)
302
+ if checks is None or not checks.complete:
303
+ return False
304
+ attempts = checks_for_head(checks, pull.head_sha)
305
+ if not attempts:
306
+ return False
307
+ return all(_passed(check.fields) for check in attempts)
308
+
309
+
310
+ async def _pr_threads_resolved(evaluation: Evaluation, path: str, args: dict[str, Any]) -> bool:
311
+ pull = await _select_pr(evaluation, path, args)
312
+ if pull is None:
313
+ return False
314
+ threads = await evaluation.uow.github_resource(pull.repository, THREADS, str(pull.number))
315
+ return (
316
+ threads is not None
317
+ and threads.complete
318
+ and threads.attributes.get("head_sha") == pull.head_sha
319
+ and type(threads.attributes.get("pull_version")) is int
320
+ and threads.attributes["pull_version"] == pull.version
321
+ and not unresolved_threads(threads)
322
+ )
323
+
324
+
325
+ async def _issue_closed(evaluation: Evaluation, _path: str, args: dict[str, Any]) -> bool:
326
+ if (repository := evaluation.trigger.repository) is None:
327
+ return False
328
+ issues = await evaluation.uow.github_resource(repository, ISSUES)
329
+ key = f"issue/{args['number']}"
330
+ return (
331
+ issues is not None
332
+ and issues.complete
333
+ and any(row.key == key and row.fields["state"] == "closed" for row in issues.records)
334
+ )
335
+
336
+
337
+ def _validate_main(args: dict[str, Any]) -> None:
338
+ if "sha" in args:
339
+ try:
340
+ validate_report_sha(args["sha"])
341
+ except ValueError as exc:
342
+ raise LedgerError("invalid", str(exc)) from None
343
+
344
+
345
+ async def _main_green_with_images(
346
+ evaluation: Evaluation, _path: str, args: dict[str, Any], *, image_jobs: tuple[str, ...]
347
+ ) -> bool:
348
+ repository = evaluation.trigger.repository
349
+ if repository is None or not image_jobs:
350
+ return False
351
+ main = await evaluation.uow.github_resource(repository, MAIN)
352
+ if main is None or not main.complete:
353
+ return False
354
+ tip = main.attributes.get("head_sha")
355
+ verdict = main_verdict(main, require_attribution=True)
356
+ if (
357
+ not tip
358
+ or args.get("sha", tip) != tip
359
+ or verdict is None
360
+ or verdict.fields["head_sha"] != tip
361
+ or not _passed(verdict.fields)
362
+ ):
363
+ return False
364
+ jobs = {job["name"]: job for job in sorted(verdict.fields["jobs"], key=lambda job: job["id"])}
365
+ return all(name in jobs and _passed(jobs[name]) for name in image_jobs)
366
+
367
+
368
+ def _validate_run(args: dict[str, Any]) -> None:
369
+ validate_identity(args["run_id"], "run_id")
370
+
371
+
372
+ async def _run_finished(evaluation: Evaluation, _path: str, args: dict[str, Any]) -> bool:
373
+ event = await evaluation.uow.latest_run_report(args["run_id"])
374
+ return event is not None and bool(event.fields["finished"])
375
+
376
+
377
+ def _validate_budget_ratio(args: dict[str, Any]) -> None:
378
+ validate_identity(args["run"], "run")
379
+ if args["gte"] < 0:
380
+ raise LedgerError("invalid", "gte must be nonnegative")
381
+
382
+
383
+ async def _budget_ratio(evaluation: Evaluation, _path: str, args: dict[str, Any]) -> bool:
384
+ budget = await evaluation.uow.find_budget(args["run"])
385
+ return budget is not None and reaches_budget_ratio(budget, args["gte"])
386
+
387
+
388
+ def _validate_worker(args: dict[str, Any]) -> None:
389
+ role = f"worker:{args['worker']}"
390
+ try:
391
+ role_family(role)
392
+ except ValueError:
393
+ raise LedgerError("invalid", "worker must be an exact worker slug") from None
394
+
395
+
396
+ async def _message_from(evaluation: Evaluation, path: str, args: dict[str, Any]) -> bool:
397
+ fields = {"worker": args["worker"]}
398
+ relay = await evaluation.pending_event(path, "switchboard.message", fields)
399
+ session = await evaluation.pending_event(path, "claude.session_message", fields)
400
+ return relay or session
401
+
402
+
403
+ def _validate_deploy(args: dict[str, Any]) -> None:
404
+ try:
405
+ validate_deploy_environment(args["environment"])
406
+ validate_report_sha(args["sha"])
407
+ except ValueError as exc:
408
+ raise LedgerError("invalid", str(exc)) from None
409
+
410
+
411
+ async def _deploy_finished(evaluation: Evaluation, path: str, args: dict[str, Any]) -> bool:
412
+ return await evaluation.pending_event(path, DEPLOY_STATUS, {**args, "finished": True})
413
+
414
+
415
+ def _validate_lane(args: dict[str, Any]) -> None:
416
+ validate_identity(args["lane"], "lane")
417
+
418
+
419
+ async def _checklist_empty(evaluation: Evaluation, _path: str, args: dict[str, Any]) -> bool:
420
+ lane = await evaluation.uow.find_lane(args["lane"])
421
+ if lane is None or lane.state == "archived":
422
+ return False
423
+ checklist = await evaluation.uow.find_checklist(lane.id)
424
+ return (
425
+ checklist is not None
426
+ and checklist.state == "active"
427
+ and bool(checklist.steps)
428
+ and not checklist.open_steps()
429
+ )
430
+
431
+
432
+ async def _lane_idle(
433
+ evaluation: Evaluation, _path: str, args: dict[str, Any], *, idle_minutes: int
434
+ ) -> bool:
435
+ lane = await evaluation.uow.find_lane(args["lane"])
436
+ if lane is None or lane.state == "archived":
437
+ return False
438
+ last = await evaluation.uow.lane_activity(lane.id)
439
+ tick = await evaluation.uow.latest_event("core.tick")
440
+ if last is None or tick is None or tick.seq <= last.seq:
441
+ return False
442
+ elapsed = datetime.fromisoformat(tick.observed_at) - datetime.fromisoformat(last.observed_at)
443
+ return elapsed.total_seconds() >= idle_minutes * 60
444
+
445
+
446
+ def build_leaf_registry(
447
+ *, image_jobs: tuple[str, ...] = (), lane_idle_minutes: int = 15
448
+ ) -> LeafRegistry:
449
+ registry = LeafRegistry()
450
+ for name, evaluate in (
451
+ ("pr_merged", _pr_merged),
452
+ ("pr_green", _pr_green),
453
+ ("pr_threads_resolved", _pr_threads_resolved),
454
+ ):
455
+ registry.register(LeafSpec(name, _PR_ARGS, "level", _validate_pr_selector, evaluate, True))
456
+ registry.register(
457
+ LeafSpec("issue_closed", (_NUMBER,), "level", _validate_number, _issue_closed, True)
458
+ )
459
+ registry.register(
460
+ LeafSpec(
461
+ "main_green_with_images",
462
+ (replace(_SHA, required=False),),
463
+ "level",
464
+ _validate_main,
465
+ partial(_main_green_with_images, image_jobs=image_jobs),
466
+ True,
467
+ )
468
+ )
469
+ registry.register(LeafSpec("run_finished", (RUN_ID,), "level", _validate_run, _run_finished))
470
+ registry.register(
471
+ LeafSpec("budget_ratio", _BUDGET_RATIO_ARGS, "level", _validate_budget_ratio, _budget_ratio)
472
+ )
473
+ registry.register(
474
+ LeafSpec("message_from", (_WORKER,), "event", _validate_worker, _message_from)
475
+ )
476
+ registry.register(
477
+ LeafSpec("deploy_finished", (_ENV, _SHA), "event", _validate_deploy, _deploy_finished)
478
+ )
479
+ registry.register(
480
+ LeafSpec("checklist_empty", (_LANE,), "level", _validate_lane, _checklist_empty)
481
+ )
482
+ registry.register(
483
+ LeafSpec(
484
+ "lane_idle",
485
+ (_LANE,),
486
+ "level",
487
+ _validate_lane,
488
+ partial(_lane_idle, idle_minutes=lane_idle_minutes),
489
+ )
490
+ )
491
+ return registry
492
+
493
+
494
+ async def create_trigger(
495
+ uow: UnitOfWork,
496
+ args: dict[str, Any],
497
+ *,
498
+ registry: LeafRegistry,
499
+ repository: str | None,
500
+ delivery_routes: Mapping[str, DeliveryRoute],
501
+ imported_id: str | None = None,
502
+ import_note: str | None = None,
503
+ notify_on_fire: bool = False,
504
+ ) -> dict[str, Any]:
505
+ predicate: dict[str, Any] = args["predicate"]
506
+ registry.validate(predicate, repository=repository)
507
+ kind, payload, default_lane = await validate_action(uow, args["action"], delivery_routes)
508
+ lane: str | None = args.get("lane", default_lane)
509
+ if lane is not None:
510
+ try:
511
+ lane_size = len(lane.encode("utf-8"))
512
+ except UnicodeError:
513
+ raise LedgerError("invalid", "lane must be valid UTF-8") from None
514
+ if not lane.strip() or lane_size > 128:
515
+ raise LedgerError("invalid", "lane must be 1-128 UTF-8 bytes")
516
+ mode = args.get("mode", "once")
517
+ if mode not in ("once", "every"):
518
+ raise LedgerError("invalid", "mode must be once or every")
519
+ imported_fired = args.get("imported_fired", False)
520
+ if imported_fired and mode != "once":
521
+ raise LedgerError("invalid", "only once triggers can be imported as fired")
522
+ seq = await uow.allocate_seq()
523
+ trigger = Trigger(
524
+ imported_id or f"trigger_{uuid.uuid7()}",
525
+ lane,
526
+ repository,
527
+ predicate,
528
+ kind,
529
+ payload,
530
+ "fired" if imported_fired else "open",
531
+ {},
532
+ seq,
533
+ fired_seq=seq if imported_fired else None,
534
+ mode=mode,
535
+ import_note=import_note,
536
+ notify_on_fire=notify_on_fire,
537
+ )
538
+ await uow.save_trigger(trigger)
539
+ return {"id": trigger.id}
540
+
541
+
542
+ async def cancel_trigger(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
543
+ trigger = await uow.find_trigger(args["trigger_id"])
544
+ if trigger is None:
545
+ raise LedgerError("not_found", "trigger not found")
546
+ if trigger.state == "fired":
547
+ raise LedgerError("conflict", "trigger has already fired")
548
+ if trigger.state != "canceled":
549
+ await uow.save_trigger(replace(trigger, state="canceled"))
550
+ return {"id": trigger.id, "state": "canceled"}