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,296 @@
1
+ """Lane path reservations and claim overlap rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from bisect import bisect_left
8
+ from collections import defaultdict
9
+ from dataclasses import asdict, dataclass
10
+ from itertools import combinations
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from plotroom.core.events import LedgerError
14
+
15
+ if TYPE_CHECKING:
16
+ from plotroom.core.unit_of_work import UnitOfWork
17
+
18
+ CLAIM_OVERLAP = "claim_overlap"
19
+ PR_CLAIM_OVERLAP = "pr_claim_overlap"
20
+ TICKET_TREE_MOVE = "ticket_tree_move"
21
+ OVERLAP_KINDS = (CLAIM_OVERLAP, PR_CLAIM_OVERLAP, TICKET_TREE_MOVE)
22
+ _GLOB_TOKEN = re.compile(r"\\(.)|([*?\[])")
23
+ _TRAILING_ESCAPE = re.compile(r"(?<!\\)(?:\\\\)*\\$")
24
+ _TRAILING_SPACES = re.compile(r"(?<!\\)((?:\\\\)*)( +)$")
25
+ _BRACKET_PART = r"(?:\\.|\[:[a-z]+:\]|[^\\\]])"
26
+ _BRACKET = re.compile(rf"\[(?P<negate>[!^]?+)(?P<contents>\]{_BRACKET_PART}*|{_BRACKET_PART}+)\]")
27
+ _CLASS_TOKEN = re.compile(r"\\(.)|\[:([a-z]+):\]|(.)")
28
+ _POSIX_CLASSES = {
29
+ "alnum": "0-9A-Za-z",
30
+ "alpha": "A-Za-z",
31
+ "blank": r"\x09\x20",
32
+ "cntrl": r"\x00-\x1f\x7f",
33
+ "digit": "0-9",
34
+ "graph": r"\x21-\x7e",
35
+ "lower": "a-z",
36
+ "print": r"\x20-\x7e",
37
+ "punct": r"\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e",
38
+ "space": r"\x09-\x0d\x20",
39
+ "upper": "A-Z",
40
+ "xdigit": "0-9A-Fa-f",
41
+ }
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Claim:
46
+ lane: str
47
+ glob: str
48
+ reason: str
49
+
50
+ def render(self) -> dict[str, Any]:
51
+ return asdict(self)
52
+
53
+
54
+ def _path_components(pattern: str) -> list[str]:
55
+ parts: list[str] = []
56
+ start = index = 0
57
+ while index < len(pattern):
58
+ char = pattern[index]
59
+ if char == "\\":
60
+ index += 2
61
+ continue
62
+ if char == "[" and (bracket := _BRACKET.match(pattern, index)):
63
+ index = bracket.end()
64
+ continue
65
+ if char == "/":
66
+ parts.append(pattern[start:index])
67
+ start = index + 1
68
+ index += 1
69
+ parts.append(pattern[start:])
70
+ return parts
71
+
72
+
73
+ def normalize_glob(pattern: str) -> str:
74
+ # Git ignores unescaped trailing spaces. Preserve an escaped space and the
75
+ # leading slash on a single component, which makes it root-relative.
76
+ pattern = _TRAILING_SPACES.sub(r"\1", pattern)
77
+ pattern = re.sub(r"(?<!\\)((?:\\\\)*)\\/", r"\1/", pattern)
78
+ if pattern.startswith("!") or any(ord(char) < 32 for char in pattern):
79
+ raise LedgerError("invalid", "claim glob cannot be negated or contain control characters")
80
+ parts = [part for part in _path_components(pattern) if part not in {"", "."}]
81
+ if not parts or ".." in parts or any(_TRAILING_ESCAPE.search(part) for part in parts):
82
+ raise LedgerError("invalid", "claim glob must be a valid repository path pattern")
83
+ anchored = parts[0].startswith("!") or (len(parts) == 1 and "/" in pattern.rstrip("/"))
84
+ root = "/" if anchored else ""
85
+ directory = "/" if pattern.endswith("/") else ""
86
+ if not directory:
87
+ # Removing a final "." component can expose literal spaces at the end.
88
+ parts[-1] = _TRAILING_SPACES.sub(lambda match: match[1] + r"\ " * len(match[2]), parts[-1])
89
+ return root + "/".join(parts) + directory
90
+
91
+
92
+ def literal_prefix(pattern: str) -> str:
93
+ """Represent complete path components with a trailing separator."""
94
+ path = pattern.removeprefix("/").removesuffix("/")
95
+ if not pattern.startswith("/") and "/" not in path:
96
+ return ""
97
+ prefix: list[str] = []
98
+ start = 0
99
+ for token in _GLOB_TOKEN.finditer(path):
100
+ prefix.append(path[start : token.start()])
101
+ if token.group(2):
102
+ return "".join(prefix)
103
+ prefix.append(token.group(1))
104
+ start = token.end()
105
+ prefix.append(path[start:])
106
+ return "".join(prefix) + "/"
107
+
108
+
109
+ def _translate_bracket(match: re.Match[str]) -> str:
110
+ negate = "^" if match["negate"] else ""
111
+ parts: list[str] = []
112
+ for token in _CLASS_TOKEN.finditer(match["contents"]):
113
+ if token[1]:
114
+ parts.append(re.escape(token[1]))
115
+ elif token[2]:
116
+ if token[2] not in _POSIX_CLASSES:
117
+ raise LedgerError("invalid", "claim glob has an unknown bracket character class")
118
+ parts.append(_POSIX_CLASSES[token[2]])
119
+ else:
120
+ parts.append("-" if token[3] == "-" else re.escape(token[3]))
121
+ return f"(?!/)[{negate}{''.join(parts)}]"
122
+
123
+
124
+ def _translate_component(component: str) -> str:
125
+ fragments: list[list[str]] = [[]]
126
+ index = 0
127
+ while index < len(component):
128
+ char = component[index]
129
+ parts = fragments[-1]
130
+ if char == "\\":
131
+ index += 1
132
+ parts.append(re.escape(component[index]))
133
+ elif char == "*":
134
+ if parts or len(fragments) == 1:
135
+ fragments.append([])
136
+ elif char == "?":
137
+ parts.append("[^/]")
138
+ elif char == "[":
139
+ bracket = _BRACKET.match(component, index)
140
+ if bracket is None:
141
+ raise LedgerError("invalid", "claim glob has an unterminated bracket class")
142
+ parts.append(_translate_bracket(bracket))
143
+ index = bracket.end() - 1
144
+ else:
145
+ parts.append(re.escape(char))
146
+ index += 1
147
+ if len(fragments) == 1:
148
+ return "".join(fragments[0])
149
+ # Like fnmatch, commit interior stars to the shortest match. Each matching
150
+ # literal fragment has a fixed width and the next star can absorb any suffix.
151
+ stars = [f"(?>[^/]*?{''.join(parts)})" for parts in fragments[1:-1]]
152
+ return "".join([*fragments[0], *stars, "[^/]*", *fragments[-1]])
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class PathGlob:
157
+ components: tuple[re.Pattern[bytes] | None, ...]
158
+ directory_only: bool
159
+
160
+ def matches(self, path: str) -> bool:
161
+ parts = path.encode("utf-8", errors="surrogatepass").split(b"/")
162
+ end = len(self.components)
163
+ positions = {0}
164
+ for depth, part in enumerate(parts, start=1):
165
+ advanced: set[int] = set()
166
+ for position in positions:
167
+ component = self.components[position]
168
+ if component is None:
169
+ # ** may consume this segment or leave it to the next component.
170
+ advanced.add(position)
171
+ position += 1
172
+ component = self.components[position]
173
+ if component is not None and component.fullmatch(part):
174
+ advanced.add(position + 1)
175
+ if end in advanced:
176
+ if depth < len(parts) or not self.directory_only:
177
+ return True
178
+ advanced.remove(end)
179
+ if not advanced:
180
+ return False
181
+ positions = advanced
182
+ return False
183
+
184
+
185
+ def compile_glob(pattern: str) -> PathGlob:
186
+ """Compile a normalized gitignore-style glob for repository file paths."""
187
+ path = pattern.removeprefix("/").removesuffix("/")
188
+ components = _path_components(path)
189
+ if not pattern.startswith("/") and len(components) == 1:
190
+ components.insert(0, "**")
191
+ matchers: list[re.Pattern[bytes] | None] = []
192
+ try:
193
+ for component in components:
194
+ if len(component) >= 2 and set(component) == {"*"}:
195
+ if not matchers or matchers[-1] is not None:
196
+ matchers.append(None)
197
+ else:
198
+ # Git wildmatch counts UTF-8 bytes, including inside character classes.
199
+ raw_component = component.encode("utf-8").decode("latin-1")
200
+ matchers.append(re.compile(_translate_component(raw_component).encode("latin-1")))
201
+ except UnicodeEncodeError:
202
+ raise LedgerError("invalid", "claim glob must be valid UTF-8") from None
203
+ except re.PatternError:
204
+ raise LedgerError("invalid", "claim glob has an invalid bracket range") from None
205
+ if matchers[-1] is None:
206
+ # A trailing /** must match at least one component after its parent.
207
+ matchers.append(re.compile(rb"[^/]+"))
208
+ return PathGlob(tuple(matchers), pattern.endswith("/"))
209
+
210
+
211
+ def _patterns(values: list[Any]) -> list[str]:
212
+ if not values or not all(isinstance(value, str) for value in values):
213
+ raise LedgerError("invalid", "globs must contain one or more path patterns")
214
+ patterns = sorted({normalize_glob(value) for value in values})
215
+ for pattern in patterns:
216
+ compile_glob(pattern)
217
+ return patterns
218
+
219
+
220
+ async def _editable_lane(uow: UnitOfWork, lane_id: str) -> None:
221
+ lane = await uow.find_lane(lane_id)
222
+ if lane is None:
223
+ raise LedgerError("not_found", "lane not found")
224
+ if lane.state == "archived":
225
+ raise LedgerError("conflict", "lane is archived")
226
+
227
+
228
+ async def claim(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
229
+ lane: str = args["lane"]
230
+ await _editable_lane(uow, lane)
231
+ reason: str = args["reason"]
232
+ if not reason.strip():
233
+ raise LedgerError("invalid", "claim reason must be non-empty")
234
+ requested = [Claim(lane, pattern, reason) for pattern in _patterns(args["globs"])]
235
+ existing = set(await uow.lane_claims(lane))
236
+ changes = [entry for entry in requested if entry not in existing]
237
+ if changes:
238
+ await uow.save_claims(changes)
239
+ return {"claims": [entry.render() for entry in requested], "changed": bool(changes)}
240
+
241
+
242
+ async def release(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
243
+ lane: str = args["lane"]
244
+ await _editable_lane(uow, lane)
245
+ patterns = set(_patterns(args["globs"]))
246
+ released = [entry for entry in await uow.lane_claims(lane) if entry.glob in patterns]
247
+ if released:
248
+ await uow.delete_claims(lane, [entry.glob for entry in released])
249
+ return {"claims": [entry.render() for entry in released], "changed": bool(released)}
250
+
251
+
252
+ async def sync_items(uow: UnitOfWork, kind: str, desired: dict[str, dict[str, Any]]) -> None:
253
+ """Refresh one state-backed item per subject, preserving unchanged occurrences."""
254
+ active = await uow.active_item_subjects(kind)
255
+ for subject in sorted(active - desired.keys()):
256
+ await uow.clear_item(kind, subject)
257
+ for subject, context in sorted(desired.items()):
258
+ await uow.raise_item(kind, subject, "orchestrator", context)
259
+
260
+
261
+ def _shortest_prefixes(entries: list[tuple[Claim, str]]) -> list[str]:
262
+ """Drop descendants so each candidate needs only two neighbor checks."""
263
+ shortest: list[str] = []
264
+ for prefix in sorted({prefix for _, prefix in entries}):
265
+ if not shortest or not prefix.startswith(shortest[-1]):
266
+ shortest.append(prefix)
267
+ return shortest
268
+
269
+
270
+ def _comparable_prefix(prefix: str, ordered: list[str]) -> bool:
271
+ index = bisect_left(ordered, prefix)
272
+ return (index > 0 and prefix.startswith(ordered[index - 1])) or (
273
+ index < len(ordered) and ordered[index].startswith(prefix)
274
+ )
275
+
276
+
277
+ async def reconcile_claim_pairs(uow: UnitOfWork, claims: list[Claim]) -> None:
278
+ by_lane: dict[str, list[tuple[Claim, str]]] = defaultdict(list)
279
+ for entry in claims:
280
+ by_lane[entry.lane].append((entry, literal_prefix(entry.glob)))
281
+ indexes = {lane: _shortest_prefixes(entries) for lane, entries in by_lane.items()}
282
+ desired: dict[str, dict[str, Any]] = {}
283
+ for left, right in combinations(sorted(by_lane), 2):
284
+ participants = [
285
+ entry.render()
286
+ for lane, other in ((left, right), (right, left))
287
+ for entry, prefix in by_lane[lane]
288
+ if _comparable_prefix(prefix, indexes[other])
289
+ ]
290
+ if participants:
291
+ desired[json.dumps([left, right])] = {
292
+ "lanes": [left, right],
293
+ "prs": [],
294
+ "claims": participants,
295
+ }
296
+ await sync_items(uow, CLAIM_OVERLAP, desired)
@@ -0,0 +1,379 @@
1
+ """Import typed clerk rows through existing lane, trigger, and checklist rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ from collections.abc import Mapping
9
+ from typing import TYPE_CHECKING, Any, TypedDict, cast
10
+
11
+ from plotroom.core.events import FieldSpec, LedgerError, NewEvent, validate_fields
12
+ from plotroom.core.lanes import checklist_import, start_lane
13
+ from plotroom.core.merge_lane import lane_matches_branch
14
+ from plotroom.core.next_items import ItemKind
15
+ from plotroom.core.trigger_actions import NOTIFY, SEND, DeliveryRoute
16
+ from plotroom.core.triggers import LeafRegistry, create_trigger
17
+ from plotroom.core.work_items import refresh_idle_workers
18
+
19
+ if TYPE_CHECKING:
20
+ from plotroom.core.unit_of_work import UnitOfWork
21
+
22
+ CLERK_IMPORT_ENTRY = "core.clerk_import_entry"
23
+ CLERK_IMPORT_ENTRY_FIELDS = (FieldSpec("category", "str"), FieldSpec("id", "str"))
24
+
25
+ BIND_TRIGGER = ItemKind("clerk_import_bind_trigger", 20, False, ("Bind the legacy trigger",))
26
+ REVIEW_PULL = ItemKind("clerk_import_review_pull", 20, True, ("Review the legacy PR lane",))
27
+ SKIPPED_PULL = ItemKind("clerk_import_skipped_pull", 20, True, ("Review the legacy PR hold",))
28
+ CLERK_IMPORT_ITEMS = (BIND_TRIGGER, REVIEW_PULL, SKIPPED_PULL)
29
+
30
+ _PLACEHOLDER_NOTE = "Imported fire-time fields such as [sha8] and [N] are literal text."
31
+ _HOLD_STATE = re.compile(
32
+ r"(?:on[ \t]+hold|hold(?:ing)?|held)(?:$|[ \t]+(?:for|by|until|pending)\b|[ \t]*[:(—])",
33
+ re.IGNORECASE,
34
+ )
35
+ _TRIGGER_REF = re.compile(r"(?:Trigger[ \t]+)?(?:(T[0-9]+)|`(T[0-9]+)`)", re.IGNORECASE)
36
+
37
+
38
+ class TriggerImportRow(TypedDict):
39
+ label: str
40
+ source: str
41
+ predicate: dict[str, Any] | None
42
+ text: str | None
43
+ channel: str | None
44
+ notify: bool
45
+ fired: bool
46
+
47
+
48
+ class PullImportRow(TypedDict):
49
+ pr: int
50
+ worker: str
51
+ channel: str
52
+ state: str
53
+ after_merge: str
54
+
55
+
56
+ class SkipImportRow(TypedDict):
57
+ pr: int
58
+ reason: str
59
+
60
+
61
+ _TRIGGER_FIELDS = (
62
+ FieldSpec("label", "str"),
63
+ FieldSpec("source", "str"),
64
+ FieldSpec("predicate", "object", required=False),
65
+ FieldSpec("text", "str", required=False),
66
+ FieldSpec("channel", "str", required=False),
67
+ FieldSpec("notify", "bool"),
68
+ FieldSpec("fired", "bool"),
69
+ )
70
+ _PULL_FIELDS = (
71
+ FieldSpec("pr", "int"),
72
+ FieldSpec("worker", "str"),
73
+ FieldSpec("channel", "str"),
74
+ FieldSpec("state", "str"),
75
+ FieldSpec("after_merge", "str"),
76
+ )
77
+ _SKIP_FIELDS = (FieldSpec("pr", "int"), FieldSpec("reason", "str"))
78
+ _NULLABLE_TRIGGER_FIELDS = frozenset({"predicate", "text", "channel"})
79
+
80
+
81
+ def _digest(text: str) -> str:
82
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
83
+
84
+
85
+ def _trigger_id(label: str) -> str:
86
+ return f"trigger_clerk_{_digest(label)}"
87
+
88
+
89
+ def _label_source_receipt(label: str) -> str:
90
+ return f"trigger-source:{_digest(label)}"
91
+
92
+
93
+ def _ambiguous_label_receipt(label: str) -> str:
94
+ return f"ambiguous-trigger:{_digest(label)}"
95
+
96
+
97
+ def _exact_trigger_label(text: str) -> str | None:
98
+ # A checklist sentence mentioning a label is still a checklist sentence.
99
+ text = text.strip()
100
+ if text.startswith("`") and text.endswith("`"):
101
+ text = text[1:-1]
102
+ match = _TRIGGER_REF.fullmatch(text)
103
+ return (match[1] or match[2]).upper() if match else None
104
+
105
+
106
+ def _validated_rows(
107
+ values: list[Any],
108
+ fields: tuple[FieldSpec, ...],
109
+ key: str,
110
+ what: str,
111
+ *,
112
+ nullable: frozenset[str] = frozenset(),
113
+ ) -> list[dict[str, Any]]:
114
+ rows: dict[str | int, dict[str, Any]] = {}
115
+ for value in values:
116
+ if not isinstance(value, dict):
117
+ raise LedgerError("invalid", f"{what}: each row must be an object")
118
+ row = cast("dict[str, Any]", value)
119
+ validate_fields(
120
+ fields,
121
+ {name: data for name, data in row.items() if data is not None or name not in nullable},
122
+ what,
123
+ )
124
+ row = {**dict.fromkeys(nullable), **row}
125
+ for field in fields:
126
+ if isinstance(text := row[field.name], str):
127
+ try:
128
+ text.encode("utf-8")
129
+ except UnicodeError:
130
+ raise LedgerError("invalid", f"{what}: text must be valid UTF-8") from None
131
+ identity = cast("str | int", row[key])
132
+ if key == "pr" and not 0 < cast(int, identity) <= 2**63 - 1:
133
+ raise LedgerError("invalid", f"{what}: PR must be a positive SQLite integer")
134
+ if key == "label" and not cast(str, identity).strip():
135
+ raise LedgerError("invalid", f"{what}: trigger label must not be blank")
136
+ if identity in rows and rows[identity] != row:
137
+ raise LedgerError("invalid", f"{what}: conflicting rows for {identity!r}")
138
+ rows[identity] = row
139
+ return list(rows.values())
140
+
141
+
142
+ def _target_worker(channel: str, routes: Mapping[str, DeliveryRoute]) -> str | None:
143
+ candidates = [
144
+ worker
145
+ for worker, route in routes.items()
146
+ if channel == worker
147
+ or (route.channel == "switchboard" and channel == f"relay:{route.destination}")
148
+ or (
149
+ route.channel == "claude"
150
+ and channel in (route.destination, f"session-message:{route.destination}")
151
+ )
152
+ ]
153
+ return candidates[0] if len(candidates) == 1 else None
154
+
155
+
156
+ async def _bind(uow: UnitOfWork, row: TriggerImportRow, reason: str) -> tuple[str, str]:
157
+ item = await uow.raise_item(
158
+ BIND_TRIGGER.name,
159
+ f"{row['label']}:{_digest(row['source'])}",
160
+ "orchestrator",
161
+ {"label": row["label"], "source": row["source"], "reason": reason},
162
+ )
163
+ return "items", item.id
164
+
165
+
166
+ async def _import_trigger(
167
+ uow: UnitOfWork,
168
+ row: TriggerImportRow,
169
+ digest: str,
170
+ *,
171
+ repository: str | None,
172
+ registry: LeafRegistry,
173
+ routes: Mapping[str, DeliveryRoute],
174
+ ) -> tuple[str, str]:
175
+ predicate, text, channel = row["predicate"], row["text"], row["channel"]
176
+ label = row["label"]
177
+ source_key = _label_source_receipt(label)
178
+ source = await uow.find_event("core", CLERK_IMPORT_ENTRY, source_key)
179
+ if source is None:
180
+ await uow.append(
181
+ NewEvent(
182
+ "core", CLERK_IMPORT_ENTRY, source_key, {"category": "trigger_source", "id": digest}
183
+ )
184
+ )
185
+ elif source.fields["id"] != digest:
186
+ category, item_id = await _bind(
187
+ uow, row, "An imported trigger entry already has this label"
188
+ )
189
+ await uow.append(
190
+ NewEvent(
191
+ "core",
192
+ CLERK_IMPORT_ENTRY,
193
+ _ambiguous_label_receipt(label),
194
+ {"category": category, "id": item_id},
195
+ )
196
+ )
197
+ return category, item_id
198
+ if predicate is None or set(predicate) != {"pr_merged"} or not text or not text.strip():
199
+ return await _bind(uow, row, "The trigger needs an exact condition and recognized message")
200
+ if channel is not None:
201
+ worker = _target_worker(channel, routes)
202
+ if worker is None:
203
+ return await _bind(uow, row, "The channel does not match a unique configured worker")
204
+ action = {SEND: {"worker": worker, "text": text}}
205
+ elif row["notify"]:
206
+ action = {NOTIFY: {"text": text}}
207
+ else:
208
+ return await _bind(uow, row, "The trigger does not name a supported recipient")
209
+ try:
210
+ result = await create_trigger(
211
+ uow,
212
+ {"predicate": predicate, "action": action, "imported_fired": row["fired"]},
213
+ registry=registry,
214
+ repository=repository,
215
+ delivery_routes=routes,
216
+ imported_id=_trigger_id(label),
217
+ import_note=_PLACEHOLDER_NOTE if "[sha8]" in text or "[N]" in text else None,
218
+ notify_on_fire=channel is not None and row["notify"],
219
+ )
220
+ except LedgerError as exc:
221
+ if exc.code != "invalid":
222
+ raise
223
+ return await _bind(uow, row, exc.message)
224
+ return "triggers", result["id"]
225
+
226
+
227
+ async def _review_pull(uow: UnitOfWork, row: PullImportRow, reason: str) -> tuple[str, str]:
228
+ context = dict(row)
229
+ context.pop("state")
230
+ item = await uow.raise_item(
231
+ REVIEW_PULL.name, str(row["pr"]), "orchestrator", {**context, "reason": reason}
232
+ )
233
+ return "items", item.id
234
+
235
+
236
+ async def _import_pull(
237
+ uow: UnitOfWork, row: PullImportRow, *, repository: str | None, workers: frozenset[str]
238
+ ) -> tuple[str, str]:
239
+ worker, number = row["worker"], row["pr"]
240
+ if worker not in workers:
241
+ return await _review_pull(uow, row, "The PR owner is not a configured worker")
242
+ if repository is None:
243
+ return await _review_pull(uow, row, "No GitHub projection is configured")
244
+ pull = await uow.pull_request(repository, number)
245
+ if (
246
+ pull is None
247
+ or not pull.complete
248
+ or pull.state != "open"
249
+ or pull.head_repository != repository
250
+ or not pull.branch.strip()
251
+ or not pull.head_sha.strip()
252
+ or pull != await uow.open_branch_pull(repository, pull.branch)
253
+ ):
254
+ return await _review_pull(uow, row, "The PR has no unambiguous open projected head branch")
255
+ lane = f"clerk-pr-{number}"
256
+ if (
257
+ await uow.find_lane(lane) is not None
258
+ or await uow.worker_lane(worker) is not None
259
+ or any(
260
+ active.branch == pull.branch or lane_matches_branch(active, pull.branch)
261
+ for active in await uow.active_lanes()
262
+ )
263
+ ):
264
+ return await _review_pull(uow, row, "The worker, branch, or PR already has a lane")
265
+ after_merge = row["after_merge"]
266
+ label = _exact_trigger_label(after_merge)
267
+ trigger = None
268
+ if label is not None and not await uow.find_event(
269
+ "core", CLERK_IMPORT_ENTRY, _ambiguous_label_receipt(label)
270
+ ):
271
+ trigger = await uow.find_trigger(_trigger_id(label))
272
+ await start_lane(
273
+ uow,
274
+ {"lane": lane, "worker": worker, "branch": pull.branch, "work_items": []},
275
+ workers=workers,
276
+ imported_channel=row["channel"],
277
+ imported_trigger_id=trigger.id if trigger is not None else None,
278
+ refresh_idle=False,
279
+ )
280
+ if trigger is None and after_merge.strip():
281
+ await checklist_import(
282
+ uow,
283
+ {
284
+ "lane": lane,
285
+ "rows": [
286
+ {
287
+ "step": after_merge,
288
+ "owner": worker,
289
+ "ref": f"clerk-ledger:#{number}",
290
+ }
291
+ ],
292
+ },
293
+ repository=repository,
294
+ )
295
+ return "lanes", lane
296
+
297
+
298
+ async def _import_skip(uow: UnitOfWork, row: SkipImportRow) -> tuple[str, str]:
299
+ item = await uow.raise_item(SKIPPED_PULL.name, str(row["pr"]), "orchestrator", dict(row))
300
+ return "items", item.id
301
+
302
+
303
+ async def clerk_import(
304
+ uow: UnitOfWork,
305
+ args: dict[str, Any],
306
+ *,
307
+ repository: str | None,
308
+ workers: frozenset[str],
309
+ registry: LeafRegistry,
310
+ delivery_routes: Mapping[str, DeliveryRoute],
311
+ ) -> dict[str, Any]:
312
+ """Apply the import and journal its rows atomically within the writer command."""
313
+ declared = args.get("ledger_repository")
314
+ if declared is None and (args["pulls"] or args["skips"]):
315
+ raise LedgerError("invalid", "a clerk ledger repository is required")
316
+ if declared is not None and declared.lower() != repository:
317
+ raise LedgerError("conflict", "the clerk ledger repository does not match this project")
318
+ triggers = _validated_rows(
319
+ args["triggers"],
320
+ _TRIGGER_FIELDS,
321
+ "label",
322
+ "clerk trigger",
323
+ nullable=_NULLABLE_TRIGGER_FIELDS,
324
+ )
325
+ pulls = _validated_rows(args["pulls"], _PULL_FIELDS, "pr", "clerk PR")
326
+ skips = _validated_rows(args["skips"], _SKIP_FIELDS, "pr", "clerk skip")
327
+ explicit_holds = {row["pr"] for row in skips}
328
+ skips.extend(
329
+ {"pr": row["pr"], "reason": row["state"]}
330
+ for row in pulls
331
+ if row["pr"] not in explicit_holds and _HOLD_STATE.match(row["state"].strip())
332
+ )
333
+ result: dict[str, dict[str, str]] = {"triggers": {}, "lanes": {}, "items": {}}
334
+ added_lane = False
335
+ for kind, rows, key in (
336
+ ("trigger", triggers, "label"),
337
+ ("pull", pulls, "pr"),
338
+ ("skip", skips, "pr"),
339
+ ):
340
+ for row in rows:
341
+ source_id = str(row[key])
342
+ # State changes affect hold advisories independently of lane identity.
343
+ stable = {name: value for name, value in row.items() if name != "state"}
344
+ digest = _digest(json.dumps(stable, sort_keys=True, separators=(",", ":")))
345
+ receipt_id = f"{kind}:{digest}"
346
+ receipt = await uow.find_event("core", CLERK_IMPORT_ENTRY, receipt_id)
347
+ if receipt is not None:
348
+ category, identifier = receipt.fields["category"], receipt.fields["id"]
349
+ else:
350
+ if kind == "trigger":
351
+ category, identifier = await _import_trigger(
352
+ uow,
353
+ cast(TriggerImportRow, row),
354
+ digest,
355
+ repository=repository,
356
+ registry=registry,
357
+ routes=delivery_routes,
358
+ )
359
+ elif kind == "pull":
360
+ category, identifier = await _import_pull(
361
+ uow, cast(PullImportRow, row), repository=repository, workers=workers
362
+ )
363
+ added_lane = added_lane or category == "lanes"
364
+ else:
365
+ category, identifier = await _import_skip(uow, cast(SkipImportRow, row))
366
+ await uow.append(
367
+ NewEvent(
368
+ "core",
369
+ CLERK_IMPORT_ENTRY,
370
+ receipt_id,
371
+ {"category": category, "id": identifier},
372
+ lane_id=identifier if category == "lanes" else None,
373
+ )
374
+ )
375
+ result_key = f"{kind}:{source_id}" if category == "items" else source_id
376
+ result[category][result_key] = identifier
377
+ if added_lane:
378
+ await refresh_idle_workers(uow, workers)
379
+ return result