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
plotroom/app/config.py ADDED
@@ -0,0 +1,984 @@
1
+ """Configuration: one TOML file plus ``PLOTROOM_*`` environment overrides, and the project registry.
2
+
3
+ Tool credentials (AD-12) are never read here; they are named ``PLOTROOM_<PROJECT>_<NAME>`` and
4
+ read by the adapter that needs them, so the override names below are a closed list.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import tomllib
11
+ from collections.abc import Mapping
12
+ from dataclasses import dataclass, field
13
+ from datetime import datetime, timedelta
14
+ from pathlib import Path
15
+ from typing import Any, cast
16
+
17
+ import httpx
18
+
19
+ from plotroom.adapters.claude_desktop import SESSION_ID
20
+ from plotroom.adapters.github import (
21
+ GITHUB_API,
22
+ RECONCILE_EVERY,
23
+ github_secret_name,
24
+ is_github_api_url,
25
+ )
26
+ from plotroom.adapters.github.ticket_tree import validate_tree_path
27
+ from plotroom.adapters.openrouter import OpenRouterRun
28
+ from plotroom.core.briefs import BriefSettings
29
+ from plotroom.core.events import LedgerError, format_time
30
+ from plotroom.core.github import valid_git_sha
31
+ from plotroom.core.kodus_review import KodusReviewPolicy, OpeningHeadAttestation
32
+ from plotroom.core.merge_gate import GatePolicy
33
+ from plotroom.core.roles import role_family
34
+ from plotroom.core.routing import validate_route_label
35
+ from plotroom.core.run_reports import validate_identity
36
+ from plotroom.core.snapshot import DEFAULT_SNAPSHOT_BUDGET, MIN_BOARD_BUDGET
37
+ from plotroom.core.trigger_actions import DeliveryRoute
38
+ from plotroom.ports.search import EmbeddingModel
39
+
40
+ DEFAULT_HOST = "127.0.0.1"
41
+ DEFAULT_PORT = 8765
42
+ DEFAULT_ALLOWED_HOSTS = ("localhost:*", "127.0.0.1:*", "[::1]:*")
43
+ DEFAULT_LOG_MAX_BYTES = 10 * 1024 * 1024
44
+ DEFAULT_LOG_BACKUPS = 5
45
+
46
+ _WILDCARD_TO_LOOPBACK = {"0.0.0.0": "127.0.0.1", "::": "::1"} # noqa: S104
47
+ _SLUG = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$")
48
+ _REPOSITORY = re.compile(r"[A-Za-z0-9-]+/[A-Za-z0-9_.-]+")
49
+ _WORKFLOW = re.compile(r"[A-Za-z0-9_.-]+\.ya?ml|[1-9][0-9]{0,18}")
50
+ _GITHUB_LOGIN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?")
51
+ _TOP_LEVEL_KEYS = {
52
+ "data_dir",
53
+ "backup_dir",
54
+ "backup_retain",
55
+ "host",
56
+ "port",
57
+ "allowed_hosts",
58
+ "projects",
59
+ "log_max_bytes",
60
+ "log_backups",
61
+ "snapshot_budget",
62
+ "next_budget",
63
+ "search_budget",
64
+ "tick_seconds",
65
+ "lane_idle_minutes",
66
+ "action_attempts",
67
+ "wait_cap",
68
+ }
69
+
70
+
71
+ class ConfigError(Exception):
72
+ """The configuration is unusable; the message says which setting and why."""
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class SwitchboardConfig:
77
+ board: str
78
+ command: tuple[str, ...]
79
+ senders: Mapping[str, str]
80
+ via_bridge: bool = False
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class SessionReaderConfig:
85
+ claude_home: Path
86
+ app_support: Path
87
+ sessions: Mapping[str, str]
88
+ poll_seconds: int
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class GitHubAppConfig:
93
+ client_id: str
94
+ installation_id: int
95
+ private_key_file: Path
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class GitHubConfig:
100
+ repository: str
101
+ token_file: Path | None
102
+ api_url: str
103
+ poll_seconds: int
104
+ image_jobs: tuple[str, ...] = ()
105
+ merge_gate_policy: GatePolicy = field(default_factory=GatePolicy)
106
+ app: GitHubAppConfig | None = None
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class GitHubIssuesConfig:
111
+ starter: Path
112
+ store_config: Path
113
+ milestone: int | None
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class EmbedderConfig:
118
+ url: str
119
+ model: EmbeddingModel
120
+ key_file: Path | None = None
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class Config:
125
+ """The validated settings a plotroom process runs with."""
126
+
127
+ data_dir: Path
128
+ host: str
129
+ port: int
130
+ allowed_hosts: tuple[str, ...]
131
+ projects: tuple[str, ...]
132
+ log_max_bytes: int = DEFAULT_LOG_MAX_BYTES
133
+ log_backups: int = DEFAULT_LOG_BACKUPS
134
+ drain_sessions: Mapping[str, str] = field(default_factory=lambda: {})
135
+
136
+ workers: Mapping[str, frozenset[str]] = field(default_factory=lambda: {})
137
+ ticket_trees: Mapping[str, tuple[Path, Path]] = field(default_factory=lambda: {})
138
+ snapshot_budget: int = DEFAULT_SNAPSHOT_BUDGET
139
+ next_budget: int = DEFAULT_SNAPSHOT_BUDGET
140
+ search_budget: int = DEFAULT_SNAPSHOT_BUDGET
141
+ tick_seconds: int = 60
142
+ lane_idle_minutes: int = 15
143
+ action_attempts: int = 3
144
+ wait_cap: int = 240
145
+ watchers: Mapping[str, tuple[str, ...]] = field(default_factory=lambda: {})
146
+ switchboards: Mapping[str, SwitchboardConfig] = field(default_factory=lambda: {})
147
+ session_readers: Mapping[str, SessionReaderConfig] = field(default_factory=lambda: {})
148
+ github: Mapping[str, GitHubConfig] = field(default_factory=lambda: {})
149
+
150
+ github_ticket_trees: Mapping[str, tuple[str, Path]] = field(default_factory=lambda: {})
151
+ github_issue_sources: Mapping[str, GitHubIssuesConfig] = field(default_factory=lambda: {})
152
+ delivery_routes: Mapping[str, Mapping[str, DeliveryRoute]] = field(default_factory=lambda: {})
153
+ routes: Mapping[str, Mapping[str, str]] = field(default_factory=lambda: {})
154
+ briefs: Mapping[str, BriefSettings] = field(default_factory=lambda: {})
155
+ human_logins: Mapping[str, str] = field(default_factory=lambda: {})
156
+ ask_stale_days: Mapping[str, int] = field(default_factory=lambda: {})
157
+ embedders: Mapping[str, EmbedderConfig] = field(default_factory=lambda: {})
158
+ backup_dir: Path | None = None
159
+ backup_retain: int = 3
160
+ openrouter_runs: Mapping[str, Mapping[str, OpenRouterRun]] = field(default_factory=lambda: {})
161
+
162
+ @property
163
+ def url(self) -> str:
164
+ """Where a local client reaches the server's MCP endpoint."""
165
+ host = _WILDCARD_TO_LOOPBACK.get(self.host, self.host)
166
+ host = f"[{host}]" if ":" in host else host
167
+ return f"http://{host}:{self.port}/mcp"
168
+
169
+
170
+ def default_config_path(env: Mapping[str, str]) -> Path:
171
+ """``PLOTROOM_CONFIG``, else ``~/.config/plotroom/config.toml``."""
172
+ if explicit := env.get("PLOTROOM_CONFIG"):
173
+ return Path(explicit).expanduser()
174
+ return Path.home() / ".config" / "plotroom" / "config.toml"
175
+
176
+
177
+ def default_data_dir() -> Path:
178
+ return Path.home() / ".local" / "share" / "plotroom"
179
+
180
+
181
+ def load_config(
182
+ path: Path | None,
183
+ env: Mapping[str, str],
184
+ *,
185
+ require_projects: bool = True,
186
+ ) -> Config:
187
+ """Load the file at ``path`` (or the default location, if any), then apply the environment.
188
+
189
+ A file named explicitly, by ``path`` or ``PLOTROOM_CONFIG``, must exist; the default location
190
+ may be absent, which leaves environment and defaults to decide.
191
+ """
192
+ explicit = path is not None or "PLOTROOM_CONFIG" in env
193
+ file_path = (path if path is not None else default_config_path(env)).resolve()
194
+ raw: dict[str, Any] = {}
195
+ base = Path.cwd()
196
+ if file_path.exists():
197
+ try:
198
+ raw = tomllib.loads(file_path.read_text(encoding="utf-8"))
199
+ except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc:
200
+ raise ConfigError(f"cannot read config {file_path}: {exc}") from exc
201
+ base = file_path.parent
202
+ elif explicit:
203
+ raise ConfigError(f"config file {file_path} does not exist")
204
+
205
+ unknown = sorted(set(raw) - _TOP_LEVEL_KEYS)
206
+ if unknown:
207
+ raise ConfigError(f"unknown config keys in {file_path}: {', '.join(unknown)}")
208
+
209
+ data_dir = _data_dir(env.get("PLOTROOM_DATA_DIR"), raw.get("data_dir"), base).resolve()
210
+ backup_dir = None
211
+ if (backup_path := raw.get("backup_dir")) is not None:
212
+ backup_dir = (base / Path(_string("backup_dir", backup_path)).expanduser()).resolve()
213
+ if backup_dir.is_relative_to(data_dir) or data_dir.is_relative_to(backup_dir):
214
+ raise ConfigError("backup_dir must be separate from data_dir")
215
+ host = _string("host", env.get("PLOTROOM_HOST", raw.get("host", DEFAULT_HOST)))
216
+ port = _port(env.get("PLOTROOM_PORT", raw.get("port", DEFAULT_PORT)))
217
+ allowed_hosts = _string_list(
218
+ "allowed_hosts",
219
+ env.get("PLOTROOM_ALLOWED_HOSTS", raw.get("allowed_hosts")),
220
+ DEFAULT_ALLOWED_HOSTS,
221
+ )
222
+ projects = _projects(env.get("PLOTROOM_PROJECTS"), raw.get("projects"))
223
+ drain_sessions = _drain_sessions(projects, raw.get("projects"))
224
+ workers = _workers(projects, raw.get("projects"))
225
+ switchboards = _switchboards(projects, raw.get("projects"))
226
+ worker_sessions = _worker_sessions(projects, raw.get("projects"), drain_sessions)
227
+ if require_projects and not projects:
228
+ raise ConfigError(
229
+ "no projects configured: add a [projects.<id>] table to the config file "
230
+ "or set PLOTROOM_PROJECTS to a comma-separated list of project ids"
231
+ )
232
+ log_max_bytes = _integer(
233
+ "log_max_bytes",
234
+ env.get("PLOTROOM_LOG_MAX_BYTES", raw.get("log_max_bytes", DEFAULT_LOG_MAX_BYTES)),
235
+ minimum=1,
236
+ )
237
+ log_backups = _integer(
238
+ "log_backups",
239
+ env.get("PLOTROOM_LOG_BACKUPS", raw.get("log_backups", DEFAULT_LOG_BACKUPS)),
240
+ minimum=0,
241
+ )
242
+ github = _github_projects(projects, raw.get("projects"), base)
243
+ github_trees, github_issues = _github_work_items(projects, raw.get("projects"), base, github)
244
+ return Config(
245
+ data_dir=data_dir,
246
+ backup_dir=backup_dir,
247
+ backup_retain=_integer("backup_retain", raw.get("backup_retain", 3), minimum=1),
248
+ host=host,
249
+ port=port,
250
+ allowed_hosts=allowed_hosts,
251
+ projects=projects,
252
+ log_max_bytes=log_max_bytes,
253
+ log_backups=log_backups,
254
+ drain_sessions=drain_sessions,
255
+ workers=workers,
256
+ ticket_trees=_ticket_trees(projects, raw.get("projects"), base),
257
+ watchers=_watchers(projects, raw.get("projects"), drain_sessions),
258
+ switchboards=switchboards,
259
+ session_readers=_session_readers(projects, raw.get("projects"), base, worker_sessions),
260
+ github=github,
261
+ github_ticket_trees=github_trees,
262
+ github_issue_sources=github_issues,
263
+ briefs=_brief_settings(projects, raw.get("projects")),
264
+ embedders=_embedders(projects, raw.get("projects"), base),
265
+ openrouter_runs=_openrouter_runs(projects, raw.get("projects"), base),
266
+ delivery_routes=_delivery_routes(projects, switchboards, worker_sessions, drain_sessions),
267
+ routes=_routes(projects, raw.get("projects")),
268
+ human_logins=_human_logins(projects, raw.get("projects")),
269
+ ask_stale_days=_ask_stale_days(projects, raw.get("projects")),
270
+ wait_cap=_integer("wait_cap", raw.get("wait_cap", 240), minimum=1),
271
+ snapshot_budget=_integer(
272
+ "snapshot_budget",
273
+ raw.get("snapshot_budget", DEFAULT_SNAPSHOT_BUDGET),
274
+ minimum=MIN_BOARD_BUDGET,
275
+ ),
276
+ next_budget=_integer(
277
+ "next_budget", raw.get("next_budget", DEFAULT_SNAPSHOT_BUDGET), minimum=MIN_BOARD_BUDGET
278
+ ),
279
+ search_budget=_integer(
280
+ "search_budget",
281
+ raw.get("search_budget", DEFAULT_SNAPSHOT_BUDGET),
282
+ minimum=MIN_BOARD_BUDGET,
283
+ ),
284
+ tick_seconds=_integer("tick_seconds", raw.get("tick_seconds", 60), minimum=1),
285
+ lane_idle_minutes=_integer(
286
+ "lane_idle_minutes", raw.get("lane_idle_minutes", 15), minimum=1
287
+ ),
288
+ action_attempts=_integer("action_attempts", raw.get("action_attempts", 3), minimum=1),
289
+ )
290
+
291
+
292
+ def _data_dir(env_value: str | None, file_value: Any, base: Path) -> Path:
293
+ """The environment's path is relative to the process; the file's is relative to the file."""
294
+ if env_value is not None:
295
+ return Path(_string("PLOTROOM_DATA_DIR", env_value)).expanduser()
296
+ if file_value is None:
297
+ return default_data_dir()
298
+ candidate = Path(_string("data_dir", file_value)).expanduser()
299
+ return candidate if candidate.is_absolute() else (base / candidate)
300
+
301
+
302
+ def _string(name: str, value: Any) -> str:
303
+ if not isinstance(value, str) or not value.strip():
304
+ raise ConfigError(f"{name} must be a non-empty string")
305
+ return value.strip()
306
+
307
+
308
+ def _port(value: Any) -> int:
309
+ if isinstance(value, bool) or not isinstance(value, int | str):
310
+ raise ConfigError(f"port must be an integer between 0 and 65535, got {value!r}")
311
+ try:
312
+ port = int(value)
313
+ except ValueError as exc:
314
+ raise ConfigError(f"port must be an integer between 0 and 65535, got {value!r}") from exc
315
+ if not 0 <= port <= 65535:
316
+ raise ConfigError(f"port must be an integer between 0 and 65535, got {port}")
317
+ return port
318
+
319
+
320
+ def _integer(name: str, value: Any, *, minimum: int) -> int:
321
+ message = f"{name} must be an integer of at least {minimum}, got {value!r}"
322
+ if isinstance(value, bool) or not isinstance(value, int | str):
323
+ raise ConfigError(message)
324
+ try:
325
+ number = int(value)
326
+ except ValueError as exc:
327
+ raise ConfigError(message) from exc
328
+ if number < minimum:
329
+ raise ConfigError(message)
330
+ return number
331
+
332
+
333
+ def _string_list(name: str, value: Any, default: tuple[str, ...]) -> tuple[str, ...]:
334
+ if value is None:
335
+ return default
336
+ items: Any = value.split(",") if isinstance(value, str) else value
337
+ if not isinstance(items, list) or not all(isinstance(i, str) for i in cast("list[Any]", items)):
338
+ raise ConfigError(f"{name} must be a list of strings")
339
+ cleaned = tuple(str(i).strip() for i in cast("list[Any]", items) if str(i).strip())
340
+ if not cleaned:
341
+ raise ConfigError(f"{name} must not be empty")
342
+ return cleaned
343
+
344
+
345
+ def _projects(env_value: str | None, table: Any) -> tuple[str, ...]:
346
+ ids: list[str]
347
+ if env_value is not None:
348
+ ids = [part.strip() for part in env_value.split(",") if part.strip()]
349
+ elif table is None:
350
+ ids = []
351
+ elif isinstance(table, dict):
352
+ ids = [str(key) for key in cast("dict[Any, Any]", table)]
353
+ else:
354
+ raise ConfigError("projects must be a table of [projects.<id>] entries")
355
+ for project_id in ids:
356
+ if not _SLUG.fullmatch(project_id):
357
+ raise ConfigError(
358
+ f"project id {project_id!r} must be a lowercase slug (letters, digits, '-' or '_')"
359
+ )
360
+ if len(set(ids)) != len(ids):
361
+ raise ConfigError("project ids must be unique")
362
+ return tuple(ids)
363
+
364
+
365
+ def _drain_sessions(projects: tuple[str, ...], table: Any) -> dict[str, str]:
366
+ if not isinstance(table, dict):
367
+ return {}
368
+ entries = cast("dict[str, Any]", table)
369
+ sessions: dict[str, str] = {}
370
+ for project_id in projects:
371
+ settings: Any = entries.get(project_id, {})
372
+ if not isinstance(settings, dict):
373
+ raise ConfigError(f"projects.{project_id} must be a table")
374
+ project = cast("dict[str, Any]", settings)
375
+ if "drain_session" in project:
376
+ sessions[project_id] = _string(
377
+ f"projects.{project_id}.drain_session", project["drain_session"]
378
+ )
379
+ return sessions
380
+
381
+
382
+ def _human_logins(projects: tuple[str, ...], table: Any) -> dict[str, str]:
383
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
384
+ configured: dict[str, str] = {}
385
+ for project_id in projects:
386
+ settings = entries.get(project_id, {})
387
+ if "human_login" in settings:
388
+ name = f"projects.{project_id}.human_login"
389
+ configured[project_id] = _string(name, settings["human_login"])
390
+ return configured
391
+
392
+
393
+ def _ask_stale_days(projects: tuple[str, ...], table: Any) -> dict[str, int]:
394
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
395
+ configured: dict[str, int] = {}
396
+ for project in projects:
397
+ settings = entries.get(project, {})
398
+ if "ask_stale_days" in settings:
399
+ name = f"projects.{project}.ask_stale_days"
400
+ configured[project] = _integer(name, settings["ask_stale_days"], minimum=0)
401
+ return configured
402
+
403
+
404
+ def _workers(projects: tuple[str, ...], table: Any) -> dict[str, frozenset[str]]:
405
+ configured: dict[str, frozenset[str]] = {}
406
+ if not isinstance(table, dict):
407
+ return configured
408
+
409
+ entries = cast("dict[str, dict[str, Any]]", table)
410
+ for project_id in projects:
411
+ workers: Any = entries.get(project_id, {}).get("workers", {})
412
+ if not isinstance(workers, dict):
413
+ raise ConfigError(f"projects.{project_id}.workers must be a table keyed by worker name")
414
+ names = cast("dict[str, Any]", workers)
415
+ for name, value in names.items():
416
+ if not isinstance(value, dict):
417
+ raise ConfigError(f"projects.{project_id}.workers.{name} must be a table")
418
+ try:
419
+ role_family(f"worker:{name}")
420
+ except ValueError as exc:
421
+ raise ConfigError(
422
+ f"projects.{project_id}.workers.{name}: invalid worker name"
423
+ ) from exc
424
+ configured[project_id] = frozenset(names)
425
+ return configured
426
+
427
+
428
+ def _switchboards(projects: tuple[str, ...], table: Any) -> dict[str, SwitchboardConfig]:
429
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
430
+ configured: dict[str, SwitchboardConfig] = {}
431
+ boards: set[str] = set()
432
+ for project_id in projects:
433
+ project = entries.get(project_id, {})
434
+ if "switchboard" not in project:
435
+ continue
436
+ label = f"projects.{project_id}.switchboard"
437
+ raw_settings = project["switchboard"]
438
+ if not isinstance(raw_settings, dict):
439
+ raise ConfigError(f"{label} must be a table")
440
+ settings = cast("dict[str, Any]", raw_settings)
441
+ board = _string(f"{label}.board", settings.get("board"))
442
+ if (
443
+ not _SLUG.fullmatch(board)
444
+ or board.endswith(("-", "_"))
445
+ or board == "project"
446
+ or board in boards
447
+ ):
448
+ raise ConfigError(f"{label}.board must be a unique canonical relay name")
449
+ boards.add(board)
450
+ command = _string_list(f"{label}.command", settings.get("command"), ("switchboard-relay",))
451
+ senders: dict[str, str] = {}
452
+ for worker, worker_settings in project.get("workers", {}).items():
453
+ if "switchboard_address" in worker_settings:
454
+ address = _string(
455
+ f"{label} address for {worker}", worker_settings["switchboard_address"]
456
+ )
457
+ if address in senders:
458
+ raise ConfigError(f"{label} worker addresses must be unique")
459
+ senders[address] = worker
460
+ via_bridge = settings.get("via_bridge", False)
461
+ if not isinstance(via_bridge, bool):
462
+ raise ConfigError(f"{label}.via_bridge must be a boolean")
463
+ configured[project_id] = SwitchboardConfig(board, command, senders, via_bridge)
464
+ return configured
465
+
466
+
467
+ def _embedders(projects: tuple[str, ...], table: Any, base: Path) -> dict[str, EmbedderConfig]:
468
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
469
+ configured: dict[str, EmbedderConfig] = {}
470
+ for project_id in projects:
471
+ project = entries.get(project_id, {})
472
+ if "embedder" not in project:
473
+ continue
474
+ label = f"projects.{project_id}.embedder"
475
+ raw_settings = project["embedder"]
476
+ if not isinstance(raw_settings, dict):
477
+ raise ConfigError(f"{label} must be a table")
478
+ settings = cast("dict[str, Any]", raw_settings)
479
+ if set(settings) - {"url", "model", "dimension", "key_file"}:
480
+ raise ConfigError(f"{label} supports url, model, dimension and key_file")
481
+ url = _string(f"{label}.url", settings.get("url"))
482
+ message = f"{label}.url must be an HTTP or HTTPS endpoint without credentials or fragment"
483
+ try:
484
+ endpoint = httpx.URL(url)
485
+ host = endpoint.host
486
+ port = endpoint.port
487
+ except (httpx.InvalidURL, UnicodeError) as exc:
488
+ raise ConfigError(message) from exc
489
+ if (
490
+ endpoint.scheme not in ("http", "https")
491
+ or not host
492
+ or endpoint.userinfo
493
+ or "#" in url
494
+ or (port is not None and not 1 <= port <= 65535)
495
+ or any(char.isspace() for char in host)
496
+ ):
497
+ raise ConfigError(message)
498
+ model = _string(f"{label}.model", settings.get("model"))
499
+ dimension = _integer(f"{label}.dimension", settings.get("dimension"), minimum=1)
500
+ if dimension > 2**63 - 1:
501
+ raise ConfigError(f"{label}.dimension exceeds the SQLite integer range")
502
+ key_file = None
503
+ if "key_file" in settings:
504
+ if endpoint.scheme != "https":
505
+ raise ConfigError(f"{label}.key_file requires an HTTPS endpoint")
506
+ setting = f"{label}.key_file"
507
+ key_path = _string(setting, settings["key_file"])
508
+ if "\0" in key_path:
509
+ raise ConfigError(f"{setting} must not contain a NUL character")
510
+ try:
511
+ key_file = base / Path(key_path).expanduser()
512
+ except RuntimeError:
513
+ raise ConfigError(f"{setting} could not expand the home directory") from None
514
+ configured[project_id] = EmbedderConfig(url, EmbeddingModel(model, dimension), key_file)
515
+ return configured
516
+
517
+
518
+ def _session_readers(
519
+ projects: tuple[str, ...], table: Any, base: Path, sessions: Mapping[str, dict[str, str]]
520
+ ) -> dict[str, SessionReaderConfig]:
521
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
522
+ configured: dict[str, SessionReaderConfig] = {}
523
+ for project_id in projects:
524
+ project = entries.get(project_id, {})
525
+ if "session_reader" not in project:
526
+ continue
527
+ label = f"projects.{project_id}.session_reader"
528
+ raw_settings = project["session_reader"]
529
+ if not isinstance(raw_settings, dict):
530
+ raise ConfigError(f"{label} must be a table")
531
+ settings = cast("dict[str, Any]", raw_settings)
532
+ home = (
533
+ base / Path(_string(f"{label}.claude_home", settings.get("claude_home"))).expanduser()
534
+ )
535
+ support = (
536
+ base / Path(_string(f"{label}.app_support", settings.get("app_support"))).expanduser()
537
+ )
538
+ interval = _integer(f"{label}.poll_seconds", settings.get("poll_seconds", 1), minimum=1)
539
+ configured[project_id] = SessionReaderConfig(
540
+ home.resolve(), support.resolve(), sessions[project_id], interval
541
+ )
542
+ return configured
543
+
544
+
545
+ def _worker_sessions(
546
+ projects: tuple[str, ...], table: Any, drains: Mapping[str, str]
547
+ ) -> dict[str, dict[str, str]]:
548
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
549
+ configured: dict[str, dict[str, str]] = {}
550
+ for project_id in projects:
551
+ sessions: dict[str, str] = {}
552
+ project = entries.get(project_id, {})
553
+ if "session_reader" not in project and project_id not in drains:
554
+ continue
555
+ for worker, settings in project.get("workers", {}).items():
556
+ if "claude_session" not in settings:
557
+ continue
558
+ label = f"projects.{project_id}.workers.{worker}.claude_session"
559
+ session = _string(label, settings["claude_session"])
560
+ if not SESSION_ID.fullmatch(session) or session in sessions:
561
+ raise ConfigError(f"{label}: Claude session IDs must be valid and unique")
562
+ sessions[session] = worker
563
+ configured[project_id] = sessions
564
+ return configured
565
+
566
+
567
+ def _routes(projects: tuple[str, ...], table: Any) -> dict[str, Mapping[str, str]]:
568
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
569
+ configured: dict[str, Mapping[str, str]] = {}
570
+ for project_id in projects:
571
+ project = entries.get(project_id, {})
572
+ if "routes" not in project:
573
+ continue
574
+ label = f"projects.{project_id}.routes"
575
+ raw: Any = project["routes"]
576
+ if not isinstance(raw, dict):
577
+ raise ConfigError(f"{label} must be a table of action kinds mapped to lane IDs")
578
+ routes: dict[str, str] = {}
579
+ for action_kind, lane in cast("dict[str, Any]", raw).items():
580
+ try:
581
+ kind = validate_route_label(action_kind, f"{label} action kind")
582
+ routes[kind] = validate_route_label(lane, f"{label}.{kind}")
583
+ except LedgerError as exc:
584
+ raise ConfigError(exc.message) from exc
585
+ configured[project_id] = routes
586
+ return configured
587
+
588
+
589
+ def _delivery_routes(
590
+ projects: tuple[str, ...],
591
+ switchboards: Mapping[str, SwitchboardConfig],
592
+ sessions: Mapping[str, dict[str, str]],
593
+ drains: Mapping[str, str],
594
+ ) -> dict[str, Mapping[str, DeliveryRoute]]:
595
+ configured: dict[str, Mapping[str, DeliveryRoute]] = {}
596
+ for project_id in projects:
597
+ relay = switchboards.get(project_id)
598
+ routes = {
599
+ worker: DeliveryRoute("switchboard", address)
600
+ for address, worker in (relay.senders.items() if relay is not None else ())
601
+ }
602
+ if project_id in drains:
603
+ for session, worker in sessions[project_id].items():
604
+ # An explicit relay address takes precedence over a session reader mapping.
605
+ routes.setdefault(worker, DeliveryRoute("claude", session))
606
+ configured[project_id] = routes
607
+ return configured
608
+
609
+
610
+ def _openrouter_runs(
611
+ projects: tuple[str, ...], table: Any, base: Path
612
+ ) -> dict[str, dict[str, OpenRouterRun]]:
613
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
614
+ configured: dict[str, dict[str, OpenRouterRun]] = {}
615
+ pins: set[str] = set()
616
+ for project_id in projects:
617
+ raw = entries.get(project_id, {}).get("openrouter")
618
+ if raw is None:
619
+ continue
620
+ label = f"projects.{project_id}.openrouter"
621
+ if not isinstance(raw, dict):
622
+ raise ConfigError(f"{label} must map run IDs to key bindings")
623
+ runs: dict[str, OpenRouterRun] = {}
624
+ for run, entry in cast("dict[str, Any]", raw).items():
625
+ try:
626
+ validate_identity(run, "OpenRouter run ID")
627
+ except LedgerError as exc:
628
+ raise ConfigError(f"{label}: {exc.message}") from None
629
+ if not isinstance(entry, dict) or set(cast("dict[str, Any]", entry)) != {
630
+ "key_file",
631
+ "key_sha256",
632
+ }:
633
+ raise ConfigError(f"{label} run bindings require key_file and key_sha256")
634
+ binding = cast("dict[str, Any]", entry)
635
+ pin = _string(f"{label} key_sha256", binding["key_sha256"])
636
+ if not re.fullmatch(r"[a-fA-F0-9]{64}", pin):
637
+ raise ConfigError(f"{label} key_sha256 must be a 64-digit SHA-256 hex digest")
638
+ pin = pin.lower()
639
+ if pin in pins:
640
+ raise ConfigError("each OpenRouter run must have a unique key pin")
641
+ pins.add(pin)
642
+ path = base / Path(_string(f"{label} key_file", binding["key_file"])).expanduser()
643
+ runs[run] = OpenRouterRun(path, pin)
644
+ configured[project_id] = runs
645
+ return configured
646
+
647
+
648
+ def _github_projects(projects: tuple[str, ...], table: Any, base: Path) -> dict[str, GitHubConfig]:
649
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
650
+ configured: dict[str, GitHubConfig] = {}
651
+ names: set[str] = set()
652
+ for project_id in projects:
653
+ project = entries.get(project_id, {})
654
+ if "github" not in project:
655
+ continue
656
+ label = f"projects.{project_id}.github"
657
+ raw_settings = project["github"]
658
+ if not isinstance(raw_settings, dict):
659
+ raise ConfigError(f"{label} must be a table")
660
+ settings = cast("dict[str, Any]", raw_settings)
661
+ repository = _string(f"{label}.repository", settings.get("repository")).lower()
662
+ if not _REPOSITORY.fullmatch(repository) or repository.split("/")[1] in (".", ".."):
663
+ raise ConfigError(f"{label}.repository must be a GitHub owner/repository")
664
+ app = _github_app(settings, label, base)
665
+ if app is None:
666
+ name = github_secret_name(project_id)
667
+ if name in names:
668
+ raise ConfigError(f"{label} credential environment variable must be unique")
669
+ names.add(name)
670
+ token_file = None
671
+ if "token_file" in settings:
672
+ token_file = (
673
+ base / Path(_string(f"{label}.token_file", settings["token_file"])).expanduser()
674
+ )
675
+ api_url = _string(f"{label}.api_url", settings.get("api_url", GITHUB_API)).rstrip("/")
676
+ if not is_github_api_url(api_url):
677
+ raise ConfigError(f"{label}.api_url must be the GitHub API or a loopback fixture")
678
+ if app is not None and api_url != GITHUB_API:
679
+ raise ConfigError(f"{label}.app requires the GitHub HTTPS API origin")
680
+ poll_seconds = _integer(
681
+ f"{label}.poll_seconds", settings.get("poll_seconds", 60), minimum=1
682
+ )
683
+ configured[project_id] = GitHubConfig(
684
+ repository,
685
+ token_file,
686
+ api_url,
687
+ poll_seconds,
688
+ _string_list(f"{label}.image_jobs", settings.get("image_jobs"), ()),
689
+ _merge_gate_policy(label, settings, poll_seconds, repository),
690
+ app,
691
+ )
692
+ return configured
693
+
694
+
695
+ def _github_app(settings: dict[str, Any], label: str, base: Path) -> GitHubAppConfig | None:
696
+ if "app" not in settings:
697
+ return None
698
+ label = f"{label}.app"
699
+ raw = settings["app"]
700
+ if not isinstance(raw, dict):
701
+ raise ConfigError(f"{label} must be a table")
702
+ if "token_file" in settings:
703
+ raise ConfigError(f"{label} and token_file cannot be combined")
704
+ app = cast("dict[str, Any]", raw)
705
+ if app.keys() != {"client_id", "installation_id", "private_key_file"}:
706
+ raise ConfigError(f"{label} requires client_id, installation_id, and private_key_file")
707
+ client_id = _string(f"{label}.client_id", app["client_id"])
708
+ if not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", client_id):
709
+ raise ConfigError(f"{label}.client_id must be a GitHub App client ID")
710
+ installation = _integer(f"{label}.installation_id", app["installation_id"], minimum=1)
711
+ if installation > 2**63 - 1:
712
+ raise ConfigError(f"{label}.installation_id is too large")
713
+ key = Path(_string(f"{label}.private_key_file", app["private_key_file"])).expanduser()
714
+ return GitHubAppConfig(client_id, installation, base / key)
715
+
716
+
717
+ def _positive_github_id(label: str, value: Any) -> int:
718
+ if type(value) is not int or not 0 < value <= 2**63 - 1:
719
+ raise ConfigError(f"{label} must be a positive GitHub integer ID")
720
+ return value
721
+
722
+
723
+ def _opening_head(label: str, repository: str, value: Any) -> OpeningHeadAttestation:
724
+ required = {"repository", "pull_number", "pull_id", "created_at", "head_sha"}
725
+ if not isinstance(value, dict) or value.keys() != required:
726
+ raise ConfigError(
727
+ f"{label} requires repository, pull_number, pull_id, created_at, and head_sha"
728
+ )
729
+ entry = cast("dict[str, Any]", value)
730
+ if _string(f"{label}.repository", entry["repository"]).lower() != repository:
731
+ raise ConfigError(f"{label}.repository must match the project's GitHub repository")
732
+ sha = _string(f"{label}.head_sha", entry["head_sha"])
733
+ if not valid_git_sha(sha):
734
+ raise ConfigError(f"{label}.head_sha must be a full lowercase Git SHA")
735
+ created_at = _string(f"{label}.created_at", entry["created_at"])
736
+ try:
737
+ created_at = format_time(datetime.fromisoformat(created_at))
738
+ except ValueError, OverflowError:
739
+ raise ConfigError(f"{label}.created_at must be a timestamp with a UTC offset") from None
740
+ return OpeningHeadAttestation(
741
+ repository,
742
+ _positive_github_id(f"{label}.pull_number", entry["pull_number"]),
743
+ _positive_github_id(f"{label}.pull_id", entry["pull_id"]),
744
+ created_at,
745
+ sha,
746
+ )
747
+
748
+
749
+ def _kodus_policy(
750
+ label: str, repository: str, settings: dict[str, Any]
751
+ ) -> KodusReviewPolicy | None:
752
+ if "kodus_review" not in settings:
753
+ return None
754
+ label = f"{label}.kodus_review"
755
+ raw = settings["kodus_review"]
756
+ if not isinstance(raw, dict):
757
+ raise ConfigError(f"{label} must be a table")
758
+ table = cast("dict[str, Any]", raw)
759
+ identity = {"app_id", "app_slug", "check_name"}
760
+ if not identity <= table.keys() <= identity | {"opening_heads"}:
761
+ raise ConfigError(f"{label} requires app_id, app_slug, and check_name")
762
+ slug = _string(f"{label}.app_slug", table["app_slug"])
763
+ if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,99}", slug):
764
+ raise ConfigError(f"{label}.app_slug must be a lowercase GitHub App slug")
765
+ name = _string(f"{label}.check_name", table["check_name"])
766
+ opening_heads = table.get("opening_heads", [])
767
+ if not isinstance(opening_heads, list):
768
+ raise ConfigError(f"{label}.opening_heads must be an array of tables")
769
+ attestations = tuple(
770
+ _opening_head(f"{label}.opening_heads[{index}]", repository, entry)
771
+ for index, entry in enumerate(cast("list[Any]", opening_heads))
772
+ )
773
+ if len({entry.pull_number for entry in attestations}) != len(attestations) or len(
774
+ {entry.pull_id for entry in attestations}
775
+ ) != len(attestations):
776
+ raise ConfigError(f"{label}.opening_heads contains duplicate pull identity")
777
+ return KodusReviewPolicy(
778
+ _positive_github_id(f"{label}.app_id", table["app_id"]), slug, name, attestations
779
+ )
780
+
781
+
782
+ def _merge_gate_policy(
783
+ label: str, settings: dict[str, Any], poll_seconds: int, repository: str
784
+ ) -> GatePolicy:
785
+ minimum = (
786
+ _integer(f"{label}.min_checks", settings["min_checks"], minimum=1)
787
+ if "min_checks" in settings
788
+ else None
789
+ )
790
+ ignored = settings.get("ignore_checks", [])
791
+ if not isinstance(ignored, list) or not all(
792
+ isinstance(name, str) and name for name in cast("list[Any]", ignored)
793
+ ):
794
+ raise ConfigError(f"{label}.ignore_checks must be a list of nonempty check names")
795
+ workflow = None
796
+ if "ci_workflow" in settings:
797
+ raw_workflow = settings["ci_workflow"]
798
+ workflow = _string(
799
+ f"{label}.ci_workflow", str(raw_workflow) if type(raw_workflow) is int else raw_workflow
800
+ )
801
+ if not _WORKFLOW.fullmatch(workflow) or (
802
+ workflow.isdecimal() and int(workflow) > 2**63 - 1
803
+ ):
804
+ raise ConfigError(f"{label}.ci_workflow must be a workflow filename or positive ID")
805
+ fix_label = (
806
+ _string(f"{label}.fix_label", settings["fix_label"]) if "fix_label" in settings else None
807
+ )
808
+ raw_logins = settings.get("authorized_label_logins", [])
809
+ if not isinstance(raw_logins, list) or not all(
810
+ isinstance(login, str) and _GITHUB_LOGIN.fullmatch(login)
811
+ for login in cast("list[Any]", raw_logins)
812
+ ):
813
+ raise ConfigError(f"{label}.authorized_label_logins must be a list of GitHub logins")
814
+ controller_merges = settings.get("controller_merges", False)
815
+ if type(controller_merges) is not bool:
816
+ raise ConfigError(f"{label}.controller_merges must be a Boolean")
817
+ merge_method = settings.get("merge_method", "merge")
818
+ if merge_method not in ("merge", "squash", "rebase"):
819
+ raise ConfigError(f"{label}.merge_method must be merge, squash, or rebase")
820
+ skip_label = (
821
+ _string(f"{label}.skip_label", settings["skip_label"]) if "skip_label" in settings else None
822
+ )
823
+ try:
824
+ return GatePolicy(
825
+ minimum,
826
+ tuple(cast("list[str]", ignored)),
827
+ max_age=timedelta(seconds=2 * poll_seconds),
828
+ pull_max_age=timedelta(seconds=(RECONCILE_EVERY + 2) * poll_seconds),
829
+ ci_workflow=workflow,
830
+ fix_label=fix_label,
831
+ authorized_label_logins=tuple(login.lower() for login in cast("list[str]", raw_logins)),
832
+ skip_label=skip_label,
833
+ merge_method=merge_method,
834
+ controller_merges=controller_merges,
835
+ kodus_review=_kodus_policy(label, repository, settings),
836
+ )
837
+ except OverflowError:
838
+ raise ConfigError(f"{label}.poll_seconds is too large for the merge gate") from None
839
+
840
+
841
+ def _watchers(
842
+ projects: tuple[str, ...], table: Any, drain_sessions: Mapping[str, str]
843
+ ) -> dict[str, tuple[str, ...]]:
844
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
845
+ configured: dict[str, tuple[str, ...]] = {}
846
+ for project_id in projects:
847
+ value: Any = entries.get(project_id, {}).get("watchers")
848
+ if value is None:
849
+ configured[project_id] = (
850
+ ("orchestrator", "clerk", "drain")
851
+ if project_id in drain_sessions
852
+ else ("orchestrator", "clerk")
853
+ )
854
+ continue
855
+ label = f"projects.{project_id}.watchers"
856
+ if value == []:
857
+ configured[project_id] = ()
858
+ continue
859
+ roles = _string_list(label, value, ())
860
+ try:
861
+ if any(role_family(role) == "system" for role in roles):
862
+ raise ValueError("system cannot watch")
863
+ except ValueError as exc:
864
+ raise ConfigError(f"{label}: {exc}") from None
865
+ configured[project_id] = tuple(dict.fromkeys(roles))
866
+ return configured
867
+
868
+
869
+ def _ticket_trees(
870
+ projects: tuple[str, ...], table: Any, base: Path
871
+ ) -> dict[str, tuple[Path, Path]]:
872
+ sources: dict[str, tuple[Path, Path]] = {}
873
+ if not isinstance(table, dict):
874
+ return sources
875
+ entries = cast("dict[str, dict[str, Any]]", table)
876
+ for project_id in projects:
877
+ settings = entries.get(project_id, {})
878
+ if "ticket_tree" in settings:
879
+ field_name = f"projects.{project_id}"
880
+ tree = (
881
+ base
882
+ / Path(_string(f"{field_name}.ticket_tree", settings["ticket_tree"])).expanduser()
883
+ ).resolve()
884
+ if "bmad_installation" not in settings:
885
+ raise ConfigError(
886
+ f"{field_name}.bmad_installation must name a trusted BMad installation"
887
+ )
888
+ installation = (
889
+ base
890
+ / Path(
891
+ _string(f"{field_name}.bmad_installation", settings["bmad_installation"])
892
+ ).expanduser()
893
+ ).resolve()
894
+ sources[project_id] = tree, installation
895
+ return sources
896
+
897
+
898
+ def _brief_settings(projects: tuple[str, ...], table: Any) -> dict[str, BriefSettings]:
899
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
900
+ configured: dict[str, BriefSettings] = {}
901
+ defaults = BriefSettings()
902
+ for project_id in projects:
903
+ project = entries.get(project_id, {})
904
+ if "brief" not in project:
905
+ continue
906
+ label = f"projects.{project_id}.brief"
907
+ settings = project["brief"]
908
+ if not isinstance(settings, dict):
909
+ raise ConfigError(f"{label} must be a table")
910
+ settings = cast("dict[str, Any]", settings)
911
+ if settings.keys() - {"template", "plan", "result", "standing_rules"}:
912
+ raise ConfigError(f"{label} supports template, plan, result, and standing_rules")
913
+ template = settings.get("template", defaults.template)
914
+ if not isinstance(template, str) or not template.strip():
915
+ raise ConfigError(f"{label}.template must be a non-empty string")
916
+ rules = settings.get("standing_rules", [])
917
+ if not isinstance(rules, list):
918
+ raise ConfigError(f"{label}.standing_rules must be a list of strings")
919
+ try:
920
+ configured[project_id] = BriefSettings(
921
+ template=template,
922
+ plan=_string(f"{label}.plan", settings.get("plan", defaults.plan)),
923
+ result=_string(f"{label}.result", settings.get("result", defaults.result)),
924
+ standing_rules=tuple(
925
+ _string(f"{label}.standing_rules", rule) for rule in cast("list[Any]", rules)
926
+ ),
927
+ )
928
+ except ValueError as exc:
929
+ raise ConfigError(f"{label}.template {exc}") from None
930
+ return configured
931
+
932
+
933
+ def _github_work_items(
934
+ projects: tuple[str, ...], table: Any, base: Path, github: Mapping[str, GitHubConfig]
935
+ ) -> tuple[dict[str, tuple[str, Path]], dict[str, GitHubIssuesConfig]]:
936
+ entries = cast("dict[str, dict[str, Any]]", table if isinstance(table, dict) else {})
937
+ trees: dict[str, tuple[str, Path]] = {}
938
+ issues: dict[str, GitHubIssuesConfig] = {}
939
+ for project_id in projects:
940
+ project = entries.get(project_id, {})
941
+ configured = project.keys() & {"ticket_tree", "github_ticket_tree", "github_issues"}
942
+ label = f"projects.{project_id}"
943
+ if len(configured) > 1:
944
+ raise ConfigError(f"{label} must select one work-item source")
945
+ if not configured or "ticket_tree" in configured:
946
+ continue
947
+ if project_id not in github:
948
+ raise ConfigError(f"{label} needs GitHub configuration for its work-item source")
949
+ installation = (
950
+ base
951
+ / Path(
952
+ _string(f"{label}.bmad_installation", project.get("bmad_installation"))
953
+ ).expanduser()
954
+ ).resolve()
955
+ if "github_ticket_tree" in configured:
956
+ tree = _string(f"{label}.github_ticket_tree", project["github_ticket_tree"])
957
+ try:
958
+ validate_tree_path(tree)
959
+ except ValueError:
960
+ raise ConfigError(
961
+ f"{label}.github_ticket_tree must be a repository-relative path"
962
+ ) from None
963
+ trees[project_id] = tree, installation
964
+ continue
965
+ settings = project["github_issues"]
966
+ if not isinstance(settings, dict):
967
+ raise ConfigError(f"{label}.github_issues must be a table")
968
+ settings = cast("dict[str, Any]", settings)
969
+ if settings.keys() - {"store_config", "milestone"}:
970
+ raise ConfigError(f"{label}.github_issues supports store_config and milestone")
971
+ store = (
972
+ base
973
+ / Path(
974
+ _string(f"{label}.github_issues.store_config", settings.get("store_config"))
975
+ ).expanduser()
976
+ ).resolve()
977
+ milestone = (
978
+ _integer(f"{label}.github_issues.milestone", settings["milestone"], minimum=1)
979
+ if "milestone" in settings
980
+ else None
981
+ )
982
+ starter = installation / ".agents/skills/bmad-agent-po/config/github-ticketing.toml"
983
+ issues[project_id] = GitHubIssuesConfig(starter, store, milestone)
984
+ return trees, issues