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,70 @@
1
+ """Branch identity for the merge controller's one-open-PR rule."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fnmatch import fnmatchcase
6
+ from typing import TYPE_CHECKING
7
+
8
+ if TYPE_CHECKING:
9
+ from plotroom.core.github import PullRequest
10
+ from plotroom.core.lanes import Lane
11
+ from plotroom.core.unit_of_work import UnitOfWork
12
+ from plotroom.ports.store import Transaction
13
+
14
+
15
+ def lane_matches_branch(lane: Lane, branch: str) -> bool:
16
+ """Apply the merge gate branch rule to a current lane."""
17
+ if lane.state == "archived":
18
+ return False
19
+ if lane.branch_pattern is None:
20
+ return branch == lane.branch
21
+ return fnmatchcase(branch, lane.branch_pattern)
22
+
23
+
24
+ class MergeLaneIndex:
25
+ """Bind branch patterns and first PRs once for one consistent repository view."""
26
+
27
+ def __init__(self, lanes: list[Lane], pulls: tuple[PullRequest, ...]) -> None:
28
+ self._lanes = lanes
29
+ self._matches: dict[str, tuple[Lane, ...]] = {}
30
+ self._first: dict[str, int] = {}
31
+ for pull in pulls if lanes else ():
32
+ if pull.head_repository != pull.repository or not pull.branch:
33
+ continue
34
+ for lane in self._matching(pull.branch):
35
+ first = self._first.get(lane.id)
36
+ if first is None or pull.number < first:
37
+ self._first[lane.id] = pull.number
38
+
39
+ def _matching(self, branch: str) -> tuple[Lane, ...]:
40
+ if branch not in self._matches:
41
+ self._matches[branch] = tuple(
42
+ lane for lane in self._lanes if lane_matches_branch(lane, branch)
43
+ )
44
+ return self._matches[branch]
45
+
46
+ def evidence(self, pull: PullRequest | None) -> tuple[Lane | None, int | None, bool]:
47
+ if pull is None or pull.head_repository != pull.repository or not pull.branch:
48
+ return None, None, False
49
+ matches = self._matching(pull.branch)
50
+ if len(matches) != 1:
51
+ return None, None, bool(matches)
52
+ lane = matches[0]
53
+ first = self._first.get(lane.id)
54
+ earlier = (
55
+ first if pull.state == "open" and first is not None and first < pull.number else None
56
+ )
57
+ return lane, earlier, False
58
+
59
+
60
+ async def merge_lane_evidence(
61
+ reader: Transaction | UnitOfWork, pull: PullRequest | None
62
+ ) -> tuple[Lane | None, int | None, bool]:
63
+ """Resolve the same evidence for one ad hoc gate read."""
64
+ if pull is None or pull.head_repository != pull.repository or not pull.branch:
65
+ return None, None, False
66
+ lanes = await reader.active_lanes()
67
+ if not lanes:
68
+ return None, None, False
69
+ index = MergeLaneIndex(lanes, await reader.open_pulls(pull.repository))
70
+ return index.evidence(pull)
@@ -0,0 +1,76 @@
1
+ """Pinned net file overlap and head-specific label bindings."""
2
+
3
+ import re
4
+ from dataclasses import replace
5
+ from typing import cast
6
+
7
+ from plotroom.core.github import PullRequest
8
+ from plotroom.core.github_projection import GitHubResource
9
+
10
+ PULL_COMPARISON = "pull_comparison"
11
+ ALLOW_OVERLAP = "allow-overlap"
12
+
13
+
14
+ def full_sha(value: object) -> bool:
15
+ return isinstance(value, str) and re.fullmatch(r"[a-f0-9]{40}", value) is not None
16
+
17
+
18
+ def pinned_overlap(
19
+ resource: GitHubResource | None,
20
+ pull: PullRequest,
21
+ branch: str,
22
+ main_tip: str,
23
+ ) -> tuple[str, tuple[str, ...]] | None:
24
+ if resource is None or not resource.complete:
25
+ return None
26
+ attributes = resource.attributes
27
+ base = attributes.get("merge_base")
28
+ if (
29
+ attributes.get("head_sha") != pull.head_sha
30
+ or attributes.get("pull_version") != pull.version
31
+ or attributes.get("pull_updated_at") != pull.updated_at
32
+ or attributes.get("branch") != branch
33
+ or attributes.get("main_tip") != main_tip
34
+ or not full_sha(pull.head_sha)
35
+ or not full_sha(main_tip)
36
+ or not isinstance(base, str)
37
+ or not full_sha(base)
38
+ ):
39
+ return None
40
+ raw_pr, raw_main = attributes.get("pull_paths"), attributes.get("main_paths")
41
+ if not isinstance(raw_pr, list) or not isinstance(raw_main, list):
42
+ return None
43
+ pr_files, main_files = cast("list[object]", raw_pr), cast("list[object]", raw_main)
44
+ if any(not isinstance(path, str) or not path for path in (*pr_files, *main_files)):
45
+ return None
46
+ paths = set(cast("list[str]", pr_files)).intersection(cast("list[str]", main_files))
47
+ return base, tuple(sorted(paths))
48
+
49
+
50
+ def bind_overlap_labels(
51
+ result: GitHubResource, previous: GitHubResource | None, pull: PullRequest
52
+ ) -> GitHubResource:
53
+ """Grant only a newly observed label event across two polls of the same head."""
54
+ bindings = dict(previous.attributes.get("overlap_bindings", {})) if previous else {}
55
+ known: set[str] = {record.key for record in previous.records} if previous else set()
56
+ same_head = (
57
+ previous is not None
58
+ and previous.complete
59
+ and previous.attributes.get("head_sha") == pull.head_sha
60
+ and previous.attributes.get("pull_version") == pull.version
61
+ )
62
+ for record in result.records:
63
+ if record.fields.get("name") == ALLOW_OVERLAP and record.fields.get("action") == "labeled":
64
+ binding = (
65
+ [pull.head_sha, pull.version] if same_head and record.key not in known else None
66
+ )
67
+ bindings.setdefault(record.key, binding)
68
+ return replace(result, attributes={**result.attributes, "overlap_bindings": bindings})
69
+
70
+
71
+ def overlap_label_is_bound(labels: GitHubResource | None, pull: PullRequest, event: int) -> bool:
72
+ bindings = labels.attributes.get("overlap_bindings") if labels else None
73
+ return isinstance(bindings, dict) and cast("dict[str, object]", bindings).get(str(event)) == [
74
+ pull.head_sha,
75
+ pull.version,
76
+ ]
@@ -0,0 +1,60 @@
1
+ """Ranked, durable next items and their lifecycle (AD-18)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, replace
6
+ from typing import TYPE_CHECKING, Any, Literal
7
+
8
+ from plotroom.core.events import LedgerError
9
+ from plotroom.core.roles import OwnershipView
10
+
11
+ if TYPE_CHECKING:
12
+ from plotroom.core.unit_of_work import UnitOfWork
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class ItemKind:
17
+ name: str
18
+ rank_class: int
19
+ state_backed: bool
20
+ suggested_actions: tuple[str, ...]
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Item:
25
+ id: str
26
+ kind: str
27
+ subject_ref: str
28
+ dedup_key: str
29
+ role: str
30
+ rank_class: int
31
+ state: Literal["open", "snoozed", "closed"]
32
+ opened_seq: int
33
+ closed_seq: int | None
34
+ seq: int
35
+ context: dict[str, Any]
36
+ suggested_actions: tuple[str, ...]
37
+
38
+
39
+ def visible(item: Item, role: str) -> bool:
40
+ return item.role == role or role == "orchestrator"
41
+
42
+
43
+ async def owns_ack(view: OwnershipView, args: dict[str, Any]) -> bool:
44
+ item = await view.find_item(args["item"])
45
+ return item is not None and visible(item, view.role)
46
+
47
+
48
+ async def ack(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
49
+ item = await uow.find_item(args["item"])
50
+ if item is None:
51
+ raise LedgerError("not_found", "next item not found")
52
+ if item.state != "open":
53
+ return {"item": item.id, "state": item.state, "changed": False}
54
+ if uow.item_kind(item.kind).state_backed:
55
+ updated = replace(item, state="snoozed", seq=await uow.allocate_seq())
56
+ else:
57
+ seq = await uow.allocate_seq()
58
+ updated = replace(item, state="closed", seq=seq, closed_seq=seq)
59
+ await uow.save_item(updated)
60
+ return {"item": item.id, "state": updated.state, "changed": True}
@@ -0,0 +1,103 @@
1
+ """Persist validated operator goals and report their current issue results."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from plotroom.core.events import LedgerError, format_time
9
+ from plotroom.core.github_projection import (
10
+ ISSUE_PAGINATION_VERIFIED,
11
+ ISSUE_RELATION_RETRY,
12
+ ISSUE_TREE,
13
+ GitHubResource,
14
+ )
15
+ from plotroom.core.goal_language import GoalSyntaxError, evaluate_goal, goal_predicates, parse_goal
16
+ from plotroom.core.goal_projection import GoalFacts, StoredGoal
17
+
18
+ if TYPE_CHECKING:
19
+ from plotroom.core.unit_of_work import UnitOfWork
20
+
21
+ FIRST_GOAL = (
22
+ "every issue where state = open and milestone = 1 "
23
+ "satisfies assigned_to human or blocked_by(assigned_to human)"
24
+ )
25
+
26
+
27
+ def validate_goal_name(name: str) -> None:
28
+ try:
29
+ length = len(name.encode("utf-8"))
30
+ except UnicodeEncodeError:
31
+ length = 0
32
+ if not name.strip() or not 0 < length <= 128 or "\x00" in name:
33
+ raise LedgerError("invalid", "goal name must be nonblank UTF-8 text up to 128 bytes")
34
+
35
+
36
+ async def set_goal(
37
+ uow: UnitOfWork, args: dict[str, Any], *, repository: str | None
38
+ ) -> dict[str, Any]:
39
+ name: str = args["name"]
40
+ text: str = args["text"]
41
+ validate_goal_name(name)
42
+ try:
43
+ goal = parse_goal(text)
44
+ except GoalSyntaxError as exc:
45
+ raise LedgerError("invalid", str(exc)) from None
46
+ try:
47
+ text.encode("utf-8")
48
+ except UnicodeEncodeError:
49
+ raise LedgerError("invalid", "goal text must be valid UTF-8") from None
50
+ predicates = goal_predicates(goal)
51
+ needs_blockers = "blocked_by" in predicates
52
+ if repository is not None and needs_blockers and not await uow.goals_use_blockers():
53
+ previous = await uow.github_resource(repository, ISSUE_TREE)
54
+ tree = previous if previous is not None else GitHubResource(())
55
+ retry = sorted(
56
+ {row.fields["number"] for row in tree.records if row.kind == "issue_metadata"}
57
+ )
58
+ await uow.save_github_resource(
59
+ repository,
60
+ ISSUE_TREE,
61
+ "",
62
+ replace(
63
+ tree,
64
+ complete=False,
65
+ generation=tree.generation + 1 if previous is not None else 0,
66
+ attributes={
67
+ **tree.attributes,
68
+ ISSUE_RELATION_RETRY: retry,
69
+ ISSUE_PAGINATION_VERIFIED: False,
70
+ },
71
+ ),
72
+ )
73
+ await uow.save_goal(
74
+ StoredGoal(
75
+ name,
76
+ text,
77
+ format_time(uow.now()),
78
+ needs_blockers,
79
+ uses_lanes="lane" in predicates,
80
+ uses_decisions="decision" in predicates,
81
+ )
82
+ )
83
+ return {"name": name}
84
+
85
+
86
+ def report_goals(goals: list[StoredGoal], facts: GoalFacts) -> dict[str, Any]:
87
+ reports: list[dict[str, Any]] = []
88
+ for goal in goals:
89
+ remaining = [failure.render() for failure in evaluate_goal(parse_goal(goal.text), facts)]
90
+ reports.append(
91
+ {
92
+ "name": goal.name,
93
+ "text": goal.text,
94
+ "updated_at": goal.updated_at,
95
+ "done": not remaining,
96
+ "remaining": remaining,
97
+ }
98
+ )
99
+ return {
100
+ "done": all(report["done"] for report in reports),
101
+ "goals": reports,
102
+ "as_of": facts.as_of,
103
+ }
@@ -0,0 +1,70 @@
1
+ """Claude-shaped outbox records and writer-owned delivery leases."""
2
+
3
+ from dataclasses import asdict, dataclass
4
+ from datetime import timedelta
5
+ from typing import TYPE_CHECKING, Any
6
+ from uuid import UUID, uuid4
7
+
8
+ from plotroom.core.events import LedgerError, format_time
9
+
10
+ if TYPE_CHECKING:
11
+ from plotroom.core.unit_of_work import UnitOfWork
12
+
13
+ LEASE_DURATION = timedelta(seconds=60)
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class OutboxMessage:
18
+ action_key: str
19
+ worker: str
20
+ session_id: str
21
+ text: str
22
+ seq: int
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class OutboxLease:
27
+ message: OutboxMessage
28
+ act_id: str
29
+ expires_at: str
30
+
31
+ def render(self) -> dict[str, Any]:
32
+ return {**asdict(self.message), "act_id": self.act_id, "expires_at": self.expires_at}
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class OutboxReadiness:
37
+ head: int
38
+ ready_seq: int | None
39
+ next_expiry: str | None = None
40
+
41
+
42
+ def lease_request_id(consumer_id: str, request_id: str) -> str:
43
+ """Scope retries to one drain process even if it shares a project drain token."""
44
+ try:
45
+ consumer = UUID(consumer_id)
46
+ except ValueError:
47
+ raise LedgerError("invalid", "consumer_id must be a UUIDv4") from None
48
+ if consumer.version != 4:
49
+ raise LedgerError("invalid", "consumer_id must be a UUIDv4")
50
+ if not request_id:
51
+ raise LedgerError("invalid", "outbox_lease requires a nonempty request_id")
52
+ return f"{consumer}:{request_id}"
53
+
54
+
55
+ async def lease_outbox(uow: UnitOfWork, _args: dict[str, Any]) -> dict[str, Any]:
56
+ now = uow.now()
57
+ lease = await uow.lease_outbox(
58
+ f"lease_{uuid4()}", format_time(now), format_time(now + LEASE_DURATION)
59
+ )
60
+ return {"lease": None if lease is None else lease.render()}
61
+
62
+
63
+ async def complete_outbox(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
64
+ act_id = args["act_id"]
65
+ if not act_id:
66
+ raise LedgerError("invalid", "act_id must be nonempty")
67
+ key = await uow.complete_outbox(act_id, format_time(uow.now()))
68
+ if key is None:
69
+ raise LedgerError("conflict", "act_id does not identify a current outbox lease")
70
+ return {"action_key": key, "state": "done"}
@@ -0,0 +1,152 @@
1
+ """Reconcile conflicts against the confirmed file lists of open pull requests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import defaultdict
7
+ from dataclasses import dataclass
8
+ from graphlib import CycleError, TopologicalSorter
9
+ from pathlib import PurePosixPath
10
+ from typing import TYPE_CHECKING
11
+
12
+ from plotroom.core.claims import (
13
+ PR_CLAIM_OVERLAP,
14
+ TICKET_TREE_MOVE,
15
+ Claim,
16
+ compile_glob,
17
+ sync_items,
18
+ )
19
+ from plotroom.core.github_projection import FILES
20
+
21
+ if TYPE_CHECKING:
22
+ from plotroom.core.unit_of_work import UnitOfWork
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class _PullFiles:
27
+ number: int
28
+ lane: str | None
29
+ paths: set[str]
30
+ moves: set[str]
31
+ edits: set[str]
32
+
33
+
34
+ async def _confirmed_files(
35
+ uow: UnitOfWork, repository: str, tree: PurePosixPath | None
36
+ ) -> list[_PullFiles]:
37
+ confirmed: list[_PullFiles] = []
38
+ for pull in await uow.open_pulls(repository):
39
+ resource = await uow.github_resource(repository, FILES, str(pull.number))
40
+ # An unsuccessful refresh may leave a confirmed file list cached.
41
+ if resource is None or resource.attributes.get("head_sha") != pull.head_sha:
42
+ continue
43
+ lane = await uow.branch_lane(pull.branch) if pull.head_repository == repository else None
44
+ paths: set[str] = set()
45
+ moves: set[str] = set()
46
+ edits: set[str] = set()
47
+ for row in resource.records:
48
+ if row.fields["head_sha"] != pull.head_sha:
49
+ continue
50
+ path: str = row.fields["path"]
51
+ paths.add(path)
52
+ prior: str | None = row.fields.get("previous_path")
53
+ if row.fields["status"] != "renamed" or prior is None:
54
+ edits.add(path)
55
+ continue
56
+ paths.add(prior)
57
+ if tree is not None and (
58
+ PurePosixPath(prior).is_relative_to(tree)
59
+ or PurePosixPath(path).is_relative_to(tree)
60
+ ):
61
+ moves.update((prior, path))
62
+ confirmed.append(
63
+ _PullFiles(pull.number, None if lane is None else lane.id, paths, moves, edits)
64
+ )
65
+ return confirmed
66
+
67
+
68
+ async def _reconcile_pr_claims(
69
+ uow: UnitOfWork, pulls: list[_PullFiles], claims: list[Claim]
70
+ ) -> None:
71
+ matchers = [(claim, compile_glob(claim.glob)) for claim in claims]
72
+ desired: dict[str, dict[str, object]] = {}
73
+ for pull in pulls:
74
+ matches: dict[str, list[dict[str, object]]] = defaultdict(list)
75
+ for claim, matcher in matchers:
76
+ if pull.lane == claim.lane:
77
+ continue
78
+ paths = sorted(path for path in pull.paths if matcher.matches(path))
79
+ if paths:
80
+ matches[claim.lane].append({"claim": claim.render(), "paths": paths})
81
+ for lane, evidence in matches.items():
82
+ desired[json.dumps([pull.number, lane])] = {
83
+ "lanes": [lane] if pull.lane is None else sorted((lane, pull.lane)),
84
+ "prs": [pull.number],
85
+ "claiming_lane": lane,
86
+ "matches": evidence,
87
+ }
88
+ await sync_items(uow, PR_CLAIM_OVERLAP, desired)
89
+
90
+
91
+ def _merge_order(mover: int, dependencies: dict[int, set[int]]) -> list[int]:
92
+ pending = [mover]
93
+ visited: set[int] = set()
94
+ while pending:
95
+ pr = pending.pop()
96
+ if pr not in visited:
97
+ visited.add(pr)
98
+ pending.extend(dependencies.get(pr, ()))
99
+ graph = {pr: sorted(dependencies.get(pr, ())) for pr in sorted(visited)}
100
+ try:
101
+ return list(TopologicalSorter(graph).static_order())
102
+ except CycleError:
103
+ return []
104
+
105
+
106
+ async def _reconcile_moves(uow: UnitOfWork, pulls: list[_PullFiles]) -> None:
107
+ by_number = {pull.number: pull for pull in pulls}
108
+ by_path: dict[str, set[int]] = defaultdict(set)
109
+ for pull in pulls:
110
+ for path in pull.edits:
111
+ by_path[path].add(pull.number)
112
+ conflicts: dict[int, dict[str, list[int]]] = {}
113
+ for pull in pulls:
114
+ edits = {
115
+ path: sorted(by_path[path] - {pull.number})
116
+ for path in sorted(pull.moves)
117
+ if by_path[path] - {pull.number}
118
+ }
119
+ if edits:
120
+ conflicts[pull.number] = edits
121
+ dependencies = {
122
+ mover: {number for numbers in edits.values() for number in numbers}
123
+ for mover, edits in conflicts.items()
124
+ }
125
+ desired: dict[str, dict[str, object]] = {}
126
+ for mover, edits in conflicts.items():
127
+ editors = sorted(dependencies[mover])
128
+ prs = [*editors, mover]
129
+ order = _merge_order(mover, dependencies)
130
+ context: dict[str, object] = {
131
+ "lanes": sorted(
132
+ {lane for number in prs if (lane := by_number[number].lane) is not None}
133
+ ),
134
+ "prs": sorted(prs),
135
+ "moving_pr": mover,
136
+ "editing_prs": editors,
137
+ "edits": edits,
138
+ "suggested_order": order,
139
+ }
140
+ if not order:
141
+ context["coordination_required"] = True
142
+ desired[str(mover)] = context
143
+ await sync_items(uow, TICKET_TREE_MOVE, desired)
144
+
145
+
146
+ async def reconcile_pull_overlaps(
147
+ uow: UnitOfWork, repository: str, tree_path: str | None, claims: list[Claim]
148
+ ) -> None:
149
+ tree = PurePosixPath(tree_path) if tree_path is not None else None
150
+ pulls = await _confirmed_files(uow, repository, tree) if claims or tree is not None else []
151
+ await _reconcile_pr_claims(uow, pulls, claims)
152
+ await _reconcile_moves(uow, pulls)
@@ -0,0 +1,62 @@
1
+ """Typed deployment facts from GitHub and deploy-lane workers."""
2
+
3
+ import json
4
+ import re
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from plotroom.core.events import FieldSpec, LedgerError, NewEvent
8
+
9
+ if TYPE_CHECKING:
10
+ from plotroom.core.unit_of_work import UnitOfWork
11
+
12
+ DEPLOY_STATUS = "deploy.status"
13
+ DEPLOY_FINISHED_STATES = frozenset({"success", "failure", "error", "inactive"})
14
+ DEPLOY_STATES = DEPLOY_FINISHED_STATES | {"pending", "queued", "in_progress"}
15
+ DEPLOY_ARGS = (FieldSpec("environment", "str"), FieldSpec("sha", "str"), FieldSpec("state", "str"))
16
+ DEPLOY_FIELDS = (
17
+ *DEPLOY_ARGS,
18
+ FieldSpec("finished", "bool"),
19
+ FieldSpec("repository", "str", required=False),
20
+ FieldSpec("deployment_id", "int", required=False),
21
+ FieldSpec("status_id", "int", required=False),
22
+ )
23
+ _SHA = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})")
24
+
25
+
26
+ def validate_deploy_environment(value: str) -> str:
27
+ if not value or value != value.strip() or len(value) > 255 or not value.isprintable():
28
+ raise ValueError("environment must be an exact, non-empty name of at most 255 characters")
29
+ return value
30
+
31
+
32
+ def validate_report_sha(value: str) -> str:
33
+ if not _SHA.fullmatch(value):
34
+ raise ValueError("sha must be a full lowercase hexadecimal commit SHA")
35
+ return value
36
+
37
+
38
+ def deploy_fields(environment: str, sha: str, state: str) -> dict[str, Any]:
39
+ if state not in DEPLOY_STATES:
40
+ raise ValueError("unsupported deployment state")
41
+ return {
42
+ "environment": validate_deploy_environment(environment),
43
+ "sha": validate_report_sha(sha),
44
+ "state": state,
45
+ "finished": state in DEPLOY_FINISHED_STATES,
46
+ }
47
+
48
+
49
+ async def deploy_report(uow: UnitOfWork, args: dict[str, Any]) -> dict[str, Any]:
50
+ lane_id: str = args["lane"]
51
+ lane = await uow.find_lane(lane_id)
52
+ if lane is None or lane.state == "archived":
53
+ raise LedgerError("conflict", "lane is archived or missing")
54
+ try:
55
+ fields = deploy_fields(args["environment"], args["sha"], args["state"])
56
+ except ValueError as exc:
57
+ raise LedgerError("invalid", str(exc)) from None
58
+ identity = json.dumps([lane_id, fields["environment"], fields["sha"], fields["state"]])
59
+ event = await uow.append(
60
+ NewEvent("deploy", DEPLOY_STATUS, f"worker:{identity}", fields, lane_id=lane_id)
61
+ )
62
+ return {"event": event.event.id, "created": event.created}