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,808 @@
1
+ """The ledger: the one write path into a project's event log (AD-2, AD-3, AD-14)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import copy
7
+ import math
8
+ from collections.abc import Awaitable, Callable, Mapping
9
+ from dataclasses import dataclass, replace
10
+ from datetime import datetime
11
+ from functools import partial
12
+ from typing import Any
13
+ from uuid import uuid4
14
+
15
+ from plotroom.core.actions import ACTION_PAGE_SIZE, Action, QueuedAction
16
+ from plotroom.core.ask_checks import DEFAULT_ASK_STALE_DAYS
17
+ from plotroom.core.briefs import BRIEF, BriefSettings
18
+ from plotroom.core.catalog import Catalog
19
+ from plotroom.core.claims import PR_CLAIM_OVERLAP, TICKET_TREE_MOVE, Claim, sync_items
20
+ from plotroom.core.commands import COMMAND_APPENDER, command_kind
21
+ from plotroom.core.events import (
22
+ AppendResult,
23
+ Event,
24
+ LedgerError,
25
+ NewEvent,
26
+ format_time,
27
+ is_json,
28
+ validate_fields,
29
+ )
30
+ from plotroom.core.github import (
31
+ SNAPSHOT_HEALTH,
32
+ FetchCursor,
33
+ FetchRetry,
34
+ GitHubSummary,
35
+ ObservedPull,
36
+ PullRequest,
37
+ apply_pull_poll,
38
+ )
39
+ from plotroom.core.github_projection import GitHubResource
40
+ from plotroom.core.merge_controller import ACTIVE_MERGE_ITEMS, reconcile_merge_controller
41
+ from plotroom.core.merge_gate import GatePolicy, GateSnapshot, GateVerdict, evaluate_gate
42
+ from plotroom.core.next_items import Item
43
+ from plotroom.core.operator_goals import report_goals, validate_goal_name
44
+ from plotroom.core.roles import OwnershipView, role_family
45
+ from plotroom.core.run_reports import validate_identity
46
+ from plotroom.core.search import SemanticSearch
47
+ from plotroom.core.search_sources import PRIVATE_KINDS, SEARCH_KINDS
48
+ from plotroom.core.triggers import trigger_snapshot_is_too_deep
49
+ from plotroom.core.unit_of_work import UnitOfWork
50
+ from plotroom.core.watchers import Watchers
51
+ from plotroom.core.writer import ProjectWriter
52
+ from plotroom.ports.clock import Clock
53
+ from plotroom.ports.search import MAX_SEARCH_LIMIT, MAX_SEARCH_QUERY_LENGTH, Search, SearchPage
54
+ from plotroom.ports.store import Board, Store, Transaction
55
+ from plotroom.ports.work_items import WorkItem, WorkItemSource
56
+
57
+ _WAITING_FOR_GITHUB = "waiting for the first GitHub poll"
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class CommandResult:
62
+ """What a command returned; ``replayed`` is true when it is the first call's stored result."""
63
+
64
+ result: dict[str, Any]
65
+ replayed: bool
66
+
67
+
68
+ def _check_role(role: str) -> str:
69
+ try:
70
+ return role_family(role)
71
+ except ValueError as exc:
72
+ raise LedgerError("invalid", str(exc)) from None
73
+
74
+
75
+ def _consume_write_failure(future: asyncio.Future[None]) -> None:
76
+ if not future.cancelled():
77
+ future.exception()
78
+
79
+
80
+ class Ledger:
81
+ """One project's event log: typed appends and deduplicated commands, one transaction each."""
82
+
83
+ def __init__(
84
+ self,
85
+ store: Store,
86
+ catalog: Catalog,
87
+ clock: Clock,
88
+ *,
89
+ watcher_roles: tuple[str, ...] = (),
90
+ wait_cap: int = 240,
91
+ github_repository: str | None = None,
92
+ merge_gate_policy: GatePolicy | None = None,
93
+ github_tree_path: str | None = None,
94
+ session_workers: Mapping[str, str] | None = None,
95
+ drain_enabled: bool = False,
96
+ bridge_workers: tuple[str, ...] | None = None,
97
+ brief_settings: BriefSettings | None = None,
98
+ live_merge_controller: bool = False,
99
+ merge_clerk: Callable[[], Awaitable[bool]] | None = None,
100
+ fixture_merge_enabled: bool = False,
101
+ fixture_branch_updates: bool = False,
102
+ human_login: str | None = None,
103
+ ask_stale_days: int = DEFAULT_ASK_STALE_DAYS,
104
+ search: Search | None = None,
105
+ semantic_search: SemanticSearch | None = None,
106
+ ) -> None:
107
+ if search is not None and search.project_id != store.project_id:
108
+ raise ValueError("a ledger and its search index must belong to the same project")
109
+ if semantic_search is not None and semantic_search.index.project_id != store.project_id:
110
+ raise ValueError("a ledger and its embedding index must belong to the same project")
111
+ self._store = store
112
+ self._search = search
113
+ self._semantic_search = semantic_search
114
+ self._catalog = catalog
115
+ self._clock = clock
116
+ self._writer = ProjectWriter(store)
117
+ self.watchers = Watchers(watcher_roles)
118
+ self._wait_cap = wait_cap
119
+ self._bridge_workers = bridge_workers
120
+ self.github_repository = github_repository
121
+ self._merge_gate_policy = merge_gate_policy or GatePolicy()
122
+ self._github_tree_path = github_tree_path
123
+ self._live_merge_controller = live_merge_controller
124
+ self._merge_clerk = merge_clerk
125
+ self.confirm_merge_gate: Callable[[GateSnapshot], Awaitable[GateSnapshot | None]] | None = (
126
+ None
127
+ )
128
+ self._fixture_merge_enabled = fixture_merge_enabled
129
+ self._fixture_branch_updates = fixture_branch_updates
130
+ self.github_error = _WAITING_FOR_GITHUB if github_repository else None
131
+ self._github_error_revision = 0
132
+ # A reopened ledger does not inherit the previous daemon's health.
133
+ self._github_snapshot_epoch = uuid4().hex
134
+ self.session_workers = dict(session_workers or {})
135
+ self._drain_enabled = drain_enabled
136
+ self._brief_settings = brief_settings or BriefSettings()
137
+ self._human_login = human_login
138
+ self._ask_stale_days = ask_stale_days
139
+ self._stopping = asyncio.Event()
140
+
141
+ @property
142
+ def commit_signal(self) -> asyncio.Event:
143
+ return self._writer.commit_signal
144
+
145
+ @property
146
+ def merge_gate_policy(self) -> GatePolicy:
147
+ return self._merge_gate_policy
148
+
149
+ async def pending_action(self) -> Action | None:
150
+ return await self._store.pending_action()
151
+
152
+ async def pending_actions(
153
+ self,
154
+ *,
155
+ after: int,
156
+ skip_branch_updates: bool,
157
+ skip_controller_merges: bool = False,
158
+ skip_bridge_workers: tuple[str, ...] | None = None,
159
+ ) -> tuple[QueuedAction, ...]:
160
+ return await self._store.pending_actions(
161
+ after=after,
162
+ limit=ACTION_PAGE_SIZE,
163
+ skip_branch_updates=skip_branch_updates,
164
+ skip_controller_merges=skip_controller_merges,
165
+ skip_bridge_workers=skip_bridge_workers,
166
+ )
167
+
168
+ @property
169
+ def project_id(self) -> str:
170
+ return self._store.project_id
171
+
172
+ async def search(
173
+ self, text: str, kinds: tuple[str, ...] | None, limit: int, *, role: str = "system"
174
+ ) -> SearchPage:
175
+ visible = SEARCH_KINDS
176
+ if _check_role(role) != "orchestrator":
177
+ visible -= PRIVATE_KINDS
178
+ if self._search is None:
179
+ raise LedgerError("unavailable", "the project search index is unavailable")
180
+ if not text.strip() or len(text) > MAX_SEARCH_QUERY_LENGTH or "\x00" in text:
181
+ raise LedgerError(
182
+ "invalid", f"search text must contain 1 to {MAX_SEARCH_QUERY_LENGTH} characters"
183
+ )
184
+ if not 1 <= limit <= MAX_SEARCH_LIMIT:
185
+ raise LedgerError("invalid", f"search limit must be between 1 and {MAX_SEARCH_LIMIT}")
186
+ if kinds is not None:
187
+ visible = visible.intersection(kinds)
188
+ selected = tuple(sorted(visible))
189
+ if self._semantic_search is not None:
190
+ return await self._semantic_search.query(
191
+ self._search, self.project_id, text.strip(), selected, limit
192
+ )
193
+ return await self._search.query(self.project_id, text.strip(), selected, limit)
194
+
195
+ def start(self) -> None:
196
+ self._stopping.clear()
197
+ self._writer.start()
198
+
199
+ async def clean_disabled_merge_items(self) -> None:
200
+ if not self._live_merge_controller:
201
+
202
+ async def clear(uow: UnitOfWork) -> None:
203
+ for kind in ACTIVE_MERGE_ITEMS:
204
+ for subject in sorted(await uow.active_item_subjects(kind)):
205
+ await uow.clear_item(kind, subject)
206
+
207
+ await self.run("system", clear)
208
+
209
+ async def initialize_overlaps(self) -> None:
210
+ """Materialize conflicts from facts already stored before the daemon opened."""
211
+
212
+ async def restore(uow: UnitOfWork) -> None:
213
+ if self.github_repository is None:
214
+ for kind in (PR_CLAIM_OVERLAP, TICKET_TREE_MOVE):
215
+ await sync_items(uow, kind, {})
216
+ else:
217
+ uow.pull_overlaps_changed()
218
+
219
+ await self.run("system", restore)
220
+
221
+ async def stop(self) -> None:
222
+ """Finish the queued inputs and stop the writer; later inputs fail ``unavailable``."""
223
+ self.stop_waiting()
224
+ await self._writer.stop()
225
+
226
+ def gate_availability(self, snapshot: GateSnapshot) -> GateSnapshot:
227
+ return replace(snapshot, github_unavailable=self.github_error is not None)
228
+
229
+ async def set_github_error(self, error: str | None) -> None:
230
+ changed = self.github_error != error
231
+ self.github_error = error
232
+ self._github_error_revision += 1
233
+ repository = self.github_repository
234
+ if repository is None:
235
+ if changed:
236
+ await self.refresh_merge_controller()
237
+ return
238
+
239
+ marker = self._snapshot_health_cursor(error, format_time(self._clock.now()))
240
+ if changed and self._live_merge_controller:
241
+
242
+ async def publish(uow: UnitOfWork) -> None:
243
+ await uow.save_fetch_cursor(repository, SNAPSHOT_HEALTH, marker)
244
+ uow.all_merge_pulls = True
245
+
246
+ publication = self._enqueue_work("system", publish)
247
+ else:
248
+
249
+ async def publish_silently(tx: Transaction) -> None:
250
+ previous = await tx.fetch_cursor(repository, SNAPSHOT_HEALTH)
251
+ if previous is None or previous.watermark != marker.watermark:
252
+ await tx.save_fetch_cursor(repository, SNAPSHOT_HEALTH, marker)
253
+
254
+ publication = self._writer.enqueue(publish_silently, notify=False)
255
+
256
+ # Health is already fail-closed. Publish that accepted observation
257
+ # even if its caller stops waiting behind another writer input.
258
+ publication.add_done_callback(_consume_write_failure)
259
+ await asyncio.shield(publication)
260
+
261
+ def _snapshot_health_cursor(self, error: str | None, as_of: str) -> FetchCursor:
262
+ status = "-" if error is None else "+" + error
263
+ return FetchCursor(self._github_snapshot_epoch + status, as_of, 1)
264
+
265
+ async def commit_github_pull_poll(
266
+ self,
267
+ repository: str,
268
+ baseline: FetchCursor | None,
269
+ pulls: tuple[ObservedPull, ...],
270
+ as_of: str,
271
+ ) -> bool:
272
+ error_revision = self._github_error_revision
273
+ refresh: asyncio.Future[None] | None = None
274
+
275
+ async def commit_observation(uow: UnitOfWork) -> bool:
276
+ committed = await apply_pull_poll(uow, repository, baseline, pulls, as_of)
277
+ if committed:
278
+ await uow.save_fetch_cursor(
279
+ repository, SNAPSHOT_HEALTH, self._snapshot_health_cursor(None, as_of)
280
+ )
281
+ return committed
282
+
283
+ def publish(committed: bool) -> None:
284
+ nonlocal refresh
285
+ if (
286
+ not committed
287
+ or self.github_error is None
288
+ or self._github_error_revision != error_revision
289
+ ):
290
+ return
291
+ self.github_error = None
292
+ if self._live_merge_controller and self._writer.running:
293
+ refresh = self._enqueue_work("system", self._mark_all_merge_pulls)
294
+ # A canceled active poll still commits and queues its refresh.
295
+ refresh.add_done_callback(_consume_write_failure)
296
+
297
+ committed = await self.run("system", commit_observation, after_commit=publish)
298
+ if refresh is not None:
299
+ await asyncio.shield(refresh)
300
+ return committed
301
+
302
+ @staticmethod
303
+ async def _mark_all_merge_pulls(uow: UnitOfWork) -> None:
304
+ uow.all_merge_pulls = True
305
+
306
+ async def refresh_merge_controller(self) -> None:
307
+ if self._live_merge_controller:
308
+ await self.run("system", self._mark_all_merge_pulls)
309
+
310
+ async def _refresh_merge_controller(self, uow: UnitOfWork) -> None:
311
+ if (
312
+ self._live_merge_controller
313
+ and self.github_repository is not None
314
+ and (
315
+ uow.all_merge_pulls
316
+ or uow.merge_pull_numbers
317
+ or uow.merge_check_heads
318
+ or uow.merge_observations
319
+ )
320
+ ):
321
+ clerk = await self._merge_clerk() if self._merge_clerk is not None else False
322
+ await reconcile_merge_controller(
323
+ uow,
324
+ self.github_repository,
325
+ self.merge_gate_policy,
326
+ github_unavailable=self.github_error is not None,
327
+ clerk=clerk,
328
+ stage_fixture_merges=self._fixture_merge_enabled,
329
+ branch_updates=self._fixture_branch_updates,
330
+ )
331
+
332
+ async def _evaluate_triggers(self, tx: Transaction) -> None:
333
+ if (leaves := self._catalog.trigger_leaves) is not None:
334
+ uow = UnitOfWork(
335
+ tx,
336
+ self._catalog.events,
337
+ self._clock,
338
+ role="system",
339
+ items=self._catalog.items,
340
+ search=self._search,
341
+ )
342
+ await leaves.evaluate_open(uow)
343
+
344
+ async def run[T](
345
+ self,
346
+ role: str,
347
+ work: Callable[[UnitOfWork], Awaitable[T]],
348
+ *,
349
+ after_commit: Callable[[T], None] | None = None,
350
+ ) -> T:
351
+ """Run ``work`` as one input in one transaction; its appends are checked as ``role``."""
352
+ return await self._enqueue_work(role, work, after_commit=after_commit)
353
+
354
+ def _enqueue_work[T](
355
+ self,
356
+ role: str,
357
+ work: Callable[[UnitOfWork], Awaitable[T]],
358
+ *,
359
+ after_commit: Callable[[T], None] | None = None,
360
+ ) -> asyncio.Future[T]:
361
+ _check_role(role)
362
+
363
+ async def in_transaction(tx: Transaction) -> T:
364
+ uow = UnitOfWork(
365
+ tx,
366
+ self._catalog.events,
367
+ self._clock,
368
+ role=role,
369
+ items=self._catalog.items,
370
+ search=self._search,
371
+ )
372
+ result = await work(uow)
373
+ await uow.refresh_overlaps(self.github_repository, self._github_tree_path)
374
+ await self._refresh_merge_controller(uow)
375
+ await uow.refresh_asks(self.github_repository, self._human_login, self._ask_stale_days)
376
+ await self._evaluate_triggers(tx)
377
+ return result
378
+
379
+ return self._writer.enqueue(in_transaction, after_commit=after_commit)
380
+
381
+ async def append(self, role: str, event: NewEvent) -> AppendResult:
382
+ """Append one event as ``role``. A duplicate returns the stored event, ``created=False``."""
383
+ _check_role(role)
384
+ self._catalog.events.validate_identity(role, event) # refuse before queueing
385
+ return await self.run(role, lambda uow: uow.append(event))
386
+
387
+ async def execute(
388
+ self, role: str, command: str, request_id: str, args: dict[str, Any]
389
+ ) -> CommandResult:
390
+ """Run a mutating command once per ``(role, command, request_id)``.
391
+
392
+ The first call runs the handler and records a ``core.<command>`` event with its arguments
393
+ and result in the same transaction. A retry returns that result and runs nothing.
394
+ A failed handler leaves nothing behind and the error reaches the caller.
395
+ """
396
+ family = _check_role(role)
397
+ registered = self._catalog.commands.get(command)
398
+ if registered is None:
399
+ raise LedgerError("invalid", f"unknown command {command!r}")
400
+ rule = self._catalog.writer_rules.rule_for(command, family)
401
+ if rule is None:
402
+ raise LedgerError("forbidden", f"role {role!r} may not execute {command}")
403
+ if family == "drain" and not self._drain_enabled:
404
+ raise LedgerError("forbidden", "no drain session is configured for this project")
405
+ if not isinstance(request_id, str) or not request_id: # pyright: ignore[reportUnnecessaryIsInstance]
406
+ raise LedgerError("invalid", f"{command}: request_id must be a non-empty string")
407
+ if not isinstance(args, dict): # pyright: ignore[reportUnnecessaryIsInstance]
408
+ raise LedgerError("invalid", f"{command}: args must be an object")
409
+ # One snapshot is validated, copied to the handler and recorded in the receipt, so a caller
410
+ # mutating its dict while the handler runs changes none of the three.
411
+ try:
412
+ # An overdeep trigger can still replay an existing receipt without copying its body.
413
+ snapshot = (
414
+ None
415
+ if command == "trigger" and trigger_snapshot_is_too_deep(args)
416
+ else copy.deepcopy(args)
417
+ )
418
+ except RecursionError:
419
+ raise LedgerError("invalid", f"{command}: arguments are nested too deeply") from None
420
+ kind = command_kind(command)
421
+ upstream_id = f"{role}:{request_id}"
422
+
423
+ async def in_transaction(
424
+ tx: Transaction, *, check_only: bool = False
425
+ ) -> CommandResult | None:
426
+ uow = UnitOfWork(
427
+ tx,
428
+ self._catalog.events,
429
+ self._clock,
430
+ role=role,
431
+ append_role=COMMAND_APPENDER,
432
+ items=self._catalog.items,
433
+ search=self._search,
434
+ )
435
+ recorded = await uow.find_event("core", kind, upstream_id)
436
+ receipt = recorded.fields if recorded is not None else None
437
+ if receipt is None and registered.record_if is not None:
438
+ receipt = await tx.find_noop_receipt(command, upstream_id)
439
+ # A retry can supply different arguments. Authorize the actual target of the
440
+ # receipt, so new arguments cannot make a previous target visible.
441
+ target: dict[str, Any]
442
+ if receipt is None:
443
+ if snapshot is None:
444
+ raise LedgerError("invalid", f"{command}: arguments are nested too deeply")
445
+ target = snapshot
446
+ try:
447
+ validate_fields(registered.args, target, command)
448
+ except RecursionError:
449
+ raise LedgerError(
450
+ "invalid", f"{command}: arguments are nested too deeply"
451
+ ) from None
452
+ else:
453
+ target = receipt["args"]
454
+ if rule.owns is not None:
455
+ view = OwnershipView(role, uow.find_event, uow.find_item, uow.find_lane)
456
+ if not await rule.owns(view, copy.deepcopy(target)):
457
+ raise LedgerError(
458
+ "forbidden", f"role {role!r} does not own the target of {command}"
459
+ )
460
+ if receipt is not None:
461
+ return CommandResult(receipt["result"], True)
462
+ if check_only:
463
+ return None
464
+ result = await registered.handler(uow, copy.deepcopy(target))
465
+ if not isinstance(result, dict) or not is_json(result): # pyright: ignore[reportUnnecessaryIsInstance]
466
+ raise TypeError(f"command {command!r} must return a JSON object")
467
+ await uow.refresh_overlaps(self.github_repository, self._github_tree_path)
468
+ await uow.refresh_asks(self.github_repository, self._human_login, self._ask_stale_days)
469
+ if registered.record_if is not None and not registered.record_if(result):
470
+ await tx.insert_noop_receipt(
471
+ command, upstream_id, {"args": target, "result": result}
472
+ )
473
+ else:
474
+ await uow.append(
475
+ NewEvent(
476
+ source="core",
477
+ kind=kind,
478
+ upstream_id=upstream_id,
479
+ fields={
480
+ "role": role,
481
+ "request_id": request_id,
482
+ "args": copy.deepcopy(target),
483
+ "result": result,
484
+ },
485
+ lane_id=target["lane"] if registered.lane_scoped else None,
486
+ )
487
+ )
488
+ await self._refresh_merge_controller(uow)
489
+ await self._evaluate_triggers(tx)
490
+ return CommandResult(result, False)
491
+
492
+ if registered.preflight is not None:
493
+ replay = await self._writer.submit(partial(in_transaction, check_only=True))
494
+ if replay is not None:
495
+ return replay
496
+ assert snapshot is not None
497
+ try:
498
+ await registered.preflight(copy.deepcopy(snapshot))
499
+ except LedgerError:
500
+ # A concurrent request may have committed this receipt during preflight.
501
+ replay = await self._writer.submit(partial(in_transaction, check_only=True))
502
+ if replay is None:
503
+ raise
504
+ return replay
505
+ committed = await self._writer.submit(in_transaction)
506
+ assert committed is not None
507
+ return committed
508
+
509
+ async def head_seq(self) -> int:
510
+ """The last allocated ``seq``. Reads committed state, not through the writer."""
511
+ return await self._store.head_seq()
512
+
513
+ async def events_after(self, seq: int, limit: int = 100) -> list[Event]:
514
+ """Committed events above ``seq``, ascending."""
515
+ return await self._store.events_after(seq, limit)
516
+
517
+ async def budget_status(self, role: str, run: str | None = None) -> list[dict[str, Any]]:
518
+ """Return current committed budget rows, optionally for one run."""
519
+ if _check_role(role) != "orchestrator":
520
+ raise LedgerError("forbidden", "only the orchestrator may read budgets")
521
+ if run is not None:
522
+ validate_identity(run, "run")
523
+ return [budget.render() for budget in await self._store.read_budgets(run)]
524
+
525
+ def stop_waiting(self) -> None:
526
+ self._stopping.set()
527
+ self.commit_signal.set()
528
+
529
+ async def wait_for_item(
530
+ self,
531
+ role: str,
532
+ cursor: int | None,
533
+ seconds: float | None,
534
+ progress: Callable[[float, float], Awaitable[None]],
535
+ ) -> tuple[int, dict[str, Any] | None]:
536
+ """Wait for the first change visible to the caller and return its resume cursor."""
537
+ _check_role(role)
538
+ if role == "drain" and not self._drain_enabled:
539
+ raise LedgerError("forbidden", "no drain session is configured for this project")
540
+ if cursor is not None and not 0 <= cursor <= 2**63 - 1:
541
+ raise LedgerError("invalid", "cursor must be a nonnegative ledger sequence")
542
+ if seconds is not None and (not math.isfinite(seconds) or seconds < 0):
543
+ raise LedgerError("invalid", "timeout must be a nonnegative finite number")
544
+ cap = float(self._wait_cap) if seconds is None else min(seconds, self._wait_cap)
545
+ now = asyncio.get_running_loop().time
546
+ started = now()
547
+ until = started + cap
548
+ position = await self.head_seq() if cursor is None else cursor
549
+ interval = min(15, cap / 2)
550
+ report_at = started
551
+ with self.watchers.waiting(role):
552
+ while True:
553
+ if self._stopping.is_set():
554
+ raise LedgerError("unavailable", "the project is stopping")
555
+ committed = self.commit_signal
556
+ wake_at = until
557
+ is_bridge = role == "bridge" and self._bridge_workers is not None
558
+ if role == "drain" or is_bridge:
559
+ check_started = now()
560
+ moment = self._clock.now()
561
+ if is_bridge:
562
+ assert self._bridge_workers is not None
563
+ readiness = await self._store.bridge_readiness(
564
+ self._bridge_workers, format_time(moment)
565
+ )
566
+ else:
567
+ readiness = await self._store.outbox_readiness(format_time(moment))
568
+ head = readiness.head
569
+ change = None
570
+ # Pending work remains actionable when resuming from a saved cursor or
571
+ # after a lease expires. The wake contains no lease or delivery payload.
572
+ if readiness.ready_seq is not None:
573
+ kind = "bridge_ready" if is_bridge else "outbox_ready"
574
+ change = {"kind": kind, "seq": readiness.ready_seq}
575
+ if readiness.next_expiry is not None:
576
+ delay = datetime.fromisoformat(readiness.next_expiry) - moment
577
+ wake_at = min(until, check_started + delay.total_seconds())
578
+ else:
579
+ head, change = await self._store.first_item_change(role, position)
580
+ if position > head:
581
+ raise LedgerError("invalid", "cursor is ahead of the project ledger")
582
+ if change is not None:
583
+ return max(position, int(change["seq"])), change
584
+ # Advancing past invisible rows is safe because the read used one committed view.
585
+ position = head
586
+ current = now()
587
+ if current >= until:
588
+ return position, None
589
+ if current >= report_at:
590
+ await progress(current - started, cap)
591
+ report_at = current + interval
592
+ try:
593
+ async with asyncio.timeout_at(min(wake_at, report_at)):
594
+ await committed.wait()
595
+ except TimeoutError:
596
+ continue
597
+
598
+ async def ready_work_items(self) -> tuple[WorkItem, ...]:
599
+ return await self._store.ready_work_items()
600
+
601
+ async def read_next(self, role: str, offset: int, limit: int) -> tuple[int, list[Item]]:
602
+ return await self._store.read_next(role, offset, limit)
603
+
604
+ async def read_open_item(self, role: str, item_id: str) -> Item | None:
605
+ return await self._store.read_open_item(role, item_id)
606
+
607
+ async def read_board(self, role: str) -> Board:
608
+ return await self._store.read_board(role)
609
+
610
+ async def snapshot_board(self, role: str) -> tuple[Board, GitHubSummary | None]:
611
+ board, github, _, _ = await self.read_snapshot(role)
612
+ return board, github
613
+
614
+ async def snapshot_summary(
615
+ self, role: str, *, checklist_lane: str | None = None
616
+ ) -> tuple[Board, GitHubSummary | None, dict[str, int], int, str | None]:
617
+ board, github, counts, claims, freeze, _ = await self._store.read_snapshot(
618
+ role, self.github_repository, checklist_lane=checklist_lane
619
+ )
620
+ return board, github, counts, claims, freeze
621
+
622
+ async def snapshot_observation(
623
+ self, role: str, *, checklist_lane: str | None = None
624
+ ) -> tuple[Board, GitHubSummary | None, dict[str, int], int, str | None, str | None]:
625
+ board, github, counts, claims, freeze, health = await self._store.read_snapshot(
626
+ role,
627
+ self.github_repository,
628
+ checklist_lane=checklist_lane,
629
+ include_github_health=True,
630
+ )
631
+ error = None
632
+ if github is not None:
633
+ error = _WAITING_FOR_GITHUB
634
+ status = ""
635
+ if health is not None and health.watermark.startswith(self._github_snapshot_epoch):
636
+ status = health.watermark[len(self._github_snapshot_epoch) :]
637
+ if status == "-" and github.as_of is not None:
638
+ error = None
639
+ elif status.startswith("+"):
640
+ error = status[1:]
641
+ return board, github, counts, claims, freeze, error
642
+
643
+ async def snapshot_with_triggers(
644
+ self, role: str
645
+ ) -> tuple[Board, GitHubSummary | None, dict[str, int]]:
646
+ board, github, trigger_counts, _ = await self.read_snapshot(role)
647
+ return board, github, trigger_counts
648
+
649
+ async def read_snapshot(
650
+ self, role: str
651
+ ) -> tuple[Board, GitHubSummary | None, dict[str, int], int]:
652
+ board, github, counts, claims, _ = await self.snapshot_summary(role)
653
+ return board, github, counts, claims
654
+
655
+ async def read_claims(
656
+ self, role: str, lane: str | None, offset: int, limit: int
657
+ ) -> tuple[int, list[Claim]]:
658
+ return await self._store.read_claims(role, lane, offset, limit)
659
+
660
+ async def brief(
661
+ self, role: str, work_item: str, worker: str, source: WorkItemSource | None
662
+ ) -> str:
663
+ if _check_role(role) not in self._catalog.read_roles.get(BRIEF, ()):
664
+ raise LedgerError("forbidden", "only the orchestrator may read a lane brief")
665
+ if worker not in self._catalog.workers:
666
+ raise LedgerError("not_found", "configured worker not found")
667
+ if not work_item or not work_item.isprintable() or not work_item.strip():
668
+ raise LedgerError("invalid", "work_item must be a nonempty printable reference")
669
+ if source is None:
670
+ raise LedgerError("unavailable", "a work-item source is not configured")
671
+ try:
672
+ source_text = await source.body(work_item)
673
+ except OSError, ValueError:
674
+ raise LedgerError("unavailable", "the work-item source could not be read") from None
675
+ if source_text is None:
676
+ raise LedgerError("not_found", "work-item text not found in the configured source")
677
+ lane, claims = await self._store.read_brief_claims(worker)
678
+ return self._brief_settings.render(work_item, worker, source_text, lane, claims)
679
+
680
+ async def read_overlaps(
681
+ self, role: str, lane: str | None, pr: int | None, offset: int, limit: int
682
+ ) -> tuple[int, list[Item]]:
683
+ return await self._store.read_overlaps(role, lane, pr, offset, limit)
684
+
685
+ async def list_triggers(self, role: str, lane: str | None) -> list[dict[str, Any]]:
686
+ if _check_role(role) != "orchestrator":
687
+ raise LedgerError("forbidden", "only the orchestrator may list triggers")
688
+ return [trigger.render() for trigger in await self._store.list_triggers(lane)]
689
+
690
+ async def merge_gate(
691
+ self,
692
+ role: str,
693
+ pr: int,
694
+ *,
695
+ expected_head_sha: str | None = None,
696
+ expected_main_sha: str | None = None,
697
+ ) -> GateVerdict:
698
+ if _check_role(role) not in {"clerk", "orchestrator"}:
699
+ raise LedgerError(
700
+ "forbidden", "only the clerk and orchestrator may query the merge gate"
701
+ )
702
+ if not 1 <= pr <= 2**63 - 1:
703
+ raise LedgerError("invalid", "pr must be a positive SQLite integer")
704
+
705
+ async def current() -> GateSnapshot:
706
+ return self.gate_availability(
707
+ await self._store.read_merge_gate(self.github_repository, pr)
708
+ )
709
+
710
+ def judge(snapshot: GateSnapshot) -> GateVerdict:
711
+ return evaluate_gate(
712
+ snapshot,
713
+ self._merge_gate_policy,
714
+ self._clock.now(),
715
+ expected_head_sha=expected_head_sha,
716
+ expected_main_sha=expected_main_sha,
717
+ )
718
+
719
+ snapshot = await current()
720
+ verdict = judge(snapshot)
721
+ if verdict.verdict != "MERGE" or (expected_head_sha is None and expected_main_sha is None):
722
+ return verdict
723
+ confirm = self.confirm_merge_gate
724
+ fresh = await confirm(snapshot) if confirm is not None else None
725
+ if fresh is None:
726
+ return judge(replace(snapshot, github_unavailable=True))
727
+
728
+ # Local policy (freeze, branch ownership and availability) can change while reading.
729
+ latest = await current()
730
+ latest_verdict = judge(latest)
731
+ if latest_verdict.verdict != "MERGE":
732
+ return latest_verdict
733
+ if latest.pull != snapshot.pull and (
734
+ latest.pull is None
735
+ or snapshot.pull is None
736
+ or replace(latest.pull, as_of=snapshot.pull.as_of) != snapshot.pull
737
+ ):
738
+ return judge(replace(latest, github_unavailable=True))
739
+ return judge(
740
+ replace(
741
+ fresh,
742
+ freeze_reason=latest.freeze_reason,
743
+ lane=latest.lane,
744
+ earlier_pull=latest.earlier_pull,
745
+ ambiguous_lane=latest.ambiguous_lane,
746
+ github_unavailable=latest.github_unavailable,
747
+ )
748
+ )
749
+
750
+ async def list_decisions(self, role: str, governs: str | None) -> list[dict[str, Any]]:
751
+ if _check_role(role) != "orchestrator":
752
+ raise LedgerError("forbidden", "only the orchestrator may list decisions")
753
+ return [decision.render() for decision in await self._store.list_decisions(governs)]
754
+
755
+ async def pending_ask_issues(self, repository: str) -> set[int]:
756
+ if self._human_login is None or repository != self.github_repository:
757
+ return set()
758
+ return await self._store.pending_ask_issues(repository)
759
+
760
+ async def goals_use_blockers(self) -> bool:
761
+ return await self._store.goals_use_blockers()
762
+
763
+ async def goal(self, role: str, name: str | None) -> dict[str, Any]:
764
+ if _check_role(role) != "orchestrator":
765
+ raise LedgerError("forbidden", "only the orchestrator may read operator goals")
766
+ if name is not None:
767
+ validate_goal_name(name)
768
+ goals, facts = await self._store.read_goals(
769
+ name,
770
+ self.github_repository,
771
+ self._human_login,
772
+ )
773
+ if not goals:
774
+ if name is not None:
775
+ raise LedgerError("not_found", "goal not found")
776
+ return {"done": False, "goals": []}
777
+ if facts is None or self.github_error is not None:
778
+ raise LedgerError(
779
+ "unavailable", "goal evaluation needs an available GitHub issue projection"
780
+ )
781
+ return report_goals(goals, facts)
782
+
783
+ async def list_asks(self, role: str, stale_only: bool) -> list[dict[str, Any]]:
784
+ if role != "orchestrator":
785
+ raise LedgerError("forbidden", "only the orchestrator may list asks")
786
+ return [ask.render() for ask in await self._store.list_asks(stale_only)]
787
+
788
+ async def pull_request(self, repository: str, number: int) -> PullRequest | None:
789
+ return await self._store.pull_request(repository, number)
790
+
791
+ async def github_resource(
792
+ self, repository: str, resource: str, scope: str = ""
793
+ ) -> GitHubResource | None:
794
+ return await self._store.github_resource(repository, resource, scope)
795
+
796
+ async def github_pull_targets(self, repository: str) -> tuple[PullRequest, ...]:
797
+ return await self._store.github_pull_targets(repository)
798
+
799
+ async def github_pending_merge_shas(
800
+ self, repository: str, as_of: str, limit: int
801
+ ) -> tuple[PullRequest, ...]:
802
+ return await self._store.github_pending_merge_shas(repository, as_of, limit)
803
+
804
+ async def fetch_cursor(self, repository: str, resource: str) -> FetchCursor | None:
805
+ return await self._store.fetch_cursor(repository, resource)
806
+
807
+ async def fetch_retry(self, repository: str, resource: str) -> FetchRetry | None:
808
+ return await self._store.fetch_retry(repository, resource)