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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"""Durable GitHub observations applied by the project's single writer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from plotroom.core.events import FieldSpec, LedgerError, NewEvent
|
|
9
|
+
from plotroom.core.lanes import infer_lane
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
CHECKS = "checks"
|
|
16
|
+
COMMIT_STATUSES = "commit_statuses"
|
|
17
|
+
COMMIT_STATUS_BUCKETS = {
|
|
18
|
+
"success": "pass",
|
|
19
|
+
"pending": "pending",
|
|
20
|
+
"failure": "fail",
|
|
21
|
+
"error": "fail",
|
|
22
|
+
}
|
|
23
|
+
MAIN = "main_runs"
|
|
24
|
+
MAIN_CI = "main_ci"
|
|
25
|
+
MAIN_CI_WINDOW = 30
|
|
26
|
+
THREADS = "review_threads"
|
|
27
|
+
KODUS_REVIEW = "kodus_review"
|
|
28
|
+
FILES = "pull_files"
|
|
29
|
+
LABELS = "pull_labels"
|
|
30
|
+
PULL_TEXT = "pull_text"
|
|
31
|
+
ISSUES = "issues"
|
|
32
|
+
COMMENTS = "issue_comments"
|
|
33
|
+
COMMENT_BACKFILL = "issue_comments_backfill"
|
|
34
|
+
ASK_COMMENT_HISTORY = "ask_comment_history"
|
|
35
|
+
ISSUE_TREE = "issue_tree"
|
|
36
|
+
ISSUE_PAGINATION_VERIFIED = "pagination_verified"
|
|
37
|
+
ISSUE_RELATION_RETRY = "relationship_retry"
|
|
38
|
+
|
|
39
|
+
REPOSITORY = FieldSpec("repository", "str")
|
|
40
|
+
NUMBER = FieldSpec("number", "int")
|
|
41
|
+
HEAD = FieldSpec("head_sha", "str")
|
|
42
|
+
STATUS = FieldSpec("status", "str")
|
|
43
|
+
CONCLUSION = FieldSpec("conclusion", "str", required=False)
|
|
44
|
+
NAME = FieldSpec("name", "str")
|
|
45
|
+
GITHUB_FIELDS = {
|
|
46
|
+
"check_run": (
|
|
47
|
+
FieldSpec("id", "int"),
|
|
48
|
+
HEAD,
|
|
49
|
+
NAME,
|
|
50
|
+
STATUS,
|
|
51
|
+
CONCLUSION,
|
|
52
|
+
FieldSpec("number", "int", required=False),
|
|
53
|
+
),
|
|
54
|
+
"workflow_run": (
|
|
55
|
+
FieldSpec("id", "int"),
|
|
56
|
+
FieldSpec("attempt", "int"),
|
|
57
|
+
HEAD,
|
|
58
|
+
NAME,
|
|
59
|
+
STATUS,
|
|
60
|
+
CONCLUSION,
|
|
61
|
+
FieldSpec("jobs", "array"),
|
|
62
|
+
),
|
|
63
|
+
"review_thread": (
|
|
64
|
+
FieldSpec("id", "str"),
|
|
65
|
+
NUMBER,
|
|
66
|
+
FieldSpec("resolved", "bool"),
|
|
67
|
+
FieldSpec("path", "str"),
|
|
68
|
+
FieldSpec("line", "int", required=False),
|
|
69
|
+
),
|
|
70
|
+
"pull_file": (
|
|
71
|
+
NUMBER,
|
|
72
|
+
HEAD,
|
|
73
|
+
FieldSpec("path", "str"),
|
|
74
|
+
STATUS,
|
|
75
|
+
FieldSpec("previous_path", "str", required=False),
|
|
76
|
+
),
|
|
77
|
+
"pull_label": (
|
|
78
|
+
NUMBER,
|
|
79
|
+
NAME,
|
|
80
|
+
FieldSpec("actor", "str", required=False),
|
|
81
|
+
FieldSpec("action", "str"),
|
|
82
|
+
FieldSpec("id", "int"),
|
|
83
|
+
),
|
|
84
|
+
"issue_opened": (NUMBER, FieldSpec("state", "str")),
|
|
85
|
+
"issue_closed": (NUMBER, FieldSpec("state", "str")),
|
|
86
|
+
"issue_reopened": (NUMBER, FieldSpec("state", "str")),
|
|
87
|
+
"issue_assignees": (NUMBER, FieldSpec("assignees", "array")),
|
|
88
|
+
"issue_comment": (
|
|
89
|
+
NUMBER,
|
|
90
|
+
FieldSpec("id", "int"),
|
|
91
|
+
FieldSpec("author", "str", required=False),
|
|
92
|
+
FieldSpec("created_at", "str"),
|
|
93
|
+
FieldSpec("updated_at", "str"),
|
|
94
|
+
),
|
|
95
|
+
"issue_metadata": (
|
|
96
|
+
NUMBER,
|
|
97
|
+
FieldSpec("labels", "array"),
|
|
98
|
+
FieldSpec("milestone", "int", required=False),
|
|
99
|
+
FieldSpec("sub_issues", "array"),
|
|
100
|
+
FieldSpec("blocked_by", "array"),
|
|
101
|
+
),
|
|
102
|
+
"milestone": (NUMBER, FieldSpec("state", "str"), FieldSpec("title", "str")),
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True)
|
|
107
|
+
class GitHubRecord:
|
|
108
|
+
key: str
|
|
109
|
+
kind: str
|
|
110
|
+
fields: dict[str, Any]
|
|
111
|
+
body: str = ""
|
|
112
|
+
# Raw projection fields can evolve without a distinct event (e.g. a workflow's jobs).
|
|
113
|
+
details: dict[str, Any] = field(default_factory=lambda: {})
|
|
114
|
+
fact: str = ""
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class GitHubResource:
|
|
119
|
+
records: tuple[GitHubRecord, ...]
|
|
120
|
+
complete: bool = True
|
|
121
|
+
attributes: dict[str, Any] = field(default_factory=lambda: {})
|
|
122
|
+
generation: int = 0
|
|
123
|
+
as_of: str = ""
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
async def apply_resource(
|
|
127
|
+
uow: UnitOfWork,
|
|
128
|
+
repository: str,
|
|
129
|
+
resource: str,
|
|
130
|
+
scope: str,
|
|
131
|
+
result: GitHubResource,
|
|
132
|
+
as_of: str,
|
|
133
|
+
*,
|
|
134
|
+
pulls: tuple[int, ...] = (),
|
|
135
|
+
) -> None:
|
|
136
|
+
current = await uow.github_resource(repository, resource, scope)
|
|
137
|
+
previous = {row.key: row for row in current.records} if current else {}
|
|
138
|
+
generation = current.generation + 1 if current else 1
|
|
139
|
+
fresh = {row.key: row for row in result.records}
|
|
140
|
+
bindings: dict[int, str | None] = {}
|
|
141
|
+
if resource == FILES:
|
|
142
|
+
pulls = (int(scope),)
|
|
143
|
+
candidates = set(pulls)
|
|
144
|
+
if resource == CHECKS:
|
|
145
|
+
candidates.update(
|
|
146
|
+
number for row in fresh.values() for number in row.details["pull_numbers"]
|
|
147
|
+
)
|
|
148
|
+
for number in sorted(candidates):
|
|
149
|
+
pr = await uow.pull_request(repository, number)
|
|
150
|
+
if pr is None and resource == FILES:
|
|
151
|
+
return
|
|
152
|
+
if pr is None or (resource == CHECKS and scope != pr.head_sha):
|
|
153
|
+
continue
|
|
154
|
+
if resource == FILES and result.complete and result.attributes["head_sha"] != pr.head_sha:
|
|
155
|
+
# The PR poll committed a new head while the file request was in flight.
|
|
156
|
+
return
|
|
157
|
+
bindings[number] = (
|
|
158
|
+
await infer_lane(uow, branch=pr.branch) if pr.head_repository == repository else None
|
|
159
|
+
)
|
|
160
|
+
# Gate-only resources never emit trigger events. Workflow events still come
|
|
161
|
+
# from the existing all-workflow monitor.
|
|
162
|
+
for row in () if resource in (MAIN_CI, COMMIT_STATUSES) else fresh.values():
|
|
163
|
+
prior = previous.get(row.key)
|
|
164
|
+
if prior is not None and (
|
|
165
|
+
row.fact == prior.fact
|
|
166
|
+
if row.fact
|
|
167
|
+
else (row.fields, row.body) == (prior.fields, prior.body)
|
|
168
|
+
):
|
|
169
|
+
continue
|
|
170
|
+
kind = row.kind
|
|
171
|
+
if kind == "issue_opened" and prior is not None:
|
|
172
|
+
kind = "issue_reopened"
|
|
173
|
+
fields = {"repository": repository, **row.fields}
|
|
174
|
+
selected = row.details.get("pull_numbers") or pulls
|
|
175
|
+
candidates = [(number, bindings[number]) for number in selected if number in bindings]
|
|
176
|
+
with_lane = [(number, lane) for number, lane in candidates if lane is not None]
|
|
177
|
+
lane_id = None
|
|
178
|
+
relevant = with_lane or candidates
|
|
179
|
+
if len(relevant) == 1:
|
|
180
|
+
fields["number"], lane_id = relevant[0]
|
|
181
|
+
uid = f"{repository}:{resource}:{scope}:{row.key}@{row.fact or generation}"
|
|
182
|
+
if kind in {
|
|
183
|
+
"check_run",
|
|
184
|
+
"review_thread",
|
|
185
|
+
"issue_opened",
|
|
186
|
+
"issue_closed",
|
|
187
|
+
"issue_reopened",
|
|
188
|
+
}:
|
|
189
|
+
uid = f"{uid}:{generation}"
|
|
190
|
+
await uow.append(NewEvent("github", f"github.{kind}", uid, fields, row.body, lane_id))
|
|
191
|
+
records = fresh if result.complete else {**previous, **fresh}
|
|
192
|
+
attributes = (
|
|
193
|
+
result.attributes
|
|
194
|
+
if result.complete
|
|
195
|
+
else {**(current.attributes if current else {}), **result.attributes}
|
|
196
|
+
)
|
|
197
|
+
await uow.save_github_resource(
|
|
198
|
+
repository,
|
|
199
|
+
resource,
|
|
200
|
+
scope,
|
|
201
|
+
GitHubResource(tuple(records.values()), result.complete, attributes, generation, as_of),
|
|
202
|
+
)
|
|
203
|
+
if (
|
|
204
|
+
resource == FILES
|
|
205
|
+
and result.complete
|
|
206
|
+
and (
|
|
207
|
+
current is None
|
|
208
|
+
or current.attributes.get("head_sha") != attributes.get("head_sha")
|
|
209
|
+
or previous != fresh
|
|
210
|
+
)
|
|
211
|
+
):
|
|
212
|
+
uow.pull_overlaps_changed()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def projected_issues(resource: GitHubResource | None) -> dict[int, GitHubRecord]:
|
|
216
|
+
if resource is None or not resource.complete:
|
|
217
|
+
return {}
|
|
218
|
+
return {
|
|
219
|
+
row.fields["number"]: row
|
|
220
|
+
for row in resource.records
|
|
221
|
+
if row.details.get("resource") == "issue"
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def ask_history_version(issue: GitHubRecord) -> tuple[str, int] | None:
|
|
226
|
+
count = issue.details.get("comment_count")
|
|
227
|
+
updated = issue.details.get("updated_at")
|
|
228
|
+
if (
|
|
229
|
+
issue.kind == "issue_closed"
|
|
230
|
+
and type(count) is int
|
|
231
|
+
and count >= 0
|
|
232
|
+
and isinstance(updated, str)
|
|
233
|
+
and updated
|
|
234
|
+
):
|
|
235
|
+
return f"{updated}/{count}", count
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
async def projected_comment(
|
|
240
|
+
uow: UnitOfWork, repository: str, issue: int, comment_id: int
|
|
241
|
+
) -> GitHubRecord:
|
|
242
|
+
scope = str(comment_id)
|
|
243
|
+
resource = await uow.github_resource(repository, COMMENTS, scope)
|
|
244
|
+
if resource is None or not resource.complete or not resource.records:
|
|
245
|
+
raise LedgerError(
|
|
246
|
+
"unavailable", "the cited comment is not projected yet; retry after polling"
|
|
247
|
+
)
|
|
248
|
+
if len(resource.records) == 1:
|
|
249
|
+
(comment,) = resource.records
|
|
250
|
+
if (
|
|
251
|
+
comment.kind == "issue_comment"
|
|
252
|
+
and comment.key == scope
|
|
253
|
+
and type(comment.fields.get("id")) is int
|
|
254
|
+
and comment.fields["id"] == comment_id
|
|
255
|
+
and type(comment.fields.get("number")) is int
|
|
256
|
+
and comment.fields["number"] == issue
|
|
257
|
+
):
|
|
258
|
+
return comment
|
|
259
|
+
raise LedgerError("invalid", "the projected comment does not match the cited issue and ID")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def latest_checks(resource: GitHubResource) -> tuple[GitHubRecord, ...]:
|
|
263
|
+
latest: dict[str, GitHubRecord] = {}
|
|
264
|
+
for check in sorted(resource.records, key=lambda item: int(item.fields["id"])):
|
|
265
|
+
latest[check.fields["name"]] = check
|
|
266
|
+
return tuple(latest.values())
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def checks_for_head(resource: GitHubResource, head_sha: str) -> tuple[GitHubRecord, ...] | None:
|
|
270
|
+
"""Select latest attempts by check name and app for this head."""
|
|
271
|
+
latest: dict[tuple[str, int | None, int | None], GitHubRecord] = {}
|
|
272
|
+
for check in resource.records:
|
|
273
|
+
fields = check.fields
|
|
274
|
+
if (
|
|
275
|
+
check.kind != "check_run"
|
|
276
|
+
or type(fields.get("id")) is not int
|
|
277
|
+
or fields["id"] < 1
|
|
278
|
+
or not isinstance(fields.get("name"), str)
|
|
279
|
+
or not fields["name"]
|
|
280
|
+
or fields.get("head_sha") != head_sha
|
|
281
|
+
):
|
|
282
|
+
return None
|
|
283
|
+
app_id = check.details.get("app_id")
|
|
284
|
+
# Unidentified runs cannot establish that they supersede one another.
|
|
285
|
+
if type(app_id) is int and app_id > 0:
|
|
286
|
+
key = (fields["name"], app_id, None)
|
|
287
|
+
else:
|
|
288
|
+
key = (fields["name"], None, fields["id"])
|
|
289
|
+
prior = latest.get(key)
|
|
290
|
+
if prior is None or fields["id"] > prior.fields["id"]:
|
|
291
|
+
latest[key] = check
|
|
292
|
+
return tuple(latest.values())
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def main_verdict(
|
|
296
|
+
resource: GitHubResource, *, require_attribution: bool = False
|
|
297
|
+
) -> GitHubRecord | None:
|
|
298
|
+
return next(
|
|
299
|
+
(
|
|
300
|
+
row
|
|
301
|
+
for row in resource.records
|
|
302
|
+
if row.fields["status"] == "completed"
|
|
303
|
+
and (not require_attribution or row.details.get("main_branch_run") is True)
|
|
304
|
+
),
|
|
305
|
+
None,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def unresolved_threads(resource: GitHubResource) -> tuple[GitHubRecord, ...]:
|
|
310
|
+
return tuple(row for row in resource.records if not row.fields["resolved"])
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
"""Parse and evaluate the operator's goal language over read-only issue facts."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import Enum, auto
|
|
8
|
+
from functools import cache
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
from plotroom.core.goal_projection import GoalFacts, GoalIssue, issue_number
|
|
12
|
+
|
|
13
|
+
_MAX_SOURCE = 4096
|
|
14
|
+
_MAX_TOKENS = 512
|
|
15
|
+
_MAX_DEPTH = 32
|
|
16
|
+
_WORD_OR_INTEGER = re.compile(r"[A-Za-z_][A-Za-z_0-9]*|[0-9]+")
|
|
17
|
+
_DECODER = json.JSONDecoder()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GoalSyntaxError(ValueError):
|
|
21
|
+
"""A validation error at a zero-based character offset into the goal text."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, text: str, position: int, message: str) -> None:
|
|
24
|
+
self.position = position
|
|
25
|
+
self.line = text.count("\n", 0, position) + 1
|
|
26
|
+
self.column = position - text.rfind("\n", 0, position)
|
|
27
|
+
super().__init__(f"{message} at line {self.line}, column {self.column}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class _Span:
|
|
32
|
+
start: int
|
|
33
|
+
end: int
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
type _TokenKind = Literal["word", "integer", "string", "=", "(", ")", "end"]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class _Token:
|
|
41
|
+
kind: _TokenKind
|
|
42
|
+
value: str
|
|
43
|
+
span: _Span
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _scan(text: str) -> Iterator[_Token]:
|
|
47
|
+
position = 0
|
|
48
|
+
while position < len(text):
|
|
49
|
+
char = text[position]
|
|
50
|
+
if char.isspace():
|
|
51
|
+
position += 1
|
|
52
|
+
continue
|
|
53
|
+
start = position
|
|
54
|
+
if char == '"':
|
|
55
|
+
try:
|
|
56
|
+
value, position = _DECODER.raw_decode(text, position)
|
|
57
|
+
except json.JSONDecodeError as exc:
|
|
58
|
+
raise GoalSyntaxError(text, exc.pos, exc.msg) from exc
|
|
59
|
+
assert isinstance(value, str)
|
|
60
|
+
yield _Token("string", value, _Span(start, position))
|
|
61
|
+
elif char in ("=", "(", ")"):
|
|
62
|
+
position += 1
|
|
63
|
+
yield _Token(char, char, _Span(start, position))
|
|
64
|
+
elif match := _WORD_OR_INTEGER.match(text, position):
|
|
65
|
+
position = match.end()
|
|
66
|
+
kind = "integer" if char.isascii() and char.isdecimal() else "word"
|
|
67
|
+
yield _Token(kind, match[0], _Span(start, position))
|
|
68
|
+
else:
|
|
69
|
+
raise GoalSyntaxError(text, position, f"Unexpected character {char!r}")
|
|
70
|
+
yield _Token("end", "", _Span(position, position))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class _Atom:
|
|
75
|
+
span: _Span
|
|
76
|
+
field: Literal["state", "milestone", "label", "assigned_to", "lane", "decision"]
|
|
77
|
+
value: str | int | None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class _Unary:
|
|
82
|
+
span: _Span
|
|
83
|
+
operator: Literal["not", "blocked_by", "group"]
|
|
84
|
+
child: _Predicate
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class _Boolean:
|
|
89
|
+
span: _Span
|
|
90
|
+
operator: Literal["and", "or"]
|
|
91
|
+
children: tuple[_Predicate, ...]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
type _Predicate = _Atom | _Unary | _Boolean
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class Goal:
|
|
99
|
+
text: str
|
|
100
|
+
selector: _Predicate
|
|
101
|
+
requirement: _Predicate
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class _Parser:
|
|
105
|
+
def __init__(self, text: str) -> None:
|
|
106
|
+
self.text = text
|
|
107
|
+
self.tokens = _scan(text)
|
|
108
|
+
self.count = 0
|
|
109
|
+
self.current = next(self.tokens)
|
|
110
|
+
|
|
111
|
+
def advance(self) -> _Token:
|
|
112
|
+
token = self.current
|
|
113
|
+
if self.count >= _MAX_TOKENS:
|
|
114
|
+
raise GoalSyntaxError(self.text, token.span.start, "Goal has too many tokens")
|
|
115
|
+
self.count += 1
|
|
116
|
+
self.current = next(self.tokens)
|
|
117
|
+
return token
|
|
118
|
+
|
|
119
|
+
def expect(self, kind: _TokenKind, value: str | None = None) -> _Token:
|
|
120
|
+
token = self.current
|
|
121
|
+
if token.kind != kind or (value is not None and token.value != value):
|
|
122
|
+
expected = repr(value) if value is not None else _TOKEN_NAMES[kind]
|
|
123
|
+
raise GoalSyntaxError(self.text, token.span.start, f"Expected {expected}")
|
|
124
|
+
return token if kind == "end" else self.advance()
|
|
125
|
+
|
|
126
|
+
def parse(self) -> Goal:
|
|
127
|
+
self.expect("word", "every")
|
|
128
|
+
self.expect("word", "issue")
|
|
129
|
+
self.expect("word", "where")
|
|
130
|
+
selector = self.boolean("or", 0)
|
|
131
|
+
self.expect("word", "satisfies")
|
|
132
|
+
requirement = self.boolean("or", 0)
|
|
133
|
+
self.expect("end")
|
|
134
|
+
return Goal(self.text, selector, requirement)
|
|
135
|
+
|
|
136
|
+
def boolean(self, operator: Literal["and", "or"], depth: int) -> _Predicate:
|
|
137
|
+
def operand() -> _Predicate:
|
|
138
|
+
return self.boolean("and", depth) if operator == "or" else self.term(depth)
|
|
139
|
+
|
|
140
|
+
first = operand()
|
|
141
|
+
children = [first]
|
|
142
|
+
while self.current.kind == "word" and self.current.value == operator:
|
|
143
|
+
self.advance()
|
|
144
|
+
children.append(operand())
|
|
145
|
+
if len(children) == 1:
|
|
146
|
+
return first
|
|
147
|
+
return _Boolean(_Span(first.span.start, children[-1].span.end), operator, tuple(children))
|
|
148
|
+
|
|
149
|
+
def term(self, depth: int) -> _Predicate:
|
|
150
|
+
token = self.current
|
|
151
|
+
if depth >= _MAX_DEPTH:
|
|
152
|
+
raise GoalSyntaxError(self.text, token.span.start, "Predicate nesting is too deep")
|
|
153
|
+
if token.kind == "(":
|
|
154
|
+
return self.group("group", token.span.start, depth)
|
|
155
|
+
if token.kind != "word":
|
|
156
|
+
raise GoalSyntaxError(self.text, token.span.start, "Expected a predicate")
|
|
157
|
+
self.advance()
|
|
158
|
+
field = token.value
|
|
159
|
+
start = token.span.start
|
|
160
|
+
if field == "not":
|
|
161
|
+
child = self.term(depth + 1)
|
|
162
|
+
return _Unary(_Span(start, child.span.end), "not", child)
|
|
163
|
+
if field == "blocked_by":
|
|
164
|
+
return self.group("blocked_by", start, depth)
|
|
165
|
+
if field == "state":
|
|
166
|
+
self.expect("=")
|
|
167
|
+
state = self.expect("word")
|
|
168
|
+
if state.value not in ("open", "closed"):
|
|
169
|
+
raise GoalSyntaxError(self.text, state.span.start, "Expected 'open' or 'closed'")
|
|
170
|
+
return _Atom(_Span(start, state.span.end), "state", state.value)
|
|
171
|
+
if field == "milestone":
|
|
172
|
+
self.expect("=")
|
|
173
|
+
number = self.expect("integer")
|
|
174
|
+
try:
|
|
175
|
+
value = int(number.value)
|
|
176
|
+
except ValueError:
|
|
177
|
+
raise GoalSyntaxError(self.text, number.span.start, "Integer is too long") from None
|
|
178
|
+
if value == 0:
|
|
179
|
+
raise GoalSyntaxError(self.text, number.span.start, "Expected a positive integer")
|
|
180
|
+
return _Atom(_Span(start, number.span.end), "milestone", value)
|
|
181
|
+
if field in ("label", "lane", "decision"):
|
|
182
|
+
name = self.expect("string")
|
|
183
|
+
return _Atom(_Span(start, name.span.end), field, name.value)
|
|
184
|
+
if field == "assigned_to":
|
|
185
|
+
if self.current.kind == "word" and self.current.value == "human":
|
|
186
|
+
human = self.advance()
|
|
187
|
+
return _Atom(_Span(start, human.span.end), "assigned_to", None)
|
|
188
|
+
login = self.expect("string")
|
|
189
|
+
return _Atom(_Span(start, login.span.end), "assigned_to", login.value.casefold())
|
|
190
|
+
raise GoalSyntaxError(self.text, start, f"Unknown predicate {field!r}")
|
|
191
|
+
|
|
192
|
+
def group(self, operator: Literal["blocked_by", "group"], start: int, depth: int) -> _Unary:
|
|
193
|
+
self.expect("(")
|
|
194
|
+
child = self.boolean("or", depth + 1)
|
|
195
|
+
end = self.expect(")").span.end
|
|
196
|
+
return _Unary(_Span(start, end), operator, child)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
_TOKEN_NAMES: dict[_TokenKind, str] = {
|
|
200
|
+
"word": "a keyword",
|
|
201
|
+
"integer": "a positive integer",
|
|
202
|
+
"string": "a quoted string",
|
|
203
|
+
"=": "'='",
|
|
204
|
+
"(": "'('",
|
|
205
|
+
")": "')'",
|
|
206
|
+
"end": "the end of the goal",
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def parse_goal(text: str) -> Goal:
|
|
211
|
+
"""Validate a goal and retain its source for exact clause evidence."""
|
|
212
|
+
if len(text) > _MAX_SOURCE:
|
|
213
|
+
raise GoalSyntaxError(text, _MAX_SOURCE, "Goal text is too long")
|
|
214
|
+
return _Parser(text).parse()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def goal_predicates(goal: Goal) -> frozenset[str]:
|
|
218
|
+
def collect(predicate: _Predicate) -> Iterator[str]:
|
|
219
|
+
if isinstance(predicate, _Atom):
|
|
220
|
+
yield predicate.field
|
|
221
|
+
elif isinstance(predicate, _Unary):
|
|
222
|
+
yield predicate.operator
|
|
223
|
+
yield from collect(predicate.child)
|
|
224
|
+
else:
|
|
225
|
+
for child in predicate.children:
|
|
226
|
+
yield from collect(child)
|
|
227
|
+
|
|
228
|
+
return frozenset((*collect(goal.selector), *collect(goal.requirement)))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class _Truth(Enum):
|
|
232
|
+
FALSE = auto()
|
|
233
|
+
UNKNOWN = auto()
|
|
234
|
+
TRUE = auto()
|
|
235
|
+
|
|
236
|
+
@classmethod
|
|
237
|
+
def of(cls, value: bool) -> _Truth:
|
|
238
|
+
return cls.TRUE if value else cls.FALSE
|
|
239
|
+
|
|
240
|
+
def negate(self) -> _Truth:
|
|
241
|
+
return self if self is _Truth.UNKNOWN else self.of(self is _Truth.FALSE)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass(frozen=True)
|
|
245
|
+
class _ClauseFailure:
|
|
246
|
+
span: _Span
|
|
247
|
+
status: Literal["failed", "unavailable"]
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@dataclass(frozen=True)
|
|
251
|
+
class _Result:
|
|
252
|
+
truth: _Truth
|
|
253
|
+
failures: tuple[_ClauseFailure, ...] = ()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _result(truth: _Truth, span: _Span) -> _Result:
|
|
257
|
+
if truth is _Truth.TRUE:
|
|
258
|
+
return _Result(truth)
|
|
259
|
+
status = "unavailable" if truth is _Truth.UNKNOWN else "failed"
|
|
260
|
+
return _Result(truth, (_ClauseFailure(span, status),))
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _evaluate_atom(atom: _Atom, issue: GoalIssue, facts: GoalFacts) -> _Truth:
|
|
264
|
+
field, value = atom.field, atom.value
|
|
265
|
+
match field:
|
|
266
|
+
case "state":
|
|
267
|
+
return _Truth.of(issue.state == value)
|
|
268
|
+
case "milestone":
|
|
269
|
+
return _Truth.of(issue.milestone == value)
|
|
270
|
+
case "label":
|
|
271
|
+
return _Truth.of(value in issue.labels)
|
|
272
|
+
case "lane":
|
|
273
|
+
if value in issue.lanes:
|
|
274
|
+
return _Truth.TRUE
|
|
275
|
+
return _Truth.UNKNOWN if value in facts.unresolved_lanes else _Truth.FALSE
|
|
276
|
+
case "decision":
|
|
277
|
+
return _Truth.of(value in issue.decisions)
|
|
278
|
+
case "assigned_to":
|
|
279
|
+
login = facts.human_login if value is None else value
|
|
280
|
+
if login is None:
|
|
281
|
+
return _Truth.UNKNOWN
|
|
282
|
+
assert isinstance(login, str)
|
|
283
|
+
normalized = login.casefold()
|
|
284
|
+
return _Truth.of(any(assignee.casefold() == normalized for assignee in issue.assignees))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@dataclass(frozen=True)
|
|
288
|
+
class GoalFailure:
|
|
289
|
+
issue: int
|
|
290
|
+
title: str
|
|
291
|
+
clauses: tuple[GoalClause, ...]
|
|
292
|
+
|
|
293
|
+
def render(self) -> dict[str, object]:
|
|
294
|
+
return {
|
|
295
|
+
"issue": self.issue,
|
|
296
|
+
"title": self.title,
|
|
297
|
+
"clauses": [
|
|
298
|
+
{"clause": clause.text, "position": clause.position, "status": clause.status}
|
|
299
|
+
for clause in self.clauses
|
|
300
|
+
],
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
@dataclass(frozen=True)
|
|
305
|
+
class GoalClause:
|
|
306
|
+
text: str
|
|
307
|
+
position: int
|
|
308
|
+
status: Literal["failed", "unavailable"]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def evaluate_goal(goal: Goal, facts: GoalFacts) -> list[GoalFailure]:
|
|
312
|
+
"""Return each selected violation, including evidence that leaves selection unknown."""
|
|
313
|
+
|
|
314
|
+
def blocker_truth(issue: GoalIssue, predicate: _Predicate) -> _Truth:
|
|
315
|
+
if issue.blockers is None:
|
|
316
|
+
return _Truth.UNKNOWN
|
|
317
|
+
truth = _Truth.FALSE
|
|
318
|
+
for ref in issue.blockers:
|
|
319
|
+
number = ref if isinstance(ref, int) else issue_number(facts.repository, ref)
|
|
320
|
+
if number is None or (blocker := facts.issues.get(number)) is None:
|
|
321
|
+
truth = _Truth.UNKNOWN
|
|
322
|
+
elif blocker.state == "open":
|
|
323
|
+
match = evaluate(predicate, number).truth
|
|
324
|
+
if match is _Truth.TRUE:
|
|
325
|
+
return match
|
|
326
|
+
if match is _Truth.UNKNOWN:
|
|
327
|
+
truth = match
|
|
328
|
+
return truth
|
|
329
|
+
|
|
330
|
+
@cache
|
|
331
|
+
def evaluate(predicate: _Predicate, number: int) -> _Result:
|
|
332
|
+
issue = facts.issues[number]
|
|
333
|
+
if isinstance(predicate, _Atom):
|
|
334
|
+
return _result(_evaluate_atom(predicate, issue, facts), predicate.span)
|
|
335
|
+
if isinstance(predicate, _Unary):
|
|
336
|
+
match predicate.operator:
|
|
337
|
+
case "group":
|
|
338
|
+
return evaluate(predicate.child, number)
|
|
339
|
+
case "not":
|
|
340
|
+
truth = evaluate(predicate.child, number).truth.negate()
|
|
341
|
+
case "blocked_by":
|
|
342
|
+
truth = blocker_truth(issue, predicate.child)
|
|
343
|
+
return _result(truth, predicate.span)
|
|
344
|
+
results: list[_Result] = []
|
|
345
|
+
for child in predicate.children:
|
|
346
|
+
result = evaluate(child, number)
|
|
347
|
+
if predicate.operator == "or" and result.truth is _Truth.TRUE:
|
|
348
|
+
return result
|
|
349
|
+
results.append(result)
|
|
350
|
+
if predicate.operator == "and" and any(r.truth is _Truth.FALSE for r in results):
|
|
351
|
+
truth = _Truth.FALSE
|
|
352
|
+
elif any(r.truth is _Truth.UNKNOWN for r in results):
|
|
353
|
+
truth = _Truth.UNKNOWN
|
|
354
|
+
else:
|
|
355
|
+
truth = _Truth.TRUE if predicate.operator == "and" else _Truth.FALSE
|
|
356
|
+
return _Result(truth, tuple(clause for result in results for clause in result.failures))
|
|
357
|
+
|
|
358
|
+
failures: list[GoalFailure] = []
|
|
359
|
+
for number, issue in sorted(facts.issues.items()):
|
|
360
|
+
selection = evaluate(goal.selector, number)
|
|
361
|
+
if selection.truth is _Truth.FALSE:
|
|
362
|
+
continue
|
|
363
|
+
result = evaluate(goal.requirement, number) if selection.truth is _Truth.TRUE else selection
|
|
364
|
+
if result.truth is _Truth.TRUE:
|
|
365
|
+
continue
|
|
366
|
+
clauses = tuple(
|
|
367
|
+
GoalClause(
|
|
368
|
+
goal.text[failure.span.start : failure.span.end], failure.span.start, failure.status
|
|
369
|
+
)
|
|
370
|
+
for failure in result.failures
|
|
371
|
+
)
|
|
372
|
+
failures.append(GoalFailure(number, issue.title, clauses))
|
|
373
|
+
evaluate.cache_clear()
|
|
374
|
+
return failures
|