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,349 @@
1
+ """Read the clerk's Markdown templates as data for the running local daemon."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import os
10
+ import re
11
+ import sys
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ from mcp.client.client import Client
17
+ from mcp.client.stdio import StdioServerParameters
18
+ from mcp_types import TextContent
19
+
20
+ if TYPE_CHECKING:
21
+ from plotroom.core.clerk_import import PullImportRow, SkipImportRow, TriggerImportRow
22
+
23
+ log = logging.getLogger("plotroom")
24
+
25
+ _LINE_END = re.compile(r"\r\n?|\n")
26
+ _HEADING = re.compile(r" {0,3}##[ \t]+(.+?)[ \t]*")
27
+ _COMMENT_START = re.compile(r" {0,3}<!--")
28
+ _FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
29
+ _LABEL = re.compile(r"(T[0-9]+):[ \t]*(.*)")
30
+ _PR_CONDITION = re.compile(
31
+ r"#([0-9]+) merges(?: \((?:tell a waiting lane|the coordinator decides what follows|"
32
+ r"a lane whose post-merge list is already empty)\))?"
33
+ )
34
+ _BRANCH_CONDITION = re.compile(r"branch `([^`<>]+)` opens a PR that merges")
35
+ _FIRED = re.compile(r"FIRED ([0-9]{4}-[0-9]{2}-[0-9]{2}[ T][0-9:.+Z-]+) ([0-9a-fA-F]{7,40})")
36
+ _MESSAGE = re.compile(r'- Message `([^`]+)`:[ \t]*"(.+)"')
37
+ _NOTIFY = re.compile(r'- Tell the coordinator:[ \t]*"(.+?)"( Don\'t message the lane\.)?')
38
+ _ARCHIVE_OWNER = re.compile(r'- Owner: [^`]+ `[^`]+`\. Its post-merge list is "none"\.')
39
+ _TRIGGER_TITLE = "# Clerk triggers"
40
+ _LEDGER_TITLE = re.compile(r"# Clerk ledger: ([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)")
41
+ _OPEN_HEADING = re.compile(r"open prs(?:[ \t]+#+)?", re.IGNORECASE)
42
+ _OPEN_HEADER = ("pr", "owner (lane)", "kind", "channel", "state", "after merge")
43
+ _SKIP_HEADER = ("pr", "why, and who asked")
44
+
45
+
46
+ def _sections(text: str) -> list[tuple[str, list[str]]]:
47
+ sections: list[tuple[str, list[str]]] = []
48
+ fence = ""
49
+ comment = False
50
+ for line in _LINE_END.split(text):
51
+ if not fence and (comment or _COMMENT_START.match(line)):
52
+ # Never treat heading-like lines inside Markdown comments as live records.
53
+ rest = line
54
+ while True:
55
+ if comment:
56
+ _, close, rest = rest.partition("-->")
57
+ if not close:
58
+ break
59
+ comment = False
60
+ _, start, rest = rest.partition("<!--")
61
+ if not start:
62
+ break
63
+ comment = True
64
+ continue
65
+ marker = _FENCE.fullmatch(line)
66
+ if marker is not None:
67
+ delimiter, rest = marker.groups()
68
+ if not fence:
69
+ if delimiter.startswith("~") or "`" not in rest:
70
+ fence = delimiter
71
+ elif delimiter.startswith(fence) and not rest.strip(" \t"):
72
+ fence = ""
73
+ heading = _HEADING.fullmatch(line) if not (fence or marker) else None
74
+ if heading is not None:
75
+ sections.append((heading[1], []))
76
+ elif sections:
77
+ sections[-1][1].append(line)
78
+ return sections
79
+
80
+
81
+ def _document_title(text: str) -> str:
82
+ line = next((line for line in _LINE_END.split(text) if line.strip(" \t")), "")
83
+ title = line.lstrip(" ")
84
+ return title.rstrip(" \t") if len(line) - len(title) <= 3 else ""
85
+
86
+
87
+ def _number(text: str) -> int | None:
88
+ if len(text) > 19 or not text.isascii() or not text.isdecimal():
89
+ return None
90
+ number = int(text)
91
+ return number if 0 < number <= 2**63 - 1 else None
92
+
93
+
94
+ def _predicate(condition: str) -> dict[str, Any] | None:
95
+ if (match := _PR_CONDITION.fullmatch(condition)) and (pr := _number(match[1])):
96
+ return {"pr_merged": {"number": pr}}
97
+ if (match := _BRANCH_CONDITION.fullmatch(condition)) and match[1].strip():
98
+ return {"pr_merged": {"branch_glob": match[1]}}
99
+ return None
100
+
101
+
102
+ def _fired_marker(line: str) -> bool:
103
+ if line.startswith("- "):
104
+ line = line[2:]
105
+ for wrapper in ("`", "**"):
106
+ if line.startswith(wrapper) and line.endswith(wrapper):
107
+ line = line[len(wrapper) : -len(wrapper)]
108
+ break
109
+ match = _FIRED.fullmatch(line)
110
+ if match is None:
111
+ return False
112
+ try:
113
+ datetime.fromisoformat(match[1])
114
+ except ValueError:
115
+ return False
116
+ return True
117
+
118
+
119
+ def _exact_trigger(row: TriggerImportRow, condition: str, body: list[str]) -> None:
120
+ predicate = _predicate(condition)
121
+ if predicate is None:
122
+ return
123
+ fired = False
124
+ channel = None
125
+ message = None
126
+ notify = False
127
+ owner = False
128
+ for original in body:
129
+ line = original.rstrip()
130
+ if not line:
131
+ continue
132
+ if not fired and _fired_marker(line):
133
+ fired = True
134
+ elif message is None and (match := _MESSAGE.fullmatch(line)):
135
+ channel, message = match.groups()
136
+ elif message is None and not notify and (match := _NOTIFY.fullmatch(line)):
137
+ if bool(match[2]) != owner:
138
+ return
139
+ message = match[1]
140
+ notify = True
141
+ elif not notify and channel is not None and line == "- Tell the coordinator.":
142
+ notify = True
143
+ elif not owner and message is None and _ARCHIVE_OWNER.fullmatch(line):
144
+ owner = True
145
+ else:
146
+ return
147
+ if not message or not message.strip() or (owner and channel is not None):
148
+ return
149
+ row.update(predicate=predicate, text=message, channel=channel, notify=notify, fired=fired)
150
+
151
+
152
+ def parse_triggers(text: str) -> list[TriggerImportRow]:
153
+ """Recognize complete template entries, retaining unsupported sections for binding."""
154
+ rows: dict[str, TriggerImportRow] = {}
155
+ for heading, body in _sections(text):
156
+ source = ("## " + heading + "\n" + "\n".join(body)).rstrip()
157
+ match = _LABEL.fullmatch(heading)
158
+ label = match[1] if match else "unrecognized-" + hashlib.sha256(source.encode()).hexdigest()
159
+ row: TriggerImportRow = {
160
+ "label": label,
161
+ "source": source,
162
+ "predicate": None,
163
+ "text": None,
164
+ "channel": None,
165
+ "notify": False,
166
+ "fired": False,
167
+ }
168
+ if match is not None:
169
+ _exact_trigger(row, match[2], body)
170
+ if label in rows and rows[label] != row:
171
+ raise ValueError(f"triggers template contains conflicting entries for {label}")
172
+ rows[label] = row
173
+ if not rows and _document_title(text) != _TRIGGER_TITLE:
174
+ raise ValueError("expected a clerk triggers template")
175
+ return list(rows.values())
176
+
177
+
178
+ def _cells(line: str) -> tuple[str, ...]:
179
+ if not re.match(r" {0,3}\|", line):
180
+ return ()
181
+ line = line.strip()
182
+ if not line.endswith("|"):
183
+ return ()
184
+ # Keep escaped pipes in prose and skip the leading/trailing table delimiters.
185
+ protected = re.split(r"(\\\\|\\\|)", line[1:-1])
186
+ parts: list[str] = [""]
187
+ for index, segment in enumerate(protected):
188
+ if index % 2:
189
+ parts[-1] += segment[1:]
190
+ continue
191
+ head, *rest = segment.split("|")
192
+ parts[-1] += head
193
+ parts.extend(rest)
194
+ return tuple(value.strip() for value in parts)
195
+
196
+
197
+ def _table(body: list[str], header: tuple[str, ...]) -> list[tuple[str, ...]]:
198
+ start = next((index for index, line in enumerate(body) if line.strip()), None)
199
+ if start is None:
200
+ return []
201
+ names = _cells(body[start])
202
+ separator = _cells(body[start + 1]) if start + 1 < len(body) else ()
203
+ if (
204
+ tuple(name.lower() for name in names) != header
205
+ or len(separator) != len(header)
206
+ or any(not re.fullmatch(r":?-{3,}:?", value) for value in separator)
207
+ ):
208
+ raise ValueError(f"unexpected Markdown table columns or separator for {', '.join(header)}")
209
+ rows: list[tuple[str, ...]] = []
210
+ for line in body[start + 2 :]:
211
+ if not line.strip():
212
+ continue
213
+ cells = _cells(line)
214
+ if len(cells) != len(header):
215
+ raise ValueError(f"unexpected content or row width in table for {', '.join(header)}")
216
+ rows.append(cells)
217
+ return rows
218
+
219
+
220
+ def _unquote(text: str) -> str:
221
+ if len(text) > 1 and text[0] == text[-1] == "`":
222
+ return text[1:-1]
223
+ return text
224
+
225
+
226
+ def _pull_number(cell: str) -> int:
227
+ value = _unquote(cell)
228
+ if not value.startswith("#") or (number := _number(value[1:])) is None:
229
+ raise ValueError("expected a positive #PR number in the clerk ledger")
230
+ return number
231
+
232
+
233
+ def parse_ledger(text: str) -> tuple[str, list[PullImportRow], list[SkipImportRow]]:
234
+ """Read the two supported tables. Flake receipts and historical audit stay in the source."""
235
+ match = _LEDGER_TITLE.fullmatch(_document_title(text))
236
+ if match is None:
237
+ raise ValueError("expected a clerk ledger with an owner/repository title")
238
+ pulls: dict[int, PullImportRow] = {}
239
+ skips: dict[int, SkipImportRow] = {}
240
+ sections = _sections(text)
241
+ if not any(
242
+ heading.lower() == "open prs"
243
+ or heading.lower() == "skip list"
244
+ or heading.lower().startswith("skip list (")
245
+ for heading, _ in sections
246
+ ):
247
+ raise ValueError("expected the clerk ledger template")
248
+ # A heading with closing hashes contributes to ambiguity without changing what gets imported.
249
+ open_sections = [body for heading, body in sections if _OPEN_HEADING.fullmatch(heading)]
250
+ if len(open_sections) > 1 and any(
251
+ (cells := _cells(line)) and cells[0].casefold() == "none"
252
+ for body in open_sections
253
+ for line in body
254
+ ):
255
+ raise ValueError("the empty Open PRs marker requires a single Open PRs table")
256
+ for heading, body in sections:
257
+ name = heading.lower()
258
+ if name == "open prs":
259
+ rows = _table(body, _OPEN_HEADER)
260
+ if rows and rows[0][0].casefold() == "none":
261
+ if len(rows) != 1 or any(rows[0][1:]):
262
+ raise ValueError(
263
+ "the empty Open PRs marker requires one table with no other data"
264
+ )
265
+ continue
266
+ for pr, owner, _, channel, state, after_merge in rows:
267
+ if pr.lower() == "(soon)":
268
+ continue
269
+ number = _pull_number(pr)
270
+ row: PullImportRow = {
271
+ "pr": number,
272
+ "worker": _unquote(owner),
273
+ "channel": _unquote(channel),
274
+ "state": _unquote(state),
275
+ "after_merge": after_merge,
276
+ }
277
+ if number in pulls and pulls[number] != row:
278
+ raise ValueError(f"ledger has conflicting open rows for #{number}")
279
+ pulls[number] = row
280
+ elif name == "skip list" or name.startswith("skip list ("):
281
+ for pr, reason in _table(body, _SKIP_HEADER):
282
+ number = _pull_number(pr)
283
+ row_skip: SkipImportRow = {"pr": number, "reason": reason}
284
+ if number in skips and skips[number] != row_skip:
285
+ raise ValueError(f"ledger has conflicting skip rows for #{number}")
286
+ skips[number] = row_skip
287
+ return match[1].lower(), list(pulls.values()), list(skips.values())
288
+
289
+
290
+ async def _submit(config: Path | None, token_id: str | None, args: dict[str, Any]) -> int:
291
+ command = ["-m", "plotroom", "connect", "--stdio", "--existing-local"]
292
+ for flag, value in (("--config", config), ("--token-id", token_id)):
293
+ if value is not None:
294
+ command.extend((flag, str(value)))
295
+ env = os.environ.copy()
296
+ env.pop("PLOTROOM_TOKEN", None)
297
+ env.pop("PLOTROOM_URL", None)
298
+ proxy = StdioServerParameters(command=sys.executable, args=command, env=env)
299
+ async with Client(proxy, mode="legacy") as client:
300
+ response = await client.call_tool("clerk_import", args)
301
+ first = next(iter(response.content), None)
302
+ if response.is_error or not isinstance(first, TextContent):
303
+ log.error("local import server did not accept the request")
304
+ return 1
305
+ result = json.loads(first.text)
306
+ if not result["ok"]:
307
+ log.error("local import refused", extra={"reason": result["error"]["message"]})
308
+ return 1
309
+ print(json.dumps(result["data"]))
310
+ return 0
311
+
312
+
313
+ def run_import(
314
+ config: Path | None, token_id: str | None, triggers: Path | None, ledger: Path | None
315
+ ) -> int:
316
+ if triggers is None and ledger is None:
317
+ log.error("import requires --triggers, --ledger, or both")
318
+ return 2
319
+ try:
320
+ trigger_rows: list[TriggerImportRow] = []
321
+ if triggers is not None:
322
+ source = triggers.read_text(encoding="utf-8-sig")
323
+ if _document_title(source) != _TRIGGER_TITLE:
324
+ raise ValueError("expected a clerk triggers file with its template title")
325
+ trigger_rows = parse_triggers(source)
326
+ repository, pulls, skips = (
327
+ parse_ledger(ledger.read_text(encoding="utf-8-sig")) if ledger else (None, [], [])
328
+ )
329
+ except (OSError, UnicodeError, ValueError) as exc:
330
+ log.error("cannot read clerk templates", extra={"reason": str(exc)})
331
+ return 2
332
+ try:
333
+ return asyncio.run(
334
+ _submit(
335
+ config,
336
+ token_id,
337
+ {
338
+ "triggers": trigger_rows,
339
+ "pulls": pulls,
340
+ "skips": skips,
341
+ "ledger_repository": repository,
342
+ },
343
+ )
344
+ )
345
+ except KeyboardInterrupt:
346
+ return 130
347
+ except Exception as exc:
348
+ log.error("local import connection failed", extra={"reason": type(exc).__name__})
349
+ return 1
plotroom/app/cli.py ADDED
@@ -0,0 +1,290 @@
1
+ """The ``plotroom`` command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import contextlib
8
+ import json
9
+ import logging
10
+ import os
11
+ import sys
12
+ from collections.abc import Sequence
13
+ from functools import partial
14
+ from pathlib import Path
15
+
16
+ from plotroom.app.clerk_import import run_import
17
+ from plotroom.app.config import ConfigError, load_config
18
+ from plotroom.app.lock import LockError
19
+ from plotroom.app.logging import setup_logging
20
+ from plotroom.app.tokens import LocalCleanupError, TokenError, TokenRegistry, select_local_token
21
+
22
+ EXIT_FAILURE = 1
23
+ EXIT_CONFIG = 2
24
+ EXIT_LOCKED = 4 # not 3: uvicorn exits 3 when it cannot start, e.g. when its port is taken
25
+
26
+ log = logging.getLogger("plotroom")
27
+
28
+
29
+ DEFAULT_START_TIMEOUT = 20.0
30
+
31
+
32
+ def _positive_seconds(text: str) -> float:
33
+ try:
34
+ seconds = float(text)
35
+ except ValueError:
36
+ raise argparse.ArgumentTypeError(f"{text!r} is not a number of seconds") from None
37
+ if not 0 < seconds < float("inf"):
38
+ raise argparse.ArgumentTypeError("must be a positive number of seconds")
39
+ return seconds
40
+
41
+
42
+ def _parser() -> argparse.ArgumentParser:
43
+ parser = argparse.ArgumentParser(prog="plotroom")
44
+ commands = parser.add_subparsers(dest="command", required=True)
45
+
46
+ serve = commands.add_parser("serve", help="own a data directory and serve the tools over HTTP")
47
+ serve.add_argument("--config", type=Path, help="TOML config file (default: PLOTROOM_CONFIG)")
48
+ serve.add_argument(
49
+ "--log-file",
50
+ type=Path,
51
+ metavar="PATH",
52
+ help="write the log to this size-rotating file instead of stdout",
53
+ )
54
+
55
+ connect = commands.add_parser("connect", help="reach a running server")
56
+ connect.add_argument("--stdio", action="store_true", required=True, help="proxy stdio to HTTP")
57
+ connect.add_argument("--url", help="the server's MCP endpoint (default: from the config)")
58
+ connect.add_argument("--config", type=Path, help="TOML config file (default: PLOTROOM_CONFIG)")
59
+ connect.add_argument("--token-id", help="local token ID (default: PLOTROOM_TOKEN_ID)")
60
+ connect.add_argument(
61
+ "--start-timeout",
62
+ type=_positive_seconds,
63
+ default=DEFAULT_START_TIMEOUT,
64
+ metavar="SECONDS",
65
+ help="how long to wait for a daemon started on demand (default: %(default)s)",
66
+ )
67
+ connect.add_argument("--existing-local", action="store_true", help=argparse.SUPPRESS)
68
+ command = commands.add_parser("import", help="import a clerk template into the local daemon")
69
+ command.add_argument("--config", type=Path, help="TOML config file (default: PLOTROOM_CONFIG)")
70
+ command.add_argument(
71
+ "--token-id", help="local orchestrator token ID (default: PLOTROOM_TOKEN_ID)"
72
+ )
73
+ command.add_argument("--triggers", type=Path, help="copy of the clerk triggers.md file")
74
+ command.add_argument("--ledger", type=Path, help="copy of the clerk ledger.md file")
75
+ watch = commands.add_parser("watch", help="wait until the next visible board change")
76
+ watch.add_argument("--config", type=Path, help="TOML config file (default: PLOTROOM_CONFIG)")
77
+ watch.add_argument("--token-id", help="local token ID (default: PLOTROOM_TOKEN_ID)")
78
+ watch.add_argument("--url", help="MCP endpoint (default: the local daemon)")
79
+ watch.add_argument("--cursor", type=int, help="resume after this board sequence")
80
+ bridge = commands.add_parser("bridge", help="relay local Switchboard mail to an MCP server")
81
+ bridge.add_argument("--url", required=True, help="server MCP endpoint")
82
+ bridge.add_argument("--board", required=True, help="the configured Switchboard board")
83
+ bridge.add_argument("--mode", choices=("auto", "legacy"), default="auto")
84
+ bridge.add_argument("--relay-command", nargs=argparse.REMAINDER, default=("switchboard-relay",))
85
+ token = commands.add_parser("token", help="manage credentials without a running daemon")
86
+ token_commands = token.add_subparsers(dest="action", required=True)
87
+ issue = token_commands.add_parser("issue", help="issue a token and print it once as JSON")
88
+ issue.add_argument("--project", required=True, help="project ID from the server config")
89
+ issue.add_argument(
90
+ "--role", required=True, help="orchestrator, clerk, worker:<name>, drain, bridge"
91
+ )
92
+ revoke = token_commands.add_parser("revoke", help="revoke a token by its public ID")
93
+ revoke.add_argument("token_id", help="the public ID returned at issue")
94
+ for action in (issue, revoke):
95
+ action.add_argument(
96
+ "--config", type=Path, help="TOML config file (default: PLOTROOM_CONFIG)"
97
+ )
98
+ action.add_argument(
99
+ "--no-local", action="store_true", help="skip the local credentials file"
100
+ )
101
+ return parser
102
+
103
+
104
+ def main(argv: Sequence[str] | None = None) -> int:
105
+ args = _parser().parse_args(argv)
106
+ if args.command == "serve":
107
+ return _serve(args.config, args.log_file)
108
+ setup_logging(sys.stderr) # stdout is the protocol channel
109
+ if args.command == "token":
110
+ return _token(args)
111
+ if args.command == "watch":
112
+ return _watch(args.url, args.config, args.token_id, args.cursor)
113
+ if args.command == "bridge":
114
+ from plotroom.app.bridge import run_bridge
115
+
116
+ return run_bridge(args.url, args.board, args.mode, args.relay_command)
117
+ if args.command == "import":
118
+ return run_import(args.config, args.token_id, args.triggers, args.ledger)
119
+ return _connect(
120
+ args.url, args.config, args.start_timeout, args.token_id, existing_local=args.existing_local
121
+ )
122
+
123
+
124
+ def _token(args: argparse.Namespace) -> int:
125
+ try:
126
+ issuing = args.action == "issue"
127
+ config = load_config(args.config, os.environ, require_projects=issuing)
128
+ registry = TokenRegistry(config.data_dir)
129
+ if issuing:
130
+ if args.project not in config.projects:
131
+ raise TokenError("the selected project is not configured")
132
+ try:
133
+ issued = registry.issue(args.project, args.role, local=not args.no_local)
134
+ except ValueError:
135
+ raise TokenError(
136
+ "token role must be orchestrator, clerk, worker:<name>, drain or bridge"
137
+ ) from None
138
+ print(json.dumps({"token_id": issued.token_id, "token": issued.bearer}))
139
+ else:
140
+ registry.revoke(args.token_id, local=not args.no_local)
141
+ except LocalCleanupError as exc:
142
+ invalid = isinstance(exc.failure, TokenError)
143
+ reason = str(exc.failure) if invalid else "cannot update the local token store"
144
+ log.error(
145
+ "%s",
146
+ exc,
147
+ extra={
148
+ "reason": reason,
149
+ "hint": "retry the same revoke command after fixing the local store",
150
+ },
151
+ )
152
+ return EXIT_CONFIG if invalid else EXIT_FAILURE
153
+ except (ConfigError, TokenError) as exc:
154
+ log.error("cannot manage token", extra={"reason": str(exc)})
155
+ return EXIT_CONFIG
156
+ except OSError as exc:
157
+ log.error("cannot write token files", extra={"reason": exc.strerror})
158
+ return EXIT_FAILURE
159
+ return 0
160
+
161
+
162
+ def _serve(config_path: Path | None, log_file: Path | None) -> int:
163
+ from plotroom.app.portfile import START_DIRECTORY_ENV
164
+ from plotroom.app.serve import Daemon
165
+
166
+ # The limits come from the config, so it is read before logging is set up; until then, and when
167
+ # it cannot be read, errors go to a plain stream handler (stderr is the daemon's own file).
168
+ setup_logging(sys.stdout if log_file is None else sys.stderr)
169
+ try:
170
+ config = load_config(config_path, os.environ)
171
+ except ConfigError as exc:
172
+ log.error("invalid configuration", extra={"reason": str(exc)})
173
+ return EXIT_CONFIG
174
+ if log_file is not None:
175
+ try:
176
+ setup_logging(file=log_file, max_bytes=config.log_max_bytes, backups=config.log_backups)
177
+ except OSError as exc:
178
+ log.error("cannot open the log file", extra={"path": str(log_file), "reason": str(exc)})
179
+ return EXIT_FAILURE
180
+ try:
181
+ daemon = Daemon(config, expected_directory=os.environ.get(START_DIRECTORY_ENV))
182
+ asyncio.run(daemon.run_as_service())
183
+ except ConfigError as exc:
184
+ log.error("invalid configuration", extra={"reason": str(exc)})
185
+ return EXIT_CONFIG
186
+ except LockError as exc:
187
+ # The winner owns the log file: a loser must not roll or delete it through its own handler.
188
+ setup_logging(sys.stderr)
189
+ log.error("data directory is locked", extra={"reason": str(exc)})
190
+ return EXIT_LOCKED
191
+ except KeyboardInterrupt:
192
+ pass
193
+ except Exception:
194
+ log.exception("serve failed")
195
+ return EXIT_FAILURE
196
+ return 0
197
+
198
+
199
+ def _watch(url: str | None, config: Path | None, token_id: str | None, cursor: int | None) -> int:
200
+ from mcp.client.client import Client
201
+ from mcp.client.stdio import StdioServerParameters
202
+ from mcp_types import TextContent
203
+
204
+ args = ["-m", "plotroom", "connect", "--stdio"]
205
+ for flag, value in (("--url", url), ("--config", config), ("--token-id", token_id)):
206
+ if value is not None:
207
+ args.extend((flag, str(value)))
208
+
209
+ async def watch() -> int:
210
+ position = cursor
211
+ proxy = StdioServerParameters(command=sys.executable, args=args, env=os.environ.copy())
212
+ async with Client(proxy, mode="legacy") as client:
213
+ while True:
214
+ response = await client.call_tool(
215
+ "wait", {} if position is None else {"cursor": position}
216
+ )
217
+ first = next(iter(response.content), None)
218
+ if not isinstance(first, TextContent):
219
+ raise ValueError("wait returned no JSON result")
220
+ result = json.loads(first.text)
221
+ if not result["ok"]:
222
+ log.error("wait failed", extra={"reason": result["error"]["message"]})
223
+ return EXIT_FAILURE
224
+ data = result["data"]
225
+ position = int(data["cursor"])
226
+ if data["item"] is not None:
227
+ print(json.dumps(data))
228
+ return 0
229
+
230
+ try:
231
+ return asyncio.run(watch())
232
+ except KeyboardInterrupt:
233
+ return 130
234
+ except Exception as exc:
235
+ log.error("watch connection failed", extra={"reason": type(exc).__name__})
236
+ return EXIT_FAILURE
237
+
238
+
239
+ def _connect(
240
+ url: str | None,
241
+ config_path: Path | None,
242
+ start_timeout: float,
243
+ token_id: str | None,
244
+ *,
245
+ existing_local: bool = False,
246
+ ) -> int:
247
+ from plotroom.adapters.mcp.proxy import EndpointError, StdioProxy, UpstreamStartError
248
+ from plotroom.app.daemon_start import DaemonLocation, ensure_daemon, require_daemon
249
+
250
+ env = os.environ.copy()
251
+ target = url or env.get("PLOTROOM_URL")
252
+ bearer = env.get("PLOTROOM_TOKEN")
253
+ token_id = token_id or env.get("PLOTROOM_TOKEN_ID")
254
+ try:
255
+ if existing_local and (target is not None or bearer is not None):
256
+ raise TokenError("this connection requires a locally stored token and daemon")
257
+ if token_id is not None and (target is not None or bearer is not None):
258
+ raise TokenError("--token-id is for locally stored credentials and config-derived URLs")
259
+ if target is not None:
260
+ proxy = StdioProxy(target, bearer=bearer)
261
+ else:
262
+ if config_path is not None:
263
+ config_path = config_path.resolve()
264
+ elif path := env.get("PLOTROOM_CONFIG"):
265
+ env["PLOTROOM_CONFIG"] = str(Path(path).expanduser().resolve())
266
+ config = load_config(config_path, env, require_projects=False)
267
+ location = DaemonLocation(config)
268
+ if bearer is None:
269
+ bearer = select_local_token(config.data_dir, token_id)
270
+ if bearer is not None and location.identity is None:
271
+ raise TokenError("the local token's data directory no longer exists")
272
+ if existing_local and bearer is None:
273
+ raise TokenError("no local credential is available for import")
274
+ ensure = (
275
+ partial(require_daemon, location, within=start_timeout)
276
+ if existing_local
277
+ else partial(ensure_daemon, location, config_path, env=env, wait=start_timeout)
278
+ )
279
+ proxy = StdioProxy(
280
+ config.url,
281
+ ensure=ensure,
282
+ bearer=bearer,
283
+ current_endpoint=location.current_endpoint,
284
+ )
285
+ except (ConfigError, EndpointError, TokenError, UpstreamStartError, OSError) as exc:
286
+ log.error("invalid connection configuration", extra={"reason": str(exc)})
287
+ return EXIT_CONFIG
288
+ with contextlib.suppress(KeyboardInterrupt, BrokenPipeError):
289
+ asyncio.run(proxy.run())
290
+ return 0
plotroom/app/clock.py ADDED
@@ -0,0 +1,12 @@
1
+ """The system ``Clock``: the one place the server reads the time."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, datetime
6
+
7
+
8
+ class SystemClock:
9
+ """Implements ``plotroom.ports.Clock`` with the wall clock, in UTC."""
10
+
11
+ def now(self) -> datetime:
12
+ return datetime.now(UTC)