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,85 @@
1
+ """Mutating commands (AD-2, AD-14): deduplicated by ``request_id`` and recorded as events.
2
+
3
+ A command's first run appends the handler's own events and then one ``core.<command>`` event with
4
+ ``upstream_id = <role>:<request_id>`` holding the arguments and the result, all in one
5
+ transaction. A retry finds that event and returns its result without running the handler.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections.abc import Awaitable, Callable
12
+ from dataclasses import dataclass
13
+ from typing import Any
14
+
15
+ from plotroom.core.events import EventKind, EventRegistry, FieldSpec, LedgerError
16
+ from plotroom.core.roles import WriterRule
17
+ from plotroom.core.unit_of_work import UnitOfWork
18
+
19
+ CommandHandler = Callable[[UnitOfWork, dict[str, Any]], Awaitable[dict[str, Any]]]
20
+ _NAME = re.compile(r"[a-z][a-z0-9_]*")
21
+
22
+ COMMAND_SOURCE = "core"
23
+ COMMAND_APPENDER = "system"
24
+ COMMAND_FIELDS: tuple[FieldSpec, ...] = (
25
+ FieldSpec("role", "str"),
26
+ FieldSpec("request_id", "str"),
27
+ FieldSpec("args", "object"),
28
+ FieldSpec("result", "object"),
29
+ )
30
+
31
+
32
+ class CommandError(LedgerError):
33
+ """A handler's refusal. It rolls the command back and reaches the caller with its code."""
34
+
35
+
36
+ def command_kind(name: str) -> str:
37
+ return f"{COMMAND_SOURCE}.{name}"
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Command:
42
+ """A registered command: its name, typed arguments and handler.
43
+
44
+ The handler runs inside the writer transaction with the unit of work and the validated
45
+ arguments, and returns a JSON object: the command's result. An optional read-only preflight
46
+ receives validated, authorized arguments outside the writer. Recorded replays skip preflight.
47
+ """
48
+
49
+ name: str
50
+ args: tuple[FieldSpec, ...]
51
+ handler: CommandHandler
52
+ record_if: Callable[[dict[str, Any]], bool] | None = None
53
+ lane_scoped: bool = False
54
+ preflight: Callable[[dict[str, Any]], Awaitable[None]] | None = None
55
+
56
+ def __post_init__(self) -> None:
57
+ if not _NAME.fullmatch(self.name):
58
+ raise ValueError(f"command name {self.name!r} must be lowercase letters, digits, _")
59
+ if self.lane_scoped and FieldSpec("lane", "str") not in self.args:
60
+ raise ValueError(f"lane-scoped command {self.name!r} requires a lane argument")
61
+
62
+
63
+ class CommandRegistry:
64
+ """The one registry of commands. Registering one registers its ``core.<name>`` event kind."""
65
+
66
+ def __init__(self, events: EventRegistry) -> None:
67
+ self._events = events
68
+ self._commands: dict[str, Command] = {}
69
+
70
+ def register(self, command: Command, *, rules: tuple[WriterRule, ...] = ()) -> None:
71
+ if command.name in self._commands:
72
+ raise ValueError(f"command {command.name!r} is already registered")
73
+ kind = command_kind(command.name)
74
+ if self._events.get(kind) is not None:
75
+ raise ValueError(f"event kind {kind!r} is already registered")
76
+ self._events.writer_rules.declare(command.name, rules)
77
+ self._events.register(EventKind(kind, COMMAND_FIELDS, frozenset({COMMAND_APPENDER})))
78
+ self._commands[command.name] = command
79
+
80
+ def get(self, name: str) -> Command | None:
81
+ return self._commands.get(name)
82
+
83
+ @property
84
+ def names(self) -> tuple[str, ...]:
85
+ return tuple(sorted(self._commands))
@@ -0,0 +1,21 @@
1
+ """Project-local deploy window commands."""
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from plotroom.core.events import LedgerError
6
+
7
+ if TYPE_CHECKING:
8
+ from plotroom.core.unit_of_work import UnitOfWork
9
+
10
+
11
+ async def freeze(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
12
+ reason: str = args["reason"]
13
+ if not reason.strip():
14
+ raise LedgerError("invalid", "freeze reason must not be blank")
15
+ await uow.set_deploy_freeze(reason)
16
+ return {"frozen": True, "reason": reason}
17
+
18
+
19
+ async def unfreeze(uow: UnitOfWork, _args: dict[str, Any]) -> dict[str, Any]:
20
+ await uow.set_deploy_freeze(None)
21
+ return {"frozen": False, "reason": None}
@@ -0,0 +1,20 @@
1
+ """The tool result envelope: ``{ok, data}`` or ``{ok: false, error: {code, message}}``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal, get_args
6
+
7
+ ErrorCode = Literal["forbidden", "not_found", "conflict", "invalid", "unavailable"]
8
+ ERROR_CODES: tuple[str, ...] = get_args(ErrorCode)
9
+
10
+
11
+ def ok(data: Any) -> dict[str, Any]:
12
+ """Wrap a successful result."""
13
+ return {"ok": True, "data": data}
14
+
15
+
16
+ def err(code: ErrorCode, message: str) -> dict[str, Any]:
17
+ """Wrap a failure; ``code`` must be one of the declared codes."""
18
+ if code not in ERROR_CODES:
19
+ raise ValueError(f"unknown error code {code!r}; expected one of {ERROR_CODES}")
20
+ return {"ok": False, "error": {"code": code, "message": message}}
@@ -0,0 +1,227 @@
1
+ """Typed events and the event-kind registry (AD-2).
2
+
3
+ Every input becomes one event ``(seq, id, source, kind, upstream_id, lane_id?, fields, body,
4
+ observed_at)``. The registry declares, per kind, its typed ``fields`` and the role families that
5
+ may append it; ``validate_append`` is the single check.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from datetime import UTC, datetime
14
+ from typing import Any, Literal, get_args
15
+
16
+ from plotroom.core.envelope import ERROR_CODES, ErrorCode
17
+ from plotroom.core.roles import ROLE_FAMILIES, WriterRule, WriterRules, role_family
18
+
19
+ FieldType = Literal["str", "int", "bool", "number", "object", "array"]
20
+ FIELD_TYPES: tuple[str, ...] = get_args(FieldType)
21
+ _KIND = re.compile(r"[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*")
22
+
23
+
24
+ class LedgerError(Exception):
25
+ """A refused input. ``code`` is one of the envelope's error codes."""
26
+
27
+ def __init__(self, code: ErrorCode, message: str) -> None:
28
+ if code not in ERROR_CODES:
29
+ raise ValueError(f"unknown error code {code!r}; expected one of {ERROR_CODES}")
30
+ super().__init__(message)
31
+ self.code: ErrorCode = code
32
+ self.message = message
33
+
34
+
35
+ def format_time(moment: datetime) -> str:
36
+ """UTC, RFC 3339 with ``Z`` and fixed microsecond precision, so text order is time order."""
37
+ if moment.tzinfo is None or moment.utcoffset() is None:
38
+ raise ValueError("a clock must return a timezone-aware datetime")
39
+ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class FieldSpec:
44
+ """One declared field of an event kind (or one argument of a command)."""
45
+
46
+ name: str
47
+ type: FieldType
48
+ required: bool = True
49
+
50
+ def __post_init__(self) -> None:
51
+ if not self.name:
52
+ raise ValueError("a field needs a name")
53
+ if self.type not in FIELD_TYPES:
54
+ raise ValueError(f"field {self.name!r}: unknown type {self.type!r}")
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class NewEvent:
59
+ """An input not yet stored: no ``seq``, ``id`` or ``observed_at`` (the ledger assigns them)."""
60
+
61
+ source: str
62
+ kind: str
63
+ upstream_id: str
64
+ fields: dict[str, Any] = field(default_factory=lambda: {})
65
+ body: str = ""
66
+ lane_id: str | None = None
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Event:
71
+ """A stored event."""
72
+
73
+ seq: int
74
+ id: str
75
+ source: str
76
+ kind: str
77
+ upstream_id: str
78
+ lane_id: str | None
79
+ fields: dict[str, Any]
80
+ body: str
81
+ observed_at: str
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class AppendResult:
86
+ """The event now stored for the appended identity; ``created`` is false for a duplicate."""
87
+
88
+ event: Event
89
+ created: bool
90
+
91
+
92
+ def is_json(value: Any) -> bool:
93
+ """Whether ``value`` is plain JSON: dicts with string keys, lists, strings, finite numbers."""
94
+ if value is None or isinstance(value, (str, bool, int)):
95
+ return True
96
+ if isinstance(value, float):
97
+ return math.isfinite(value)
98
+ if isinstance(value, list):
99
+ return all(is_json(item) for item in value) # pyright: ignore[reportUnknownVariableType]
100
+ if isinstance(value, dict):
101
+ return all(
102
+ isinstance(key, str) and is_json(item)
103
+ for key, item in value.items() # pyright: ignore[reportUnknownVariableType]
104
+ )
105
+ return False
106
+
107
+
108
+ def _has_type(value: Any, expected: str) -> bool:
109
+ # bool is a subclass of int; a flag is never an integer or a number here
110
+ if isinstance(value, bool):
111
+ return expected == "bool"
112
+ if expected == "str":
113
+ return isinstance(value, str)
114
+ if expected == "int":
115
+ return isinstance(value, int)
116
+ if expected == "number":
117
+ # an int of any size is a number; isfinite() would overflow converting it to a float
118
+ return isinstance(value, int) or (isinstance(value, float) and math.isfinite(value))
119
+ if expected == "object":
120
+ return isinstance(value, dict)
121
+ if expected == "array":
122
+ return isinstance(value, list)
123
+ return False
124
+
125
+
126
+ def validate_fields(specs: tuple[FieldSpec, ...], values: dict[str, Any], what: str) -> None:
127
+ """Refuse missing, unknown and mistyped fields, and values that are not JSON."""
128
+ declared = {spec.name: spec for spec in specs}
129
+ for name in values:
130
+ if name not in declared:
131
+ raise LedgerError("invalid", f"{what}: unknown field {name!r}")
132
+ for spec in specs:
133
+ if spec.name not in values:
134
+ if spec.required:
135
+ raise LedgerError("invalid", f"{what}: missing required field {spec.name!r}")
136
+ continue
137
+ value = values[spec.name]
138
+ if not _has_type(value, spec.type):
139
+ raise LedgerError("invalid", f"{what}: field {spec.name!r} must be of type {spec.type}")
140
+ if not is_json(value):
141
+ raise LedgerError("invalid", f"{what}: field {spec.name!r} must be JSON")
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class EventKind:
146
+ """A registered kind: ``<source>.<name>``, its fields and the role families that append it."""
147
+
148
+ kind: str
149
+ fields: tuple[FieldSpec, ...]
150
+ appenders: frozenset[str]
151
+
152
+ def __post_init__(self) -> None:
153
+ if not _KIND.fullmatch(self.kind):
154
+ raise ValueError(f"event kind {self.kind!r} must look like <source>.<name>")
155
+ names = [spec.name for spec in self.fields]
156
+ if len(set(names)) != len(names):
157
+ raise ValueError(f"event kind {self.kind!r} declares a field twice")
158
+ unknown = self.appenders - ROLE_FAMILIES
159
+ if unknown or not self.appenders:
160
+ raise ValueError(
161
+ f"event kind {self.kind!r}: appenders must be a non-empty subset of "
162
+ f"{sorted(ROLE_FAMILIES)}, got {sorted(self.appenders)}"
163
+ )
164
+
165
+ @property
166
+ def source(self) -> str:
167
+ """The upstream system the kind belongs to: its prefix."""
168
+ return self.kind.partition(".")[0]
169
+
170
+
171
+ class EventRegistry:
172
+ """The one registry of event kinds."""
173
+
174
+ def __init__(self) -> None:
175
+ self._kinds: dict[str, EventKind] = {}
176
+ self.writer_rules = WriterRules()
177
+
178
+ def register(self, kind: EventKind) -> None:
179
+ if kind.kind in self._kinds:
180
+ raise ValueError(f"event kind {kind.kind!r} is already registered")
181
+ self.writer_rules.declare(kind.kind, tuple(WriterRule(role) for role in kind.appenders))
182
+ self._kinds[kind.kind] = kind
183
+
184
+ def get(self, kind: str) -> EventKind | None:
185
+ return self._kinds.get(kind)
186
+
187
+ @property
188
+ def kinds(self) -> tuple[str, ...]:
189
+ return tuple(sorted(self._kinds))
190
+
191
+ def validate_identity(self, role: str, event: NewEvent) -> EventKind:
192
+ """The registered kind when ``role`` may append ``event``'s identity; else ``LedgerError``.
193
+
194
+ Checks everything that names the event, not its declared fields: ``invalid`` for a
195
+ malformed role, an unregistered kind, a ``source`` that is not the kind's prefix, a bad
196
+ ``upstream_id``, ``body``, ``lane_id`` or a ``fields`` that is not an object;
197
+ ``forbidden`` when the role's family is not an appender.
198
+ """
199
+ try:
200
+ family = role_family(role)
201
+ except ValueError as exc:
202
+ raise LedgerError("invalid", str(exc)) from None
203
+ registered = self._kinds.get(event.kind)
204
+ if registered is None:
205
+ raise LedgerError("invalid", f"unknown event kind {event.kind!r}")
206
+ if event.source != registered.source:
207
+ raise LedgerError(
208
+ "invalid",
209
+ f"{event.kind}: source must be {registered.source!r}, got {event.source!r}",
210
+ )
211
+ if self.writer_rules.rule_for(event.kind, family) is None:
212
+ raise LedgerError("forbidden", f"role {role!r} may not append {event.kind}")
213
+ if not isinstance(event.upstream_id, str) or not event.upstream_id: # pyright: ignore[reportUnnecessaryIsInstance]
214
+ raise LedgerError("invalid", f"{event.kind}: upstream_id must be a non-empty string")
215
+ if not isinstance(event.body, str): # pyright: ignore[reportUnnecessaryIsInstance]
216
+ raise LedgerError("invalid", f"{event.kind}: body must be a string")
217
+ if event.lane_id is not None and (not isinstance(event.lane_id, str) or not event.lane_id): # pyright: ignore[reportUnnecessaryIsInstance]
218
+ raise LedgerError("invalid", f"{event.kind}: lane_id must be a non-empty string")
219
+ if not isinstance(event.fields, dict): # pyright: ignore[reportUnnecessaryIsInstance]
220
+ raise LedgerError("invalid", f"{event.kind}: fields must be an object")
221
+ return registered
222
+
223
+ def validate_append(self, role: str, event: NewEvent) -> EventKind:
224
+ """``validate_identity`` and then the per-field check: what a new event must pass."""
225
+ registered = self.validate_identity(role, event)
226
+ validate_fields(registered.fields, event.fields, event.kind)
227
+ return registered
@@ -0,0 +1,306 @@
1
+ """Typed GitHub facts and their project pull request projection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, replace
7
+ from typing import TYPE_CHECKING, Literal
8
+
9
+ from plotroom.core.events import FieldSpec, NewEvent
10
+ from plotroom.core.github_projection import (
11
+ ASK_COMMENT_HISTORY,
12
+ COMMENTS,
13
+ FILES,
14
+ ISSUES,
15
+ GitHubRecord,
16
+ GitHubResource,
17
+ apply_resource,
18
+ ask_history_version,
19
+ projected_issues,
20
+ )
21
+ from plotroom.core.lanes import infer_lane, refresh_ready_lanes
22
+
23
+ if TYPE_CHECKING:
24
+ from plotroom.core.unit_of_work import UnitOfWork
25
+
26
+ PULL_REQUESTS = "pull_requests"
27
+ SNAPSHOT_HEALTH = "snapshot_health"
28
+ DETAILS = "details"
29
+ PULL_DETAIL_ATTEMPT_PREFIX = "pull_details/"
30
+ ACTIVE_PULL_DETAIL_BUDGET = 17
31
+ TERMINAL_PULL_DETAIL_BUDGET = 2
32
+ MERGE_SHA_ATTEMPT_PREFIX = "pull_merge_sha/"
33
+ PR_OPENED = "github.pr_opened"
34
+ PR_MERGED = "github.pr_merged"
35
+ PR_CLOSED = "github.pr_closed"
36
+ PR_REOPENED = "github.pr_reopened"
37
+ PR_HEAD_CHANGED = "github.pr_head_changed"
38
+ PR_KINDS = (PR_OPENED, PR_MERGED, PR_CLOSED, PR_REOPENED, PR_HEAD_CHANGED)
39
+ PR_FIELDS = (
40
+ FieldSpec("repository", "str"),
41
+ FieldSpec("number", "int"),
42
+ FieldSpec("branch", "str"),
43
+ FieldSpec("head_sha", "str"),
44
+ FieldSpec("head_repository", "str", required=False),
45
+ FieldSpec("state", "str"),
46
+ FieldSpec("updated_at", "str"),
47
+ )
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class ObservedPull:
52
+ number: int
53
+ branch: str
54
+ head_sha: str
55
+ head_repository: str | None
56
+ state: Literal["open", "closed", "merged"]
57
+ updated_at: str
58
+ body: str
59
+ draft: bool | None = False
60
+ merge_commit_sha: str | None = None
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class PullRequest:
65
+ repository: str
66
+ number: int
67
+ branch: str
68
+ head_sha: str
69
+ head_repository: str | None
70
+ state: str
71
+ updated_at: str
72
+ as_of: str
73
+ complete: bool
74
+ version: int
75
+ draft: bool | None = False
76
+ merge_commit_sha: str | None = None
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class FetchCursor:
81
+ watermark: str
82
+ as_of: str
83
+ generation: int
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class FetchRetry:
88
+ until: str
89
+ next_backoff: int
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class GitHubSummary:
94
+ open_prs: int
95
+ as_of: str | None
96
+
97
+
98
+ def valid_git_sha(value: object) -> bool:
99
+ return isinstance(value, str) and re.fullmatch(r"[0-9a-f]{40}", value) is not None
100
+
101
+
102
+ async def apply_merge_sha_backfill(
103
+ uow: UnitOfWork, target: PullRequest, merge_sha: str | None, as_of: str
104
+ ) -> None:
105
+ resource = f"{MERGE_SHA_ATTEMPT_PREFIX}{target.number}"
106
+ prior = await uow.fetch_cursor(target.repository, resource)
107
+ await uow.save_fetch_cursor(
108
+ target.repository,
109
+ resource,
110
+ FetchCursor(
111
+ "", max(as_of, prior.as_of) if prior else as_of, prior.generation + 1 if prior else 1
112
+ ),
113
+ )
114
+ if merge_sha is None or not valid_git_sha(merge_sha):
115
+ return
116
+ current = await uow.pull_request(target.repository, target.number)
117
+ if (
118
+ current is None
119
+ or not current.complete
120
+ or current.state != "merged"
121
+ or current.merge_commit_sha is not None
122
+ or current.head_sha != target.head_sha
123
+ ):
124
+ return
125
+ await uow.save_pull_request(replace(current, merge_commit_sha=merge_sha), merge_sha_only=True)
126
+
127
+
128
+ async def apply_pull_poll(
129
+ uow: UnitOfWork,
130
+ repository: str,
131
+ baseline: FetchCursor | None,
132
+ pulls: tuple[ObservedPull, ...],
133
+ as_of: str,
134
+ ) -> bool:
135
+ if await uow.fetch_cursor(repository, PULL_REQUESTS) != baseline:
136
+ return False
137
+ branches: set[str] = set()
138
+ for observed in pulls:
139
+ await _project_pull(uow, repository, observed, as_of, branches, initial=baseline is None)
140
+ for branch in sorted(branches):
141
+ await refresh_ready_lanes(uow, repository, branch)
142
+ watermark = max((pull.updated_at for pull in pulls), default="")
143
+ if baseline is not None:
144
+ watermark = max(baseline.watermark, watermark)
145
+ await uow.save_fetch_cursor(
146
+ repository,
147
+ PULL_REQUESTS,
148
+ FetchCursor(watermark, as_of, 1 if baseline is None else baseline.generation + 1),
149
+ )
150
+ await uow.save_fetch_retry(repository, PULL_REQUESTS, None)
151
+ return True
152
+
153
+
154
+ def _changes(current: PullRequest | None, observed: ObservedPull) -> tuple[str, ...]:
155
+ by_state = {
156
+ "open": PR_OPENED if current is None else PR_REOPENED,
157
+ "closed": PR_CLOSED,
158
+ "merged": PR_MERGED,
159
+ }
160
+ if current is None:
161
+ return (by_state[observed.state],)
162
+ changes: list[str] = []
163
+ if (current.branch, current.head_sha, current.head_repository) != (
164
+ observed.branch,
165
+ observed.head_sha,
166
+ observed.head_repository,
167
+ ):
168
+ changes.append(PR_HEAD_CHANGED)
169
+ if current.state != observed.state:
170
+ changes.append(by_state[observed.state])
171
+ return tuple(changes)
172
+
173
+
174
+ async def _project_pull(
175
+ uow: UnitOfWork,
176
+ repository: str,
177
+ observed: ObservedPull,
178
+ as_of: str,
179
+ branches: set[str],
180
+ *,
181
+ initial: bool,
182
+ ) -> None:
183
+ current = await uow.pull_request(repository, observed.number)
184
+ if current is not None and (
185
+ current.updated_at > observed.updated_at
186
+ or (current.state == "merged" and observed.state != "merged")
187
+ ):
188
+ return
189
+ await uow.index_pull_body(repository, observed.number, observed.body)
190
+ changes = _changes(current, observed)
191
+ previous_version = current.version if current is not None else 0
192
+ projected = PullRequest(
193
+ repository,
194
+ observed.number,
195
+ observed.branch,
196
+ observed.head_sha,
197
+ observed.head_repository,
198
+ observed.state,
199
+ observed.updated_at,
200
+ as_of,
201
+ True,
202
+ previous_version + len(changes),
203
+ observed.draft,
204
+ current.merge_commit_sha
205
+ if current is not None and current.merge_commit_sha is not None
206
+ else observed.merge_commit_sha,
207
+ )
208
+ if current is not None and current.head_sha != projected.head_sha:
209
+ files = await uow.github_resource(repository, FILES, str(projected.number))
210
+ if files is not None and files.attributes.get("head_sha") is not None:
211
+ await apply_resource(
212
+ uow,
213
+ repository,
214
+ FILES,
215
+ str(projected.number),
216
+ GitHubResource((), complete=False, attributes={"head_sha": None}),
217
+ as_of,
218
+ )
219
+ if not changes:
220
+ if current != projected:
221
+ await uow.save_pull_request(projected)
222
+ return
223
+ if current is not None and current.head_repository == repository:
224
+ branches.add(current.branch)
225
+ if projected.head_repository == repository:
226
+ branches.add(projected.branch)
227
+ lane_id = (
228
+ await infer_lane(uow, branch=projected.branch)
229
+ if projected.head_repository == repository
230
+ else None
231
+ )
232
+ fields = {
233
+ "repository": repository,
234
+ "number": projected.number,
235
+ "branch": projected.branch,
236
+ "head_sha": projected.head_sha,
237
+ "state": projected.state,
238
+ "updated_at": projected.updated_at,
239
+ }
240
+ if projected.head_repository is not None:
241
+ fields["head_repository"] = projected.head_repository
242
+ for version, kind in enumerate(changes, start=previous_version + 1):
243
+ uid = f"{repository}#{projected.number}@{version}:{projected.updated_at}"
244
+ await uow.append(NewEvent("github", kind, uid, fields, observed.body, lane_id))
245
+ await uow.save_pull_request(projected, historical=initial and current is None)
246
+ uow.pull_overlaps_changed()
247
+
248
+
249
+ async def apply_comments(
250
+ uow: UnitOfWork,
251
+ repository: str,
252
+ baseline: FetchCursor | None,
253
+ comments: tuple[GitHubRecord, ...],
254
+ watermark: str,
255
+ as_of: str,
256
+ *,
257
+ cursor_resource: str = COMMENTS,
258
+ ) -> None:
259
+ if await uow.fetch_cursor(repository, cursor_resource) != baseline:
260
+ return
261
+ await _apply_comment_records(uow, repository, comments, as_of)
262
+ await uow.save_fetch_cursor(
263
+ repository,
264
+ cursor_resource,
265
+ FetchCursor(watermark, as_of, baseline.generation + 1 if baseline else 1),
266
+ )
267
+
268
+
269
+ async def _apply_comment_records(
270
+ uow: UnitOfWork, repository: str, comments: tuple[GitHubRecord, ...], as_of: str
271
+ ) -> None:
272
+ for comment in comments:
273
+ prior = await uow.github_resource(repository, COMMENTS, comment.key)
274
+ if prior and prior.records[0].fields["updated_at"] > comment.fields["updated_at"]:
275
+ continue
276
+ if prior is None or prior.records != (comment,):
277
+ await apply_resource(
278
+ uow, repository, COMMENTS, comment.key, GitHubResource((comment,)), as_of
279
+ )
280
+
281
+
282
+ async def apply_ask_comment_history(
283
+ uow: UnitOfWork,
284
+ repository: str,
285
+ number: int,
286
+ version: str,
287
+ comments: tuple[GitHubRecord, ...],
288
+ as_of: str,
289
+ ) -> None:
290
+ issue = projected_issues(await uow.github_resource(repository, ISSUES)).get(number)
291
+ if issue is None or ask_history_version(issue) != (version, len(comments)):
292
+ return
293
+ await _apply_comment_records(uow, repository, comments, as_of)
294
+ await uow.save_github_resource(
295
+ repository,
296
+ ASK_COMMENT_HISTORY,
297
+ str(number),
298
+ GitHubResource(
299
+ (),
300
+ attributes={
301
+ "version": version,
302
+ "comment_ids": [row.fields["id"] for row in comments],
303
+ },
304
+ as_of=as_of,
305
+ ),
306
+ )