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,111 @@
|
|
|
1
|
+
"""Storage for the trigger inventory and its committed projection inputs."""
|
|
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.triggers import Trigger
|
|
12
|
+
|
|
13
|
+
_FIND = text("SELECT * FROM triggers WHERE id = :id")
|
|
14
|
+
_OPEN = text("SELECT * FROM triggers WHERE state = 'open' ORDER BY created_seq")
|
|
15
|
+
_LIST = text("SELECT * FROM triggers ORDER BY created_seq")
|
|
16
|
+
_LIST_LANE = text("SELECT * FROM triggers WHERE lane = :lane ORDER BY created_seq")
|
|
17
|
+
_COUNTS = text("SELECT state, count(*) AS total FROM triggers GROUP BY state")
|
|
18
|
+
_SAVE = text("""
|
|
19
|
+
INSERT INTO triggers
|
|
20
|
+
(id, lane, repository, predicate, action_kind, action_payload, state, bindings,
|
|
21
|
+
created_seq, fired_seq, action_key, mode, was_true, event_floors,
|
|
22
|
+
import_note, notify_on_fire)
|
|
23
|
+
VALUES
|
|
24
|
+
(:id, :lane, :repository, :predicate, :action_kind, :action_payload, :state, :bindings,
|
|
25
|
+
:created_seq, :fired_seq, :action_key, :mode, :was_true, :event_floors,
|
|
26
|
+
:import_note, :notify_on_fire)
|
|
27
|
+
ON CONFLICT(id) DO UPDATE SET state = excluded.state, bindings = excluded.bindings,
|
|
28
|
+
fired_seq = excluded.fired_seq, action_key = excluded.action_key,
|
|
29
|
+
was_true = excluded.was_true, event_floors = excluded.event_floors
|
|
30
|
+
""")
|
|
31
|
+
_BRANCHES = text("""
|
|
32
|
+
SELECT p.number, p.branch FROM github_pull_requests AS p
|
|
33
|
+
JOIN trigger_pr_branch_order AS o
|
|
34
|
+
ON p.repository = o.repository AND p.number = o.number AND p.branch = o.branch
|
|
35
|
+
WHERE p.repository = :repository AND p.complete
|
|
36
|
+
ORDER BY o.observation_order
|
|
37
|
+
""")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _from_row(row: Row[Any]) -> Trigger:
|
|
41
|
+
return Trigger(
|
|
42
|
+
row.id,
|
|
43
|
+
row.lane,
|
|
44
|
+
row.repository,
|
|
45
|
+
json.loads(row.predicate),
|
|
46
|
+
row.action_kind,
|
|
47
|
+
json.loads(row.action_payload),
|
|
48
|
+
row.state,
|
|
49
|
+
json.loads(row.bindings),
|
|
50
|
+
row.created_seq,
|
|
51
|
+
row.fired_seq,
|
|
52
|
+
row.action_key,
|
|
53
|
+
row.mode,
|
|
54
|
+
bool(row.was_true),
|
|
55
|
+
json.loads(row.event_floors),
|
|
56
|
+
row.import_note,
|
|
57
|
+
bool(row.notify_on_fire),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
async def find_trigger(connection: AsyncConnection, trigger_id: str) -> Trigger | None:
|
|
62
|
+
row = (await connection.execute(_FIND, {"id": trigger_id})).first()
|
|
63
|
+
return _from_row(row) if row is not None else None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def open_triggers(connection: AsyncConnection) -> list[Trigger]:
|
|
67
|
+
return [_from_row(row) for row in await connection.execute(_OPEN)]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def list_triggers(connection: AsyncConnection, lane: str | None) -> list[Trigger]:
|
|
71
|
+
rows = (
|
|
72
|
+
await connection.execute(_LIST)
|
|
73
|
+
if lane is None
|
|
74
|
+
else await connection.execute(_LIST_LANE, {"lane": lane})
|
|
75
|
+
)
|
|
76
|
+
return [_from_row(row) for row in rows]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def trigger_counts(connection: AsyncConnection) -> dict[str, int]:
|
|
80
|
+
return {row.state: row.total for row in await connection.execute(_COUNTS)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def save_trigger(connection: AsyncConnection, trigger: Trigger) -> None:
|
|
84
|
+
await connection.execute(
|
|
85
|
+
_SAVE,
|
|
86
|
+
{
|
|
87
|
+
"id": trigger.id,
|
|
88
|
+
"lane": trigger.lane,
|
|
89
|
+
"repository": trigger.repository,
|
|
90
|
+
"predicate": json.dumps(trigger.predicate, allow_nan=False),
|
|
91
|
+
"action_kind": trigger.action_kind,
|
|
92
|
+
"action_payload": json.dumps(trigger.action_payload, allow_nan=False),
|
|
93
|
+
"state": trigger.state,
|
|
94
|
+
"bindings": json.dumps(trigger.bindings),
|
|
95
|
+
"created_seq": trigger.created_seq,
|
|
96
|
+
"fired_seq": trigger.fired_seq,
|
|
97
|
+
"action_key": trigger.action_key,
|
|
98
|
+
"mode": trigger.mode,
|
|
99
|
+
"was_true": trigger.was_true,
|
|
100
|
+
"event_floors": json.dumps(trigger.event_floors),
|
|
101
|
+
"import_note": trigger.import_note,
|
|
102
|
+
"notify_on_fire": trigger.notify_on_fire,
|
|
103
|
+
},
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def branch_candidates(
|
|
108
|
+
connection: AsyncConnection, repository: str
|
|
109
|
+
) -> tuple[tuple[int, str], ...]:
|
|
110
|
+
rows = await connection.execute(_BRANCHES, {"repository": repository})
|
|
111
|
+
return tuple((row.number, row.branch) for row in rows)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""The read-only source's durable projection."""
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import text
|
|
4
|
+
from sqlalchemy.ext.asyncio import AsyncConnection
|
|
5
|
+
|
|
6
|
+
from plotroom.ports.work_items import WorkItem
|
|
7
|
+
|
|
8
|
+
_READY = text("SELECT ref, title FROM work_items ORDER BY source_order")
|
|
9
|
+
_CLEAR = text("DELETE FROM work_items")
|
|
10
|
+
_INSERT = text("INSERT INTO work_items (ref, title, source_order) VALUES (:ref, :title, :order)")
|
|
11
|
+
_CLAIMED = text(
|
|
12
|
+
"SELECT DISTINCT item.value FROM lanes, json_each(lanes.work_items) AS item "
|
|
13
|
+
"WHERE lanes.state != 'archived'"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
async def ready_work_items(connection: AsyncConnection) -> tuple[WorkItem, ...]:
|
|
18
|
+
return tuple(WorkItem(row.ref, row.title) for row in await connection.execute(_READY))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def replace_work_items(connection: AsyncConnection, items: tuple[WorkItem, ...]) -> None:
|
|
22
|
+
if items == await ready_work_items(connection):
|
|
23
|
+
return
|
|
24
|
+
await connection.execute(_CLEAR)
|
|
25
|
+
if items:
|
|
26
|
+
await connection.execute(
|
|
27
|
+
_INSERT,
|
|
28
|
+
[
|
|
29
|
+
{"ref": item.ref, "title": item.title, "order": index}
|
|
30
|
+
for index, item in enumerate(items)
|
|
31
|
+
],
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def claimed_work_items(connection: AsyncConnection) -> set[str]:
|
|
36
|
+
return {str(row.value) for row in await connection.execute(_CLAIMED)}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""A local, protected participant on a configured Switchboard relay."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
from mcp import ClientSession
|
|
13
|
+
from mcp.client.stdio import StdioServerParameters, stdio_client
|
|
14
|
+
from mcp.types import TextContent
|
|
15
|
+
|
|
16
|
+
from plotroom.core.actions import Action
|
|
17
|
+
from plotroom.core.bridge import record_inbound
|
|
18
|
+
from plotroom.core.lanes import infer_lane
|
|
19
|
+
from plotroom.core.ledger import Ledger
|
|
20
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
21
|
+
|
|
22
|
+
log = logging.getLogger("plotroom.switchboard")
|
|
23
|
+
NAME = "plotroom"
|
|
24
|
+
WAIT_SECONDS = 15
|
|
25
|
+
REGISTRATION_WAIT_SECONDS = 10
|
|
26
|
+
PINNED_SEND_TIMEOUT_SECONDS = 5
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
async def call_relay(
|
|
30
|
+
session: ClientSession, name: str, arguments: dict[str, Any], read_seconds: float = 5
|
|
31
|
+
) -> dict[str, Any]:
|
|
32
|
+
result = await session.call_tool(name, arguments, read_timeout_seconds=read_seconds)
|
|
33
|
+
if result.is_error:
|
|
34
|
+
raise ValueError(f"Switchboard {name} failed")
|
|
35
|
+
payload: Any = result.structured_content
|
|
36
|
+
if payload is None and result.content and isinstance(result.content[0], TextContent):
|
|
37
|
+
payload = json.loads(result.content[0].text)
|
|
38
|
+
if not isinstance(payload, dict):
|
|
39
|
+
raise ValueError(f"Switchboard {name} did not return an object")
|
|
40
|
+
return cast("dict[str, Any]", payload)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Switchboard:
|
|
44
|
+
def __init__(
|
|
45
|
+
self, ledger: Ledger, board: str, command: tuple[str, ...], senders: Mapping[str, str]
|
|
46
|
+
) -> None:
|
|
47
|
+
self._ledger = ledger
|
|
48
|
+
self._board = board
|
|
49
|
+
self._server = StdioServerParameters(
|
|
50
|
+
command=command[0],
|
|
51
|
+
args=list(command[1:]),
|
|
52
|
+
env={"SWITCHBOARD_BOARD": board, "SWITCHBOARD_AUTO": "0"},
|
|
53
|
+
)
|
|
54
|
+
self._senders = senders
|
|
55
|
+
self._ready = asyncio.Event()
|
|
56
|
+
self._session: ClientSession | None = None
|
|
57
|
+
|
|
58
|
+
async def run(self) -> None:
|
|
59
|
+
delay = 0.25
|
|
60
|
+
while True:
|
|
61
|
+
try:
|
|
62
|
+
# The child controls its diagnostic text. Keep message data out of daemon logs.
|
|
63
|
+
with open(os.devnull, "w", encoding="utf-8") as errlog: # noqa: ASYNC230
|
|
64
|
+
async with (
|
|
65
|
+
stdio_client(self._server, errlog=errlog) as (read, write),
|
|
66
|
+
ClientSession(read, write, read_timeout_seconds=10) as session,
|
|
67
|
+
):
|
|
68
|
+
await session.initialize()
|
|
69
|
+
registered = await call_relay(session, "register", {"name": NAME})
|
|
70
|
+
if registered.get("ok") is not True or registered.get("you") != NAME:
|
|
71
|
+
raise ValueError("Switchboard refused the protected address")
|
|
72
|
+
self._session = session
|
|
73
|
+
self._ready.set()
|
|
74
|
+
try:
|
|
75
|
+
while True:
|
|
76
|
+
await self.receive(session)
|
|
77
|
+
delay = 0.25
|
|
78
|
+
finally:
|
|
79
|
+
self._ready.clear()
|
|
80
|
+
self._session = None
|
|
81
|
+
except Exception:
|
|
82
|
+
log.warning(
|
|
83
|
+
"Switchboard receive unavailable, retrying",
|
|
84
|
+
extra={"project": self._ledger.project_id, "retry_seconds": delay},
|
|
85
|
+
)
|
|
86
|
+
await asyncio.sleep(delay)
|
|
87
|
+
delay = min(delay * 2, 30)
|
|
88
|
+
|
|
89
|
+
async def send(self, action: Action) -> None:
|
|
90
|
+
address, body = action.payload.get("to"), action.payload.get("body")
|
|
91
|
+
if not isinstance(address, str) or not address.strip() or not isinstance(body, str):
|
|
92
|
+
raise ValueError("Switchboard sends require a recipient and a message body")
|
|
93
|
+
address = address.strip()
|
|
94
|
+
async with asyncio.timeout(REGISTRATION_WAIT_SECONDS):
|
|
95
|
+
while (session := self._session) is None:
|
|
96
|
+
await self._ready.wait()
|
|
97
|
+
arguments = {
|
|
98
|
+
"to": address,
|
|
99
|
+
"body": json.dumps({"action_key": action.key, "body": body}, ensure_ascii=False),
|
|
100
|
+
"idempotency_key": action.key,
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async def submit() -> None:
|
|
104
|
+
response = await call_relay(session, "send", arguments)
|
|
105
|
+
if type(response.get("id")) is not int or response.get("to") != address:
|
|
106
|
+
raise ValueError("Switchboard did not accept the send")
|
|
107
|
+
|
|
108
|
+
lane, worker = action.payload.get("lane"), action.payload.get("worker")
|
|
109
|
+
if lane is None:
|
|
110
|
+
await submit()
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
async def submit_if_current(uow: UnitOfWork) -> None:
|
|
114
|
+
if await infer_lane(uow, worker=worker) == lane:
|
|
115
|
+
async with asyncio.timeout(PINNED_SEND_TIMEOUT_SECONDS):
|
|
116
|
+
await submit()
|
|
117
|
+
|
|
118
|
+
# Registration has already finished. Serialize only the bounded send with lane changes.
|
|
119
|
+
await self._ledger.run("system", submit_if_current)
|
|
120
|
+
|
|
121
|
+
async def receive(self, session: ClientSession) -> None:
|
|
122
|
+
batch = await call_relay(session, "wait", {"timeout_s": WAIT_SECONDS}, WAIT_SECONDS + 5)
|
|
123
|
+
messages = batch.get("messages")
|
|
124
|
+
if not isinstance(messages, list):
|
|
125
|
+
raise ValueError("Switchboard wait did not return a message list")
|
|
126
|
+
for message in cast("list[Any]", messages):
|
|
127
|
+
if not isinstance(message, dict):
|
|
128
|
+
raise ValueError("Switchboard returned a malformed message")
|
|
129
|
+
await self._receive_one(session, cast("dict[str, Any]", message))
|
|
130
|
+
|
|
131
|
+
async def _receive_one(self, session: ClientSession, message: dict[str, Any]) -> None:
|
|
132
|
+
message_id, sender, body, receipt = (
|
|
133
|
+
message.get(k) for k in ("id", "from", "body", "receipt")
|
|
134
|
+
)
|
|
135
|
+
if (
|
|
136
|
+
type(message_id) is not int
|
|
137
|
+
or message_id < 1
|
|
138
|
+
or not isinstance(sender, str)
|
|
139
|
+
or not sender
|
|
140
|
+
or not isinstance(body, str)
|
|
141
|
+
or not isinstance(receipt, str)
|
|
142
|
+
or not receipt
|
|
143
|
+
):
|
|
144
|
+
raise ValueError("Switchboard returned an invalid claim")
|
|
145
|
+
|
|
146
|
+
async def record(uow: UnitOfWork) -> None:
|
|
147
|
+
await record_inbound(uow, self._board, self._senders, message_id, sender, body)
|
|
148
|
+
|
|
149
|
+
await self._ledger.run("system", record)
|
|
150
|
+
acknowledged = await call_relay(session, "ack", {"id": message_id, "receipt": receipt})
|
|
151
|
+
if acknowledged.get("ok") is not True:
|
|
152
|
+
log.warning("Switchboard claim expired", extra={"project": self._ledger.project_id})
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""A deterministic project-local usage meter for tests and local fixtures."""
|
|
2
|
+
|
|
3
|
+
from plotroom.ports.usage_meter import UsageObservation
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class FixtureUsageMeter:
|
|
7
|
+
def __init__(self, readings: tuple[UsageObservation, ...] = ()) -> None:
|
|
8
|
+
self.readings = readings
|
|
9
|
+
|
|
10
|
+
async def observations(self) -> tuple[UsageObservation, ...]:
|
|
11
|
+
return self.readings
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Read the ready-to-start view of a local BMad repo ticket tree."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import contextlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import stat
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import tomllib
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, BinaryIO, cast
|
|
14
|
+
|
|
15
|
+
from plotroom.ports.work_items import MAX_WORK_ITEM_BODY_BYTES, WorkItem
|
|
16
|
+
|
|
17
|
+
_READER_TIMEOUT = 15.0
|
|
18
|
+
_FIND_OUTPUT_LIMIT = 2 * MAX_WORK_ITEM_BODY_BYTES
|
|
19
|
+
_UNKNOWN_REFERENCE = "no ticket matches "
|
|
20
|
+
_TICKET_ID = re.compile(r"^[0-9A-Za-z]+$")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TicketTreeError(ValueError):
|
|
24
|
+
"""The local source could not read the configured ticket tree."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _read_source_file(scope: Path, path: Path) -> str:
|
|
28
|
+
try:
|
|
29
|
+
parts = path.relative_to(scope).parts
|
|
30
|
+
if not parts or ".." in parts:
|
|
31
|
+
raise ValueError("not a ticket file")
|
|
32
|
+
directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
33
|
+
with contextlib.ExitStack() as stack:
|
|
34
|
+
directory = os.open(scope.anchor, directory_flags)
|
|
35
|
+
stack.callback(os.close, directory)
|
|
36
|
+
for part in (*scope.parts[1:], *parts[:-1]):
|
|
37
|
+
directory = os.open(part, directory_flags, dir_fd=directory)
|
|
38
|
+
stack.callback(os.close, directory)
|
|
39
|
+
fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory)
|
|
40
|
+
with open(fd, "rb") as file:
|
|
41
|
+
if not stat.S_ISREG(os.fstat(file.fileno()).st_mode):
|
|
42
|
+
raise ValueError("not a regular file")
|
|
43
|
+
content = file.read(MAX_WORK_ITEM_BODY_BYTES + 1)
|
|
44
|
+
if len(content) > MAX_WORK_ITEM_BODY_BYTES:
|
|
45
|
+
raise TicketTreeError("the ticket file exceeds the size limit")
|
|
46
|
+
return content.decode("utf-8")
|
|
47
|
+
except TicketTreeError:
|
|
48
|
+
raise
|
|
49
|
+
except (OSError, ValueError) as exc:
|
|
50
|
+
raise TicketTreeError(
|
|
51
|
+
"cannot read a regular UTF-8 ticket file in the configured tree"
|
|
52
|
+
) from exc
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _ticket_id(value: object) -> int | str | None:
|
|
56
|
+
# Match the trusted reader's numeric and lettered identifiers.
|
|
57
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
58
|
+
return value
|
|
59
|
+
if isinstance(value, str) and _TICKET_ID.match(value) and value not in ("true", "false"):
|
|
60
|
+
return int(value) if value.isdigit() else value
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _compact_body(document: str, ticket_id: int | str) -> str | None:
|
|
65
|
+
try:
|
|
66
|
+
# The BMad reader accepts a UTF-8 BOM and reads through universal newlines.
|
|
67
|
+
text = document.removeprefix("\ufeff").replace("\r\n", "\n").replace("\r", "\n")
|
|
68
|
+
entries = tomllib.loads(text).get("entry", [])
|
|
69
|
+
if not isinstance(entries, list):
|
|
70
|
+
raise ValueError("entry must be a list")
|
|
71
|
+
matches: list[dict[str, Any]] = []
|
|
72
|
+
for row in cast("list[Any]", entries):
|
|
73
|
+
if not isinstance(row, dict):
|
|
74
|
+
raise ValueError("entry must contain tables")
|
|
75
|
+
candidate = cast("dict[str, Any]", row)
|
|
76
|
+
if _ticket_id(candidate.get("id")) == ticket_id:
|
|
77
|
+
matches.append(candidate)
|
|
78
|
+
except ValueError as exc:
|
|
79
|
+
raise TicketTreeError("the compact ticket breakdown is invalid") from exc
|
|
80
|
+
if not matches:
|
|
81
|
+
return None
|
|
82
|
+
if len(matches) != 1:
|
|
83
|
+
raise TicketTreeError("the compact ticket breakdown has duplicate ids")
|
|
84
|
+
ticket = matches[0]
|
|
85
|
+
|
|
86
|
+
def string(field: str) -> str:
|
|
87
|
+
return str(ticket.get(field, ""))
|
|
88
|
+
|
|
89
|
+
def lines(field: str) -> list[str]:
|
|
90
|
+
values = ticket.get(field, [])
|
|
91
|
+
if not isinstance(values, list):
|
|
92
|
+
raise TicketTreeError(f"invalid compact ticket {field}")
|
|
93
|
+
return [str(value) for value in cast("list[Any]", values)]
|
|
94
|
+
|
|
95
|
+
body = f"# {string('title')}\n\n## Description\n\n{string('description')}\n\n"
|
|
96
|
+
body += f"## Requirements\n\nVerify: {string('verify')}\n"
|
|
97
|
+
if references := lines("references"):
|
|
98
|
+
body += "\n## References\n\n" + "".join(f"- {reference}\n" for reference in references)
|
|
99
|
+
notes = lines("notes")
|
|
100
|
+
if unknown := string("unknown"):
|
|
101
|
+
notes = [f"Unknown: {unknown}", *notes]
|
|
102
|
+
if notes:
|
|
103
|
+
body += "\n## Notes\n\n" + "".join(f"- {note}\n" for note in notes)
|
|
104
|
+
if len(body.encode("utf-8")) > MAX_WORK_ITEM_BODY_BYTES:
|
|
105
|
+
raise TicketTreeError("the compact ticket exceeds the size limit")
|
|
106
|
+
return body
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class BmadTicketTree:
|
|
110
|
+
"""Use the installed BMad reader so dependencies and plan state follow its rules.
|
|
111
|
+
|
|
112
|
+
The runner comes from a trusted BMad installation selected by the daemon operator.
|
|
113
|
+
Ticket files themselves are inputs to the read-only next command.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self, tree: Path, installation: Path, *, project_root: Path | None = None) -> None:
|
|
117
|
+
self.tree = tree.resolve()
|
|
118
|
+
self.installation = installation
|
|
119
|
+
self.reader = installation / "_bmad" / "method" / "scripts" / "tickets.py"
|
|
120
|
+
self.project_root = project_root
|
|
121
|
+
|
|
122
|
+
async def ready_items(self) -> tuple[WorkItem, ...]:
|
|
123
|
+
reader, root, tree = self._reader_paths()
|
|
124
|
+
with tempfile.TemporaryFile() as stdout:
|
|
125
|
+
code = await self._read(reader, root, stdout, ("next", str(tree)))
|
|
126
|
+
if code == 2:
|
|
127
|
+
raise TicketTreeError("the ticket tree must use BMad's repo store")
|
|
128
|
+
if code != 0:
|
|
129
|
+
raise TicketTreeError("the BMad reader could not read the ticket tree")
|
|
130
|
+
stdout.seek(0)
|
|
131
|
+
return self._parse(stdout)
|
|
132
|
+
|
|
133
|
+
async def body(self, ref: str) -> str | None:
|
|
134
|
+
reader, root, tree = self._reader_paths()
|
|
135
|
+
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
|
|
136
|
+
code = await self._read(reader, root, stdout, ("find", "--", str(tree), ref), stderr)
|
|
137
|
+
if code == 2:
|
|
138
|
+
raise TicketTreeError("the ticket tree must use BMad's repo store")
|
|
139
|
+
if code != 0:
|
|
140
|
+
stderr.seek(0)
|
|
141
|
+
try:
|
|
142
|
+
problem = json.loads(stderr.read(_FIND_OUTPUT_LIMIT)).get("error")
|
|
143
|
+
except AttributeError, ValueError:
|
|
144
|
+
problem = None
|
|
145
|
+
if isinstance(problem, str) and problem.startswith(_UNKNOWN_REFERENCE):
|
|
146
|
+
return None
|
|
147
|
+
raise TicketTreeError("the BMad reader could not find a unique ticket")
|
|
148
|
+
stdout.seek(0)
|
|
149
|
+
try:
|
|
150
|
+
packed = stdout.read(_FIND_OUTPUT_LIMIT + 1)
|
|
151
|
+
if len(packed) > _FIND_OUTPUT_LIMIT:
|
|
152
|
+
raise ValueError("find result exceeds the size limit")
|
|
153
|
+
ticket: dict[str, Any] = json.loads(packed)
|
|
154
|
+
value = ticket["story_file"]
|
|
155
|
+
if value is not None and not isinstance(value, str):
|
|
156
|
+
raise ValueError("invalid story file")
|
|
157
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
158
|
+
raise TicketTreeError("the BMad reader returned no ticket body reference") from exc
|
|
159
|
+
scope = tree.parent if tree.name == "tickets" else tree
|
|
160
|
+
if value is None:
|
|
161
|
+
plan = ticket.get("plan")
|
|
162
|
+
ticket_id = _ticket_id(ticket.get("id"))
|
|
163
|
+
if not isinstance(plan, str) or not plan or ticket_id is None:
|
|
164
|
+
raise TicketTreeError("the BMad reader returned no compact ticket location")
|
|
165
|
+
path = Path(plan).parent / "tickets.toml"
|
|
166
|
+
if not path.is_relative_to(scope):
|
|
167
|
+
return None
|
|
168
|
+
document = await asyncio.to_thread(_read_source_file, scope, path)
|
|
169
|
+
return _compact_body(document, ticket_id)
|
|
170
|
+
path = Path(value)
|
|
171
|
+
if not path.is_relative_to(scope):
|
|
172
|
+
return None
|
|
173
|
+
if path.suffix != ".md":
|
|
174
|
+
raise TicketTreeError("the BMad reader returned an invalid story file")
|
|
175
|
+
return await asyncio.to_thread(_read_source_file, scope, path)
|
|
176
|
+
|
|
177
|
+
def _reader_paths(self) -> tuple[Path, Path, Path]:
|
|
178
|
+
if not self.tree.is_dir():
|
|
179
|
+
raise TicketTreeError("configured ticket_tree directory does not exist")
|
|
180
|
+
tree = self.tree
|
|
181
|
+
root = self.project_root or next(
|
|
182
|
+
(p for p in (tree, *tree.parents) if (p / "_bmad").is_dir()), tree
|
|
183
|
+
)
|
|
184
|
+
root = root.resolve()
|
|
185
|
+
reader = self.reader.resolve()
|
|
186
|
+
if reader.is_relative_to(root) or not reader.is_file():
|
|
187
|
+
raise TicketTreeError("configure a trusted BMad reader outside the mirrored checkout")
|
|
188
|
+
return reader, root, tree
|
|
189
|
+
|
|
190
|
+
async def _read(
|
|
191
|
+
self,
|
|
192
|
+
reader: Path,
|
|
193
|
+
root: Path,
|
|
194
|
+
stdout: BinaryIO,
|
|
195
|
+
args: tuple[str, ...],
|
|
196
|
+
stderr: BinaryIO | None = None,
|
|
197
|
+
) -> int:
|
|
198
|
+
try:
|
|
199
|
+
process = await asyncio.create_subprocess_exec(
|
|
200
|
+
sys.executable,
|
|
201
|
+
"-I",
|
|
202
|
+
"-B",
|
|
203
|
+
str(reader),
|
|
204
|
+
"--project-root",
|
|
205
|
+
str(root),
|
|
206
|
+
*args,
|
|
207
|
+
stdout=stdout,
|
|
208
|
+
stderr=asyncio.subprocess.DEVNULL if stderr is None else stderr,
|
|
209
|
+
cwd=self.installation,
|
|
210
|
+
)
|
|
211
|
+
except OSError as exc:
|
|
212
|
+
raise TicketTreeError("cannot start the installed BMad reader") from exc
|
|
213
|
+
try:
|
|
214
|
+
async with asyncio.timeout(_READER_TIMEOUT):
|
|
215
|
+
await process.wait()
|
|
216
|
+
except TimeoutError as exc:
|
|
217
|
+
raise TicketTreeError("the BMad reader timed out") from exc
|
|
218
|
+
finally:
|
|
219
|
+
if process.returncode is None:
|
|
220
|
+
with contextlib.suppress(ProcessLookupError):
|
|
221
|
+
process.kill()
|
|
222
|
+
await process.wait()
|
|
223
|
+
assert process.returncode is not None
|
|
224
|
+
return process.returncode
|
|
225
|
+
|
|
226
|
+
def _parse(self, stdout: BinaryIO) -> tuple[WorkItem, ...]:
|
|
227
|
+
try:
|
|
228
|
+
view: dict[str, Any] = json.load(stdout)
|
|
229
|
+
if view["store"] != "repo":
|
|
230
|
+
raise TicketTreeError("the ticket tree must use BMad's repo store")
|
|
231
|
+
items: dict[str, WorkItem] = {}
|
|
232
|
+
for row in cast("list[dict[str, Any]]", view["ready_to_start"]):
|
|
233
|
+
ref, title = row["ref"], row["title"]
|
|
234
|
+
if (
|
|
235
|
+
not isinstance(ref, str)
|
|
236
|
+
or not ref
|
|
237
|
+
or not isinstance(title, str)
|
|
238
|
+
or ref in items
|
|
239
|
+
):
|
|
240
|
+
raise ValueError("invalid or duplicate work item")
|
|
241
|
+
items[ref] = WorkItem(ref, title)
|
|
242
|
+
return tuple(items.values())
|
|
243
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
244
|
+
raise TicketTreeError("the BMad reader returned no ready-to-start view") from exc
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
async def read_ticket_tree(
|
|
248
|
+
installation: Path, tree: Path, project_root: Path
|
|
249
|
+
) -> tuple[WorkItem, ...]:
|
|
250
|
+
return await BmadTicketTree(tree, installation, project_root=project_root).ready_items()
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
async def read_ticket_body(
|
|
254
|
+
installation: Path, tree: Path, project_root: Path, ref: str
|
|
255
|
+
) -> str | None:
|
|
256
|
+
return await BmadTicketTree(tree, installation, project_root=project_root).body(ref)
|