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,151 @@
1
+ """Read cumulative USD spend from each run's dedicated OpenRouter inference key."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import re
10
+ from collections.abc import Awaitable, Callable, Mapping
11
+ from dataclasses import dataclass, field
12
+ from decimal import Decimal, InvalidOperation
13
+ from hmac import compare_digest
14
+ from pathlib import Path
15
+ from typing import Any, cast
16
+
17
+ import httpx
18
+
19
+ from plotroom._secret_file import read_secret_file
20
+ from plotroom.core.budgets import OPENROUTER_PROVIDER
21
+ from plotroom.ports.clock import Clock
22
+ from plotroom.ports.usage_meter import UsageObservation
23
+
24
+ log = logging.getLogger("plotroom.openrouter")
25
+ _KEY_URL = "https://openrouter.ai/api/v1/key"
26
+ _KEY = re.compile(r"sk-or-v1-[a-zA-Z0-9-]+")
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class OpenRouterRun:
31
+ key_file: Path = field(repr=False)
32
+ key_sha256: str = field(repr=False)
33
+
34
+ @property
35
+ def reservation(self) -> str:
36
+ # Preserve the binding across restart without storing the mounted key or its pin.
37
+ return hashlib.sha256(
38
+ b"plotroom.openrouter.reservation:" + bytes.fromhex(self.key_sha256)
39
+ ).hexdigest()
40
+
41
+
42
+ def _unique_fields(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
43
+ fields = dict(pairs)
44
+ if len(fields) != len(pairs):
45
+ raise ValueError("duplicate current-key fields")
46
+ return fields
47
+
48
+
49
+ def _money(value: object) -> Decimal:
50
+ if type(value) not in (int, Decimal):
51
+ raise ValueError("expected a numeric USD amount")
52
+ amount = Decimal(cast("int | Decimal", value))
53
+ if not amount.is_finite() or amount < 0:
54
+ raise ValueError("expected a finite nonnegative USD amount")
55
+ return amount
56
+
57
+
58
+ def _usage(response: httpx.Response, cap_usd: float) -> Decimal:
59
+ body: Any = json.loads(response.content, parse_float=Decimal, object_pairs_hook=_unique_fields)
60
+ if not isinstance(body, dict):
61
+ raise ValueError("expected a current-key response")
62
+ data: Any = cast("dict[str, Any]", body).get("data")
63
+ if not isinstance(data, dict):
64
+ raise ValueError("expected current-key data")
65
+ fields = cast("dict[str, Any]", data)
66
+ limit = _money(fields.get("limit"))
67
+ if (
68
+ not 0 < limit <= Decimal(str(cap_usd))
69
+ or "limit_reset" not in fields
70
+ or fields["limit_reset"] is not None
71
+ or fields.get("is_management_key") is not False
72
+ or fields.get("is_provisioning_key") is not False
73
+ or _money(fields.get("byok_usage")) != 0
74
+ or _money(fields.get("limit_remaining")) > limit
75
+ ):
76
+ raise ValueError("key does not match the capped run contract")
77
+ return _money(fields.get("usage"))
78
+
79
+
80
+ class OpenRouterUsageMeter:
81
+ def __init__(
82
+ self,
83
+ runs: Mapping[str, OpenRouterRun],
84
+ budgets: Callable[[], Awaitable[list[tuple[str, float, str]]]],
85
+ clock: Clock,
86
+ *,
87
+ timeout: float = 5,
88
+ transport: httpx.AsyncBaseTransport | None = None,
89
+ ) -> None:
90
+ self._runs = dict(runs)
91
+ self._budgets = budgets
92
+ self._clock = clock
93
+ self._timeout = timeout
94
+ self._transport = transport
95
+
96
+ async def verify_cap(self, run: str, cap_usd: float) -> bool:
97
+ binding = self._runs.get(run)
98
+ if binding is None:
99
+ return False
100
+ async with self._client() as client:
101
+ return await self._observe(client, run, cap_usd, binding.reservation) is not None
102
+
103
+ def _client(self) -> httpx.AsyncClient:
104
+ return httpx.AsyncClient(
105
+ transport=self._transport,
106
+ timeout=self._timeout,
107
+ follow_redirects=False,
108
+ trust_env=False,
109
+ )
110
+
111
+ async def observations(self) -> tuple[UsageObservation, ...]:
112
+ targets = await self._budgets()
113
+ if not targets:
114
+ return ()
115
+ async with self._client() as client:
116
+ readings = await asyncio.gather(
117
+ *(self._observe(client, run, cap, reservation) for run, cap, reservation in targets)
118
+ )
119
+ return tuple(reading for reading in readings if reading is not None)
120
+
121
+ async def _observe(
122
+ self, client: httpx.AsyncClient, run: str, cap_usd: float, reservation: str
123
+ ) -> UsageObservation | None:
124
+ binding = self._runs.get(run)
125
+ if binding is None or not compare_digest(binding.reservation, reservation):
126
+ log.warning("OpenRouter run binding does not match its recorded reservation")
127
+ return None
128
+ try:
129
+ async with asyncio.timeout(self._timeout):
130
+ key = await read_secret_file(binding.key_file)
131
+ if _KEY.fullmatch(key) is None or not compare_digest(
132
+ hashlib.sha256(key.encode("ascii")).hexdigest(), binding.key_sha256
133
+ ):
134
+ raise ValueError("mounted key differs from its run binding")
135
+ response = await client.get(_KEY_URL, headers={"Authorization": f"Bearer {key}"})
136
+ response.raise_for_status()
137
+ amount = _usage(response, cap_usd)
138
+ spend = float(amount)
139
+ if spend == 0 and amount:
140
+ raise ValueError("USD amount is too small for the budget")
141
+ return UsageObservation(OPENROUTER_PROVIDER, run, spend, self._clock.now())
142
+ except (
143
+ OSError,
144
+ ValueError,
145
+ OverflowError,
146
+ InvalidOperation,
147
+ RecursionError,
148
+ httpx.HTTPError,
149
+ ):
150
+ log.warning("OpenRouter usage observation unavailable")
151
+ return None
@@ -0,0 +1,6 @@
1
+ """SQLite store adapter: one project file, Alembic migrations."""
2
+
3
+ from plotroom.adapters.store_sqlite.migrate import head_revision, script_heads, upgrade_to_head
4
+ from plotroom.adapters.store_sqlite.store import SqliteStore
5
+
6
+ __all__ = ["SqliteStore", "head_revision", "script_heads", "upgrade_to_head"]
@@ -0,0 +1,148 @@
1
+ """Persistence for the action runner's queue."""
2
+
3
+ import json
4
+
5
+ from sqlalchemy import text
6
+ from sqlalchemy.ext.asyncio import AsyncConnection
7
+
8
+ from plotroom.core.actions import (
9
+ BRANCH_UPDATE,
10
+ CONTROLLER_MERGE,
11
+ SWITCHBOARD_SEND,
12
+ Action,
13
+ QueuedAction,
14
+ )
15
+ from plotroom.core.trigger_actions import SEND
16
+
17
+ _INSERT = text(
18
+ "INSERT INTO actions (action_key, kind, cause_id, payload, attempts, state) "
19
+ "VALUES (:key, :kind, :cause, :payload, 0, 'pending') "
20
+ "ON CONFLICT(action_key) DO NOTHING"
21
+ )
22
+ _UPDATE = text(
23
+ "UPDATE actions SET attempts = :attempts, state = :state, payload = :payload "
24
+ "WHERE action_key = :key"
25
+ )
26
+ _BRIDGE_NEXT = text(
27
+ "SELECT * FROM actions WHERE state = 'pending' AND (kind = :switchboard OR "
28
+ "(kind = :send AND json_extract(payload, '$.worker') "
29
+ "IN (SELECT value FROM json_each(:workers))))"
30
+ " AND ((:lease IS NULL AND "
31
+ "coalesce(json_extract(payload, '$._bridge_lease.expires'), '') <= :now)"
32
+ " OR (json_extract(payload, '$._bridge_lease.id') = :lease"
33
+ " AND json_extract(payload, '$._bridge_lease.expires') > :now)) ORDER BY rowid LIMIT 1"
34
+ )
35
+ _BRIDGE_EXPIRY = text(
36
+ "SELECT min(json_extract(payload, '$._bridge_lease.expires')) FROM actions "
37
+ "WHERE state = 'pending' AND (kind = :switchboard OR "
38
+ "(kind = :send AND json_extract(payload, '$.worker') "
39
+ "IN (SELECT value FROM json_each(:workers))))"
40
+ " AND json_extract(payload, '$._bridge_lease.expires') > :now"
41
+ )
42
+ _PENDING = text(
43
+ "SELECT rowid AS queue_position, * FROM actions WHERE state = 'pending' AND rowid > :after "
44
+ "AND (:skip_branch_updates = 0 OR kind != :branch_update) "
45
+ "AND (:skip_controller_merges = 0 OR kind != :controller_merge) "
46
+ "AND (:skip_bridge = 0 OR (kind != :switchboard AND (kind != :send OR "
47
+ "NOT EXISTS (SELECT 1 FROM json_each(:workers) "
48
+ "WHERE value = json_extract(payload, '$.worker'))))) "
49
+ "ORDER BY rowid LIMIT :limit"
50
+ )
51
+
52
+
53
+ async def insert_action(connection: AsyncConnection, action: Action) -> None:
54
+ await connection.execute(
55
+ _INSERT,
56
+ {
57
+ "key": action.key,
58
+ "kind": action.kind,
59
+ "cause": action.cause_id,
60
+ "payload": json.dumps(action.payload, allow_nan=False),
61
+ },
62
+ )
63
+
64
+
65
+ async def update_action(connection: AsyncConnection, action: Action) -> None:
66
+ await connection.execute(
67
+ _UPDATE,
68
+ {
69
+ "key": action.key,
70
+ "attempts": action.attempts,
71
+ "state": action.state,
72
+ "payload": json.dumps(action.payload, allow_nan=False),
73
+ },
74
+ )
75
+
76
+
77
+ async def pending_actions(
78
+ connection: AsyncConnection,
79
+ *,
80
+ after: int,
81
+ limit: int,
82
+ skip_branch_updates: bool,
83
+ skip_controller_merges: bool = False,
84
+ skip_bridge_workers: tuple[str, ...] | None = None,
85
+ ) -> tuple[QueuedAction, ...]:
86
+ rows = await connection.execute(
87
+ _PENDING,
88
+ {
89
+ "after": after,
90
+ "limit": limit,
91
+ "skip_branch_updates": skip_branch_updates,
92
+ "branch_update": BRANCH_UPDATE,
93
+ "controller_merge": CONTROLLER_MERGE,
94
+ "skip_controller_merges": skip_controller_merges,
95
+ "skip_bridge": skip_bridge_workers is not None,
96
+ "workers": json.dumps(skip_bridge_workers or ()),
97
+ "switchboard": SWITCHBOARD_SEND,
98
+ "send": SEND,
99
+ },
100
+ )
101
+ return tuple(
102
+ QueuedAction(
103
+ row.queue_position,
104
+ Action(
105
+ row.action_key,
106
+ row.kind,
107
+ row.cause_id,
108
+ json.loads(row.payload),
109
+ row.attempts,
110
+ row.state,
111
+ ),
112
+ )
113
+ for row in rows
114
+ )
115
+
116
+
117
+ def _bridge_parameters(workers: tuple[str, ...], now: str) -> dict[str, str]:
118
+ return {
119
+ "workers": json.dumps(workers),
120
+ "now": now,
121
+ "send": SEND,
122
+ "switchboard": SWITCHBOARD_SEND,
123
+ }
124
+
125
+
126
+ async def bridge_action(
127
+ connection: AsyncConnection,
128
+ workers: tuple[str, ...],
129
+ now: str,
130
+ act_id: str | None,
131
+ ) -> Action | None:
132
+ row = (
133
+ await connection.execute(
134
+ _BRIDGE_NEXT,
135
+ {**_bridge_parameters(workers, now), "lease": act_id},
136
+ )
137
+ ).first()
138
+ if row is None:
139
+ return None
140
+ return Action(
141
+ row.action_key, row.kind, row.cause_id, json.loads(row.payload), row.attempts, row.state
142
+ )
143
+
144
+
145
+ async def bridge_expiry(
146
+ connection: AsyncConnection, workers: tuple[str, ...], now: str
147
+ ) -> str | None:
148
+ return (await connection.execute(_BRIDGE_EXPIRY, _bridge_parameters(workers, now))).scalar_one()
@@ -0,0 +1,153 @@
1
+ """Ask records and the comments needed to check them."""
2
+
3
+ import json
4
+ from typing import Any
5
+
6
+ from sqlalchemy import Row, text
7
+ from sqlalchemy.ext.asyncio import AsyncConnection
8
+
9
+ from plotroom.core.ask_checks import Ask, IssueComment, comment_time
10
+ from plotroom.core.github_projection import ASK_COMMENT_HISTORY
11
+
12
+ _ASK_FROM_COMMENT = text(
13
+ "SELECT * FROM human_asks WHERE repository = :repository AND comment_id = :comment_id"
14
+ )
15
+ _ASK_BY_ID = text("SELECT * FROM human_asks WHERE id = :id")
16
+ _SAVE_ASK = text("""
17
+ INSERT INTO human_asks
18
+ (id, repository, issue, text, options, comment_id, comment_created_at, created_at, settled_by)
19
+ VALUES
20
+ (:id, :repository, :issue, :text, :options, :comment_id, :comment_created_at, :created_at,
21
+ :settled_by)
22
+ ON CONFLICT (id) DO UPDATE SET text = excluded.text, options = excluded.options,
23
+ settled_by = excluded.settled_by
24
+ """)
25
+ _LIST_ASKS = text("""
26
+ SELECT ask.* FROM human_asks AS ask
27
+ WHERE NOT :stale_only OR EXISTS (
28
+ SELECT 1 FROM next_items AS item
29
+ WHERE item.subject_ref = ask.id AND item.kind = 'ask_stale' AND item.state != 'closed'
30
+ )
31
+ ORDER BY ask.created_at, ask.id
32
+ """)
33
+ _PENDING_ISSUES = text(
34
+ "SELECT DISTINCT issue FROM human_asks WHERE repository = :repository AND settled_by IS NULL"
35
+ )
36
+ _UNSETTLED = text("""
37
+ SELECT * FROM human_asks WHERE repository = :repository AND settled_by IS NULL ORDER BY id
38
+ """)
39
+ _ASK_COMMENTS = text("""
40
+ SELECT json_extract(records, '$[0].fields') AS fields
41
+ FROM github_resources
42
+ WHERE repository = :repository AND resource = 'issue_comments'
43
+ AND json_extract(records, '$[0].fields.number') IN (SELECT value FROM json_each(:issues))
44
+ """)
45
+
46
+
47
+ _ASK_HISTORIES = text("""
48
+ SELECT scope, attributes FROM github_resources
49
+ WHERE repository = :repository AND resource = :resource
50
+ AND scope IN (SELECT value FROM json_each(:scopes))
51
+ """)
52
+
53
+
54
+ def ask_from_row(row: Row[Any]) -> Ask:
55
+ return Ask(
56
+ ask_id=row.id,
57
+ repository=row.repository,
58
+ issue=row.issue,
59
+ text=row.text,
60
+ options=tuple(json.loads(row.options)),
61
+ comment_id=row.comment_id,
62
+ comment_created_at=row.comment_created_at,
63
+ created_at=row.created_at,
64
+ settled_by=row.settled_by,
65
+ )
66
+
67
+
68
+ async def ask_for_comment(
69
+ connection: AsyncConnection, repository: str, comment_id: int
70
+ ) -> Ask | None:
71
+ row = (
72
+ await connection.execute(
73
+ _ASK_FROM_COMMENT, {"repository": repository, "comment_id": comment_id}
74
+ )
75
+ ).first()
76
+ return None if row is None else ask_from_row(row)
77
+
78
+
79
+ async def find_ask(connection: AsyncConnection, ask_id: str) -> Ask | None:
80
+ row = (await connection.execute(_ASK_BY_ID, {"id": ask_id})).first()
81
+ return None if row is None else ask_from_row(row)
82
+
83
+
84
+ async def save_ask(connection: AsyncConnection, ask: Ask) -> None:
85
+ await connection.execute(
86
+ _SAVE_ASK,
87
+ {
88
+ "id": ask.ask_id,
89
+ "repository": ask.repository,
90
+ "issue": ask.issue,
91
+ "text": ask.text,
92
+ "options": json.dumps(ask.options),
93
+ "comment_id": ask.comment_id,
94
+ "comment_created_at": ask.comment_created_at,
95
+ "created_at": ask.created_at,
96
+ "settled_by": ask.settled_by,
97
+ },
98
+ )
99
+
100
+
101
+ async def list_asks(connection: AsyncConnection, stale_only: bool) -> list[Ask]:
102
+ return [
103
+ ask_from_row(row)
104
+ for row in await connection.execute(_LIST_ASKS, {"stale_only": stale_only})
105
+ ]
106
+
107
+
108
+ async def pending_ask_issues(connection: AsyncConnection, repository: str) -> set[int]:
109
+ rows = await connection.execute(_PENDING_ISSUES, {"repository": repository})
110
+ return {row.issue for row in rows}
111
+
112
+
113
+ async def unsettled_asks(connection: AsyncConnection, repository: str) -> list[Ask]:
114
+ return [
115
+ ask_from_row(row)
116
+ for row in await connection.execute(_UNSETTLED, {"repository": repository})
117
+ ]
118
+
119
+
120
+ async def ask_comments(
121
+ connection: AsyncConnection, repository: str, issues: set[int]
122
+ ) -> dict[int, list[IssueComment]]:
123
+ results: dict[int, list[IssueComment]] = {}
124
+ rows = await connection.execute(
125
+ _ASK_COMMENTS,
126
+ {"repository": repository, "issues": json.dumps(sorted(issues))},
127
+ )
128
+ for row in rows:
129
+ fields = json.loads(row.fields)
130
+ results.setdefault(fields["number"], []).append(
131
+ IssueComment(fields["id"], fields.get("author"), comment_time(fields["created_at"]))
132
+ )
133
+ return results
134
+
135
+
136
+ async def ask_comment_histories(
137
+ connection: AsyncConnection, repository: str, issues: set[int]
138
+ ) -> dict[int, tuple[str, frozenset[int]]]:
139
+ if not issues:
140
+ return {}
141
+ rows = await connection.execute(
142
+ _ASK_HISTORIES,
143
+ {
144
+ "repository": repository,
145
+ "resource": ASK_COMMENT_HISTORY,
146
+ "scopes": json.dumps([str(number) for number in sorted(issues)]),
147
+ },
148
+ )
149
+ result: dict[int, tuple[str, frozenset[int]]] = {}
150
+ for row in rows:
151
+ attributes = json.loads(row.attributes)
152
+ result[int(row.scope)] = (attributes["version"], frozenset(attributes["comment_ids"]))
153
+ return result
@@ -0,0 +1,138 @@
1
+ """Bounded reads and transactional checkpoints for historical search."""
2
+
3
+ import json
4
+
5
+ from sqlalchemy import text
6
+ from sqlalchemy.ext.asyncio import AsyncConnection
7
+
8
+ from plotroom.adapters.store_sqlite import asks_sql, github_sql, human_queue_sql, search_sql
9
+ from plotroom.core.github import PullRequest
10
+ from plotroom.core.github_projection import PULL_TEXT
11
+ from plotroom.core.search_sources import (
12
+ ask_record,
13
+ comment_record,
14
+ decision_record,
15
+ pull_body_record,
16
+ pull_text_record,
17
+ )
18
+ from plotroom.ports.search import BackfillPage, BackfillPosition, BackfillSource, SearchRecord
19
+
20
+ _POSITION = text("SELECT value FROM project_meta WHERE key = :key")
21
+ _SAVE_POSITION = text("""
22
+ INSERT INTO project_meta (key, value) VALUES (:key, :value)
23
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value
24
+ """)
25
+ _DECISIONS = text("SELECT * FROM decisions WHERE id > :after ORDER BY id LIMIT :limit")
26
+ _ASKS = text("SELECT * FROM human_asks WHERE id > :after ORDER BY id LIMIT :limit")
27
+ _COMMENTS = text("""
28
+ SELECT * FROM github_resources
29
+ WHERE resource = 'issue_comments' AND (repository, scope) > (:repository, :scope)
30
+ ORDER BY repository, scope LIMIT :limit
31
+ """)
32
+ _PULLS = text("""
33
+ SELECT * FROM github_pull_requests
34
+ WHERE (repository, number) > (:repository, :number)
35
+ ORDER BY repository, number LIMIT :limit
36
+ """)
37
+ # Keep the predicate identical to the partial index in revision 0022.
38
+ _LATEST_PULL = text("""
39
+ SELECT body, json_extract(fields, '$.updated_at') AS updated_at
40
+ FROM events
41
+ WHERE source = 'github' AND kind IN (
42
+ 'github.pr_opened', 'github.pr_merged', 'github.pr_closed',
43
+ 'github.pr_reopened', 'github.pr_head_changed'
44
+ )
45
+ AND json_extract(fields, '$.repository') = :repository
46
+ AND json_extract(fields, '$.number') = :number
47
+ ORDER BY seq DESC LIMIT 1
48
+ """)
49
+
50
+
51
+ async def position(connection: AsyncConnection, source: BackfillSource) -> BackfillPosition:
52
+ value = (
53
+ await connection.execute(_POSITION, {"key": f"search.backfill.{source}"})
54
+ ).scalar_one_or_none()
55
+ if value is None:
56
+ return ()
57
+ decoded = json.loads(value)
58
+ return None if decoded is None else tuple(decoded)
59
+
60
+
61
+ async def commit(
62
+ connection: AsyncConnection,
63
+ source: BackfillSource,
64
+ expected: BackfillPosition,
65
+ page: BackfillPage,
66
+ ) -> bool:
67
+ if await position(connection, source) != expected:
68
+ return False
69
+ for record in page.records:
70
+ await search_sql.index_record(connection, record, only_if_absent=True)
71
+ await connection.execute(
72
+ _SAVE_POSITION, {"key": f"search.backfill.{source}", "value": json.dumps(page.through)}
73
+ )
74
+ return True
75
+
76
+
77
+ async def read_page(
78
+ connection: AsyncConnection, source: BackfillSource, after: tuple[str | int, ...], limit: int
79
+ ) -> BackfillPage:
80
+ if source == BackfillSource.DECISIONS or source == BackfillSource.ASKS:
81
+ query = _DECISIONS if source == BackfillSource.DECISIONS else _ASKS
82
+ params = {"after": after[0] if after else "", "limit": limit}
83
+ rows = (await connection.execute(query, params)).all()
84
+ records = (
85
+ tuple(decision_record(human_queue_sql.decision_from_row(row)) for row in rows)
86
+ if source == BackfillSource.DECISIONS
87
+ else tuple(ask_record(asks_sql.ask_from_row(row)) for row in rows)
88
+ )
89
+ return BackfillPage((rows[-1].id,) if rows else None, records)
90
+ if source == BackfillSource.COMMENTS:
91
+ repository, scope = after or ("", "")
92
+ params = {"repository": repository, "scope": scope, "limit": limit}
93
+ rows = (await connection.execute(_COMMENTS, params)).all()
94
+ comments: list[SearchRecord] = []
95
+ for row in rows:
96
+ resource = github_sql.resource_from_row(row)
97
+ if resource.complete and len(resource.records) == 1:
98
+ (comment,) = resource.records
99
+ if comment.key == row.scope and comment.kind == "issue_comment":
100
+ comments.append(comment_record(row.repository, comment))
101
+ return BackfillPage(
102
+ (rows[-1].repository, rows[-1].scope) if rows else None, tuple(comments)
103
+ )
104
+ if source == BackfillSource.PULLS:
105
+ repository, number = after or ("", 0)
106
+ params = {"repository": repository, "number": number, "limit": limit}
107
+ rows = (await connection.execute(_PULLS, params)).all()
108
+ pulls: list[SearchRecord] = []
109
+ for row in rows:
110
+ record = await _retained_pull_text(connection, github_sql.pull_from_row(row))
111
+ if record is not None:
112
+ pulls.append(record)
113
+ return BackfillPage((rows[-1].repository, rows[-1].number) if rows else None, tuple(pulls))
114
+ raise ValueError("ledger event pages are read through the ledger")
115
+
116
+
117
+ async def _retained_pull_text(
118
+ connection: AsyncConnection, pull: PullRequest
119
+ ) -> SearchRecord | None:
120
+ latest = (
121
+ await connection.execute(
122
+ _LATEST_PULL, {"repository": pull.repository, "number": pull.number}
123
+ )
124
+ ).first()
125
+ snapshot = await github_sql.github_resource(
126
+ connection, pull.repository, PULL_TEXT, str(pull.number)
127
+ )
128
+ if snapshot is not None:
129
+ # Failed refreshes mark the resource incomplete and retain its verified attributes.
130
+ record = pull_text_record(
131
+ pull, snapshot, updated_since=latest.updated_at if latest else "", allow_incomplete=True
132
+ )
133
+ if record is not None:
134
+ return record
135
+ if latest is None:
136
+ return None
137
+ # Lifecycle metadata can match even when a body-only edit was never recorded.
138
+ return pull_body_record(pull.repository, pull.number, latest.body, provisional=True)