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,331 @@
1
+ """Persistence for the project GitHub projection."""
2
+
3
+ import json
4
+ from dataclasses import asdict
5
+ from typing import Any
6
+
7
+ from sqlalchemy import text
8
+ from sqlalchemy.engine import Row
9
+ from sqlalchemy.ext.asyncio import AsyncConnection
10
+
11
+ from plotroom.core.github import (
12
+ ACTIVE_PULL_DETAIL_BUDGET,
13
+ MERGE_SHA_ATTEMPT_PREFIX,
14
+ PULL_DETAIL_ATTEMPT_PREFIX,
15
+ PULL_REQUESTS,
16
+ TERMINAL_PULL_DETAIL_BUDGET,
17
+ FetchCursor,
18
+ FetchRetry,
19
+ GitHubSummary,
20
+ PullRequest,
21
+ )
22
+ from plotroom.core.github_projection import GitHubRecord, GitHubResource
23
+ from plotroom.core.lanes import Lane, with_projected_pr
24
+
25
+ PULL = text(
26
+ "SELECT * FROM github_pull_requests WHERE repository = :repository AND number = :number"
27
+ )
28
+ SAVE_PULL = text("""
29
+ INSERT INTO github_pull_requests
30
+ (repository, number, branch, head_sha, head_repository, state, updated_at,
31
+ as_of, complete, version, draft, merge_commit_sha)
32
+ VALUES (
33
+ :repository, :number, :branch, :head_sha, :head_repository, :state, :updated_at,
34
+ :as_of, :complete, :version, :draft, :merge_commit_sha
35
+ )
36
+ ON CONFLICT (repository, number) DO UPDATE SET branch = excluded.branch,
37
+ head_sha = excluded.head_sha, state = excluded.state, updated_at = excluded.updated_at,
38
+ head_repository = excluded.head_repository,
39
+ as_of = excluded.as_of, complete = excluded.complete, version = excluded.version,
40
+ draft = excluded.draft, merge_commit_sha = excluded.merge_commit_sha
41
+ """)
42
+ CURSOR = text("""
43
+ SELECT watermark, as_of, generation FROM github_fetch_cursors
44
+ WHERE repository = :repository AND resource = :resource
45
+ """)
46
+ SAVE_CURSOR = text("""
47
+ INSERT INTO github_fetch_cursors (repository, resource, watermark, as_of, generation)
48
+ VALUES (:repository, :resource, :watermark, :as_of, :generation)
49
+ ON CONFLICT (repository, resource) DO UPDATE SET watermark = excluded.watermark,
50
+ as_of = excluded.as_of, generation = excluded.generation
51
+ """)
52
+ OPEN_COUNT = text("""
53
+ SELECT count(*) FROM github_pull_requests WHERE repository = :repository AND state = 'open'
54
+ """)
55
+ BRANCH_HEAD = text("""
56
+ SELECT * FROM github_pull_requests
57
+ WHERE repository = :repository AND head_repository = :repository AND branch = :branch
58
+ AND state = 'open' AND complete
59
+ LIMIT 2
60
+ """)
61
+ BRANCH_HEADS = text("""
62
+ SELECT pr.branch, MIN(pr.number) AS number, MIN(pr.head_sha) AS head_sha
63
+ FROM github_pull_requests AS pr
64
+ JOIN json_each(:branches) AS requested ON pr.branch = requested.value
65
+ WHERE pr.repository = :repository AND pr.head_repository = :repository
66
+ AND pr.state = 'open' AND pr.complete
67
+ GROUP BY pr.branch HAVING COUNT(*) = 1
68
+ """)
69
+ PENDING_CHECKLIST_HEADS = text("""
70
+ SELECT checklist.lane, checklist.pr, checklist.head_sha
71
+ FROM json_each(:ready_lanes) AS requested
72
+ JOIN lane_checklists AS checklist ON checklist.lane = requested.value
73
+ JOIN github_pull_requests AS pr
74
+ ON pr.repository = checklist.repository AND pr.number = checklist.pr
75
+ AND pr.head_repository = checklist.repository AND pr.branch = checklist.branch
76
+ AND pr.head_sha = checklist.head_sha
77
+ WHERE checklist.repository = :repository AND checklist.state = 'pending'
78
+ AND pr.state = 'open' AND pr.complete
79
+ """)
80
+ RETRY = text("""
81
+ SELECT until, next_backoff FROM github_fetch_retries
82
+ WHERE repository = :repository AND resource = :resource
83
+ """)
84
+ SAVE_RETRY = text("""
85
+ INSERT INTO github_fetch_retries (repository, resource, until, next_backoff)
86
+ VALUES (:repository, :resource, :until, :next_backoff)
87
+ ON CONFLICT (repository, resource) DO UPDATE SET until = excluded.until,
88
+ next_backoff = excluded.next_backoff
89
+ """)
90
+ CLEAR_RETRY = text("""
91
+ DELETE FROM github_fetch_retries WHERE repository = :repository AND resource = :resource
92
+ """)
93
+
94
+
95
+ async def pull_request(
96
+ connection: AsyncConnection, repository: str, number: int
97
+ ) -> PullRequest | None:
98
+ row = (await connection.execute(PULL, {"repository": repository, "number": number})).first()
99
+ if row is None:
100
+ return None
101
+ return pull_from_row(row)
102
+
103
+
104
+ def pull_from_row(row: Row[Any]) -> PullRequest:
105
+ return PullRequest(
106
+ row.repository,
107
+ row.number,
108
+ row.branch,
109
+ row.head_sha,
110
+ row.head_repository,
111
+ row.state,
112
+ row.updated_at,
113
+ row.as_of,
114
+ bool(row.complete),
115
+ row.version,
116
+ None if row.draft is None else bool(row.draft),
117
+ row.merge_commit_sha,
118
+ )
119
+
120
+
121
+ async def open_branch_pull(
122
+ connection: AsyncConnection, repository: str, branch: str
123
+ ) -> PullRequest | None:
124
+ rows = (
125
+ await connection.execute(BRANCH_HEAD, {"repository": repository, "branch": branch})
126
+ ).all()
127
+ return pull_from_row(rows[0]) if len(rows) == 1 else None
128
+
129
+
130
+ async def project_lane_heads(
131
+ connection: AsyncConnection, repository: str, lanes: list[Lane]
132
+ ) -> list[Lane]:
133
+ if not lanes:
134
+ return []
135
+ branches = json.dumps(sorted({lane.branch for lane in lanes}))
136
+ rows = await connection.execute(BRANCH_HEADS, {"repository": repository, "branches": branches})
137
+ matches: dict[str, tuple[int | None, str | None]] = {
138
+ row.branch: (row.number, row.head_sha) for row in rows
139
+ }
140
+ pending: dict[str, tuple[int, str]] = {}
141
+ ready_lanes = [lane.id for lane in lanes if lane.state == "ready"]
142
+ if ready_lanes:
143
+ headers = await connection.execute(
144
+ PENDING_CHECKLIST_HEADS,
145
+ {"repository": repository, "ready_lanes": json.dumps(ready_lanes)},
146
+ )
147
+ pending = {row.lane: (row.pr, row.head_sha) for row in headers}
148
+ return [
149
+ with_projected_pr(lane, *pending.get(lane.id, matches.get(lane.branch, (None, None))))
150
+ for lane in lanes
151
+ ]
152
+
153
+
154
+ async def save_pull_request(connection: AsyncConnection, pull: PullRequest) -> None:
155
+ await connection.execute(SAVE_PULL, asdict(pull))
156
+
157
+
158
+ async def fetch_cursor(
159
+ connection: AsyncConnection, repository: str, resource: str
160
+ ) -> FetchCursor | None:
161
+ row = (
162
+ await connection.execute(CURSOR, {"repository": repository, "resource": resource})
163
+ ).first()
164
+ return FetchCursor(row.watermark, row.as_of, row.generation) if row is not None else None
165
+
166
+
167
+ async def save_fetch_cursor(
168
+ connection: AsyncConnection, repository: str, resource: str, cursor: FetchCursor
169
+ ) -> None:
170
+ await connection.execute(
171
+ SAVE_CURSOR, {"repository": repository, "resource": resource, **asdict(cursor)}
172
+ )
173
+
174
+
175
+ async def fetch_retry(
176
+ connection: AsyncConnection, repository: str, resource: str
177
+ ) -> FetchRetry | None:
178
+ row = (
179
+ await connection.execute(RETRY, {"repository": repository, "resource": resource})
180
+ ).first()
181
+ return FetchRetry(row.until, row.next_backoff) if row is not None else None
182
+
183
+
184
+ async def save_fetch_retry(
185
+ connection: AsyncConnection, repository: str, resource: str, retry: FetchRetry | None
186
+ ) -> None:
187
+ keys = {"repository": repository, "resource": resource}
188
+ if retry is None:
189
+ await connection.execute(CLEAR_RETRY, keys)
190
+ else:
191
+ await connection.execute(SAVE_RETRY, {**keys, **asdict(retry)})
192
+
193
+
194
+ async def summary(connection: AsyncConnection, repository: str) -> GitHubSummary:
195
+ opened = (await connection.execute(OPEN_COUNT, {"repository": repository})).scalar_one()
196
+ cursor = await fetch_cursor(connection, repository, PULL_REQUESTS)
197
+ return GitHubSummary(int(opened), cursor.as_of if cursor is not None else None)
198
+
199
+
200
+ RESOURCE = text("""
201
+ SELECT * FROM github_resources
202
+ WHERE repository = :repository AND resource = :resource AND scope = :scope
203
+ """)
204
+ SAVE_RESOURCE = text("""
205
+ INSERT INTO github_resources
206
+ (repository, resource, scope, records, attributes, complete, generation, as_of)
207
+ VALUES
208
+ (:repository, :resource, :scope, :records, :attributes, :complete, :generation, :as_of)
209
+ ON CONFLICT (repository, resource, scope) DO UPDATE SET records = excluded.records,
210
+ attributes = excluded.attributes, complete = excluded.complete,
211
+ generation = excluded.generation, as_of = excluded.as_of
212
+ """)
213
+ _DETAIL_TARGETS = """
214
+ SELECT pr.* FROM github_pull_requests AS pr
215
+ LEFT JOIN github_fetch_cursors AS cursor
216
+ ON cursor.repository = pr.repository AND cursor.resource = :prefix || pr.number
217
+ WHERE pr.repository = :repository AND pr.complete
218
+ """
219
+ _DETAIL_ORDER = """
220
+ ORDER BY COALESCE(cursor.as_of, ''), COALESCE(cursor.generation, 0), pr.number
221
+ LIMIT :limit
222
+ """
223
+ ACTIVE_DETAIL_TARGETS = text(_DETAIL_TARGETS + "AND pr.state = 'open'" + _DETAIL_ORDER)
224
+ TERMINAL_DETAIL_TARGETS = text(
225
+ _DETAIL_TARGETS
226
+ + """
227
+ AND pr.state IN ('closed', 'merged')
228
+ AND (cursor.watermark IS NULL OR cursor.watermark != (pr.updated_at || ':' || pr.version))
229
+ """
230
+ + _DETAIL_ORDER
231
+ )
232
+ DETAIL_CAPACITY_EXCEEDED = text("""
233
+ SELECT 1 FROM github_pull_requests
234
+ WHERE repository = :repository AND state = 'open' AND complete
235
+ LIMIT 1 OFFSET :budget
236
+ """)
237
+ PENDING_MERGE_SHAS = text("""
238
+ SELECT pr.* FROM github_pull_requests AS pr
239
+ LEFT JOIN github_fetch_cursors AS attempt
240
+ ON attempt.repository = pr.repository AND attempt.resource = :prefix || pr.number
241
+ WHERE pr.repository = :repository AND pr.complete AND pr.state = 'merged'
242
+ AND pr.merge_commit_sha IS NULL
243
+ ORDER BY MIN(COALESCE(attempt.as_of, pr.updated_at), :as_of),
244
+ COALESCE(attempt.generation, 0), pr.number
245
+ LIMIT :limit
246
+ """)
247
+ OPEN_PULLS = text(
248
+ "SELECT * FROM github_pull_requests WHERE repository = :repository "
249
+ "AND complete AND state = 'open' ORDER BY number"
250
+ )
251
+
252
+
253
+ async def open_pulls(connection: AsyncConnection, repository: str) -> tuple[PullRequest, ...]:
254
+ rows = await connection.execute(OPEN_PULLS, {"repository": repository})
255
+ return tuple(pull_from_row(row) for row in rows)
256
+
257
+
258
+ async def detail_capacity_exceeded(connection: AsyncConnection, repository: str) -> bool:
259
+ rows = await connection.execute(
260
+ DETAIL_CAPACITY_EXCEEDED, {"repository": repository, "budget": ACTIVE_PULL_DETAIL_BUDGET}
261
+ )
262
+ return rows.first() is not None
263
+
264
+
265
+ async def github_resource(
266
+ connection: AsyncConnection, repository: str, resource: str, scope: str
267
+ ) -> GitHubResource | None:
268
+ row = (
269
+ await connection.execute(
270
+ RESOURCE, {"repository": repository, "resource": resource, "scope": scope}
271
+ )
272
+ ).first()
273
+ if row is None:
274
+ return None
275
+ return resource_from_row(row)
276
+
277
+
278
+ def resource_from_row(row: Row[Any]) -> GitHubResource:
279
+ return GitHubResource(
280
+ tuple(GitHubRecord(**record) for record in json.loads(row.records)),
281
+ bool(row.complete),
282
+ json.loads(row.attributes),
283
+ row.generation,
284
+ row.as_of,
285
+ )
286
+
287
+
288
+ async def save_github_resource(
289
+ connection: AsyncConnection, repository: str, resource: str, scope: str, result: GitHubResource
290
+ ) -> None:
291
+ await connection.execute(
292
+ SAVE_RESOURCE,
293
+ {
294
+ "repository": repository,
295
+ "resource": resource,
296
+ "scope": scope,
297
+ "records": json.dumps([asdict(record) for record in result.records]),
298
+ "attributes": json.dumps(result.attributes),
299
+ "complete": result.complete,
300
+ "generation": result.generation,
301
+ "as_of": result.as_of,
302
+ },
303
+ )
304
+
305
+
306
+ async def github_pull_targets(
307
+ connection: AsyncConnection, repository: str
308
+ ) -> tuple[PullRequest, ...]:
309
+ keys = {"repository": repository, "prefix": PULL_DETAIL_ATTEMPT_PREFIX}
310
+ active = await connection.execute(
311
+ ACTIVE_DETAIL_TARGETS, {**keys, "limit": ACTIVE_PULL_DETAIL_BUDGET}
312
+ )
313
+ terminal = await connection.execute(
314
+ TERMINAL_DETAIL_TARGETS, {**keys, "limit": TERMINAL_PULL_DETAIL_BUDGET}
315
+ )
316
+ return tuple(pull_from_row(row) for rows in (active, terminal) for row in rows)
317
+
318
+
319
+ async def github_pending_merge_shas(
320
+ connection: AsyncConnection, repository: str, as_of: str, limit: int
321
+ ) -> tuple[PullRequest, ...]:
322
+ rows = await connection.execute(
323
+ PENDING_MERGE_SHAS,
324
+ {
325
+ "repository": repository,
326
+ "prefix": MERGE_SHA_ATTEMPT_PREFIX,
327
+ "as_of": as_of,
328
+ "limit": limit,
329
+ },
330
+ )
331
+ return tuple(pull_from_row(row) for row in rows)
@@ -0,0 +1,57 @@
1
+ """Persistence for an operator's named goal text."""
2
+
3
+ from sqlalchemy import text
4
+ from sqlalchemy.ext.asyncio import AsyncConnection
5
+
6
+ from plotroom.core.goal_projection import StoredGoal
7
+
8
+ _SAVE = text("""
9
+ INSERT INTO operator_goals (name, text, updated_at, uses_blockers, uses_lanes, uses_decisions)
10
+ VALUES (:name, :text, :updated_at, :uses_blockers, :uses_lanes, :uses_decisions)
11
+ ON CONFLICT (name) DO UPDATE SET text = excluded.text, updated_at = excluded.updated_at,
12
+ uses_blockers = excluded.uses_blockers, uses_lanes = excluded.uses_lanes,
13
+ uses_decisions = excluded.uses_decisions
14
+ """)
15
+ _LIST = text("""
16
+ SELECT name, text, updated_at, uses_blockers, uses_lanes, uses_decisions FROM operator_goals
17
+ WHERE :name IS NULL OR name = :name
18
+ ORDER BY name
19
+ """)
20
+
21
+
22
+ async def save_goal(connection: AsyncConnection, goal: StoredGoal) -> None:
23
+ await connection.execute(
24
+ _SAVE,
25
+ {
26
+ "name": goal.name,
27
+ "text": goal.text,
28
+ "updated_at": goal.updated_at,
29
+ "uses_blockers": goal.uses_blockers,
30
+ "uses_lanes": goal.uses_lanes,
31
+ "uses_decisions": goal.uses_decisions,
32
+ },
33
+ )
34
+
35
+
36
+ async def list_goals(connection: AsyncConnection, name: str | None) -> list[StoredGoal]:
37
+ return [
38
+ StoredGoal(
39
+ row.name,
40
+ row.text,
41
+ row.updated_at,
42
+ bool(row.uses_blockers),
43
+ bool(row.uses_lanes),
44
+ bool(row.uses_decisions),
45
+ )
46
+ for row in await connection.execute(_LIST, {"name": name})
47
+ ]
48
+
49
+
50
+ async def goals_use_blockers(connection: AsyncConnection) -> bool:
51
+ return bool(
52
+ (
53
+ await connection.execute(
54
+ text("SELECT EXISTS(SELECT 1 FROM operator_goals WHERE uses_blockers)")
55
+ )
56
+ ).scalar_one()
57
+ )
@@ -0,0 +1,60 @@
1
+ """Store decisions in the project's local SQLite database."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from sqlalchemy import Row, text
9
+ from sqlalchemy.ext.asyncio import AsyncConnection
10
+
11
+ from plotroom.core.human_queue import Decision
12
+
13
+ _INSERT_DECISION = text("""
14
+ INSERT INTO decisions (id, who, exact_words, where_ref, governs, settles, created_at)
15
+ VALUES (:id, :who, :exact_words, :where_ref, :governs, :settles, :created_at)
16
+ """)
17
+ _LIST_DECISIONS = text("""
18
+ SELECT * FROM decisions AS decision
19
+ WHERE :governs IS NULL OR EXISTS (
20
+ SELECT 1 FROM json_each(decision.governs) AS ticket WHERE ticket.value = :governs
21
+ )
22
+ ORDER BY decision.rowid
23
+ """)
24
+
25
+
26
+ async def insert_decision(connection: AsyncConnection, decision: Decision) -> None:
27
+ await connection.execute(
28
+ _INSERT_DECISION,
29
+ {
30
+ "id": decision.decision_id,
31
+ "who": decision.who,
32
+ "exact_words": decision.exact_words,
33
+ "where_ref": json.dumps(decision.where_ref),
34
+ "governs": json.dumps(decision.governs),
35
+ "settles": json.dumps(decision.settles),
36
+ "created_at": decision.created_at,
37
+ },
38
+ )
39
+
40
+
41
+ async def list_decisions(connection: AsyncConnection, governs: str | None) -> list[Decision]:
42
+ rows = await connection.execute(_LIST_DECISIONS, {"governs": governs})
43
+ return [decision_from_row(row) for row in rows]
44
+
45
+
46
+ def decision_from_row(row: Row[Any]) -> Decision:
47
+ return Decision(
48
+ row.id,
49
+ row.who,
50
+ row.exact_words,
51
+ json.loads(row.where_ref),
52
+ json.loads(row.governs),
53
+ json.loads(row.settles),
54
+ row.created_at,
55
+ )
56
+
57
+
58
+ async def decision_refs(connection: AsyncConnection) -> list[tuple[str, list[str]]]:
59
+ rows = await connection.execute(text("SELECT id, governs FROM decisions"))
60
+ return [(row.id, json.loads(row.governs)) for row in rows]
@@ -0,0 +1,129 @@
1
+ """Next item reads and writes in the project transaction."""
2
+
3
+ import json
4
+ from dataclasses import asdict
5
+ from typing import Any
6
+
7
+ from sqlalchemy import Row, bindparam, text
8
+ from sqlalchemy.ext.asyncio import AsyncConnection
9
+
10
+ from plotroom.core.claims import OVERLAP_KINDS
11
+ from plotroom.core.next_items import Item
12
+
13
+ _ACTIVE_SUBJECTS = text(
14
+ "SELECT subject_ref FROM next_items WHERE kind = :kind AND state != 'closed'"
15
+ )
16
+ _BY_ID = text("SELECT * FROM next_items WHERE id = :id")
17
+ _ACTIVE = text("SELECT * FROM next_items WHERE dedup_key = :key AND state != 'closed'")
18
+ _VISIBLE_OPEN = (
19
+ "SELECT * FROM next_items WHERE state = 'open' AND (:role = 'orchestrator' OR role = :role)"
20
+ )
21
+ _ORDER = "ORDER BY rank_class, opened_seq LIMIT :limit OFFSET :offset"
22
+ _OPEN = text(f"{_VISIBLE_OPEN} {_ORDER}")
23
+ _OVERLAPS = text(
24
+ "SELECT * FROM next_items WHERE state = 'open' AND (:role = 'orchestrator' OR role = :role) "
25
+ "AND kind IN :kinds "
26
+ "AND EXISTS (SELECT 1 FROM json_each(context, :path) WHERE value = :subject) "
27
+ "ORDER BY rank_class, opened_seq LIMIT :limit OFFSET :offset"
28
+ ).bindparams(bindparam("kinds", expanding=True))
29
+ _OPEN_BY_ID = text(
30
+ "SELECT * FROM next_items WHERE id = :id AND state = 'open' "
31
+ "AND (:role = 'orchestrator' OR role = :role)"
32
+ )
33
+ _SAVE = text(
34
+ "INSERT INTO next_items "
35
+ "(id, kind, subject_ref, dedup_key, role, rank_class, state, opened_seq, closed_seq, seq, "
36
+ "context, suggested_actions) VALUES "
37
+ "(:id, :kind, :subject_ref, :dedup_key, :role, :rank_class, :state, :opened_seq, "
38
+ ":closed_seq, :seq, :context, :suggested_actions) ON CONFLICT(id) DO UPDATE SET "
39
+ "state=excluded.state, closed_seq=excluded.closed_seq, seq=excluded.seq, "
40
+ "context=excluded.context"
41
+ )
42
+
43
+
44
+ _INSERT_CHANGE = text("INSERT INTO item_changes (seq, role, item) VALUES (:seq, :role, :item)")
45
+ _NEXT_CHANGE = text("SELECT item FROM item_changes WHERE seq > :cursor ORDER BY seq LIMIT 1")
46
+ _NEXT_ROLE_CHANGE = text(
47
+ "SELECT item FROM item_changes WHERE role = :role AND seq > :cursor ORDER BY seq LIMIT 1"
48
+ )
49
+
50
+
51
+ async def first_change(
52
+ connection: AsyncConnection, role: str, cursor: int
53
+ ) -> dict[str, Any] | None:
54
+ query = _NEXT_CHANGE if role == "orchestrator" else _NEXT_ROLE_CHANGE
55
+ value = (await connection.execute(query, {"role": role, "cursor": cursor})).scalar_one_or_none()
56
+ item: dict[str, Any] | None = None if value is None else json.loads(value)
57
+ return item
58
+
59
+
60
+ def _item(row: Row[Any]) -> Item:
61
+ fields = dict(row._mapping) # pyright: ignore[reportPrivateUsage]
62
+ fields["context"] = json.loads(row.context)
63
+ fields["suggested_actions"] = tuple(json.loads(row.suggested_actions))
64
+ return Item(**fields)
65
+
66
+
67
+ async def active_item_subjects(connection: AsyncConnection, kind: str) -> set[str]:
68
+ return {
69
+ str(row.subject_ref) for row in await connection.execute(_ACTIVE_SUBJECTS, {"kind": kind})
70
+ }
71
+
72
+
73
+ async def find_item(connection: AsyncConnection, item_id: str) -> Item | None:
74
+ row = (await connection.execute(_BY_ID, {"id": item_id})).first()
75
+ return None if row is None else _item(row)
76
+
77
+
78
+ async def active_item(connection: AsyncConnection, key: str) -> Item | None:
79
+ row = (await connection.execute(_ACTIVE, {"key": key})).first()
80
+ return None if row is None else _item(row)
81
+
82
+
83
+ async def open_items(
84
+ connection: AsyncConnection,
85
+ role: str,
86
+ *,
87
+ offset: int = 0,
88
+ limit: int = -1,
89
+ ) -> list[Item]:
90
+ rows = await connection.execute(_OPEN, {"role": role, "offset": offset, "limit": limit})
91
+ return [_item(row) for row in rows]
92
+
93
+
94
+ async def open_item(connection: AsyncConnection, role: str, item_id: str) -> Item | None:
95
+ row = (await connection.execute(_OPEN_BY_ID, {"role": role, "id": item_id})).first()
96
+ return None if row is None else _item(row)
97
+
98
+
99
+ async def open_overlaps(
100
+ connection: AsyncConnection,
101
+ role: str,
102
+ lane: str | None,
103
+ pr: int | None,
104
+ offset: int,
105
+ limit: int,
106
+ ) -> list[Item]:
107
+ rows = await connection.execute(
108
+ _OVERLAPS,
109
+ {
110
+ "role": role,
111
+ "kinds": OVERLAP_KINDS,
112
+ "path": "$.lanes" if lane is not None else "$.prs",
113
+ "subject": lane if lane is not None else pr,
114
+ "offset": offset,
115
+ "limit": limit,
116
+ },
117
+ )
118
+ return [_item(row) for row in rows]
119
+
120
+
121
+ async def save_item(connection: AsyncConnection, item: Item) -> None:
122
+ fields = asdict(item)
123
+ serialized = json.dumps(fields, allow_nan=False)
124
+ fields["context"] = json.dumps(item.context, allow_nan=False)
125
+ fields["suggested_actions"] = json.dumps(item.suggested_actions)
126
+ await connection.execute(_SAVE, fields)
127
+ await connection.execute(
128
+ _INSERT_CHANGE, {"seq": item.seq, "role": item.role, "item": serialized}
129
+ )
@@ -0,0 +1,85 @@
1
+ """Reads and writes for the lane board."""
2
+
3
+ import json
4
+ from dataclasses import asdict
5
+ from typing import Any, cast
6
+
7
+ from sqlalchemy import Row, text
8
+ from sqlalchemy.ext.asyncio import AsyncConnection
9
+
10
+ from plotroom.core.lanes import Lane
11
+
12
+ _FIND = text("SELECT * FROM lanes WHERE id = :id")
13
+ _WORKER = text("SELECT * FROM lanes WHERE worker = :worker AND state != 'archived'")
14
+ _SAVE = text(
15
+ "INSERT INTO lanes (id, worker, work_items, branch, state, waiting_on, pr, head_sha, "
16
+ "branch_pattern, imported_channel, imported_trigger_id) "
17
+ "VALUES (:id, :worker, :work_items, :branch, :state, :waiting_on, :pr, "
18
+ ":head_sha, :branch_pattern, :imported_channel, :imported_trigger_id) "
19
+ "ON CONFLICT(id) DO UPDATE SET state=excluded.state, waiting_on=excluded.waiting_on, "
20
+ "pr=excluded.pr, head_sha=excluded.head_sha"
21
+ )
22
+ _BOARD = text(
23
+ "SELECT * FROM lanes WHERE state != 'archived' "
24
+ "AND (:role = 'orchestrator' OR :role = 'clerk' OR :role = 'worker:' || worker) ORDER BY id"
25
+ )
26
+ _COUNTS = text(
27
+ "SELECT state, count(*) AS total FROM lanes "
28
+ "WHERE (:role = 'orchestrator' OR :role = 'clerk' OR :role = 'worker:' || worker) "
29
+ "GROUP BY state ORDER BY state"
30
+ )
31
+
32
+
33
+ def _lane(row: Row[Any]) -> Lane:
34
+ fields = dict(row._mapping) # pyright: ignore[reportPrivateUsage]
35
+ items: Any = json.loads(row.work_items)
36
+ if not isinstance(items, list) or not all(
37
+ isinstance(item, str) for item in cast("list[Any]", items)
38
+ ):
39
+ raise ValueError("invalid work items in stored lane")
40
+ fields["work_items"] = tuple(cast("list[str]", items))
41
+ return Lane(**fields)
42
+
43
+
44
+ async def find_lane(connection: AsyncConnection, lane_id: str) -> Lane | None:
45
+ row = (await connection.execute(_FIND, {"id": lane_id})).first()
46
+ return None if row is None else _lane(row)
47
+
48
+
49
+ async def worker_lane(connection: AsyncConnection, worker: str) -> Lane | None:
50
+ row = (await connection.execute(_WORKER, {"worker": worker})).first()
51
+ return None if row is None else _lane(row)
52
+
53
+
54
+ async def branch_lane(connection: AsyncConnection, branch: str) -> Lane | None:
55
+ rows = (
56
+ await connection.execute(
57
+ text("SELECT * FROM lanes WHERE branch = :branch AND state != 'archived' LIMIT 2"),
58
+ {"branch": branch},
59
+ )
60
+ ).all()
61
+ return _lane(rows[0]) if len(rows) == 1 else None
62
+
63
+
64
+ async def branch_lanes(connection: AsyncConnection, branch: str) -> list[Lane]:
65
+ rows = await connection.execute(
66
+ text("SELECT * FROM lanes WHERE branch = :branch AND state != 'archived' ORDER BY id"),
67
+ {"branch": branch},
68
+ )
69
+ return [_lane(row) for row in rows]
70
+
71
+
72
+ async def save_lane(connection: AsyncConnection, lane: Lane) -> None:
73
+ fields = asdict(lane)
74
+ fields["work_items"] = json.dumps(lane.work_items)
75
+ await connection.execute(_SAVE, fields)
76
+
77
+
78
+ async def board_lanes(connection: AsyncConnection, role: str) -> list[Lane]:
79
+ return [_lane(row) for row in await connection.execute(_BOARD, {"role": role})]
80
+
81
+
82
+ async def lane_counts(connection: AsyncConnection, role: str) -> dict[str, int]:
83
+ return {
84
+ str(row.state): int(row.total) for row in await connection.execute(_COUNTS, {"role": role})
85
+ }