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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Fixture branch updates staged and reconciled in the project writer."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, replace
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
|
|
6
|
+
from plotroom.core.actions import BRANCH_UPDATE, Action, finish_action, record_attempt
|
|
7
|
+
from plotroom.core.events import Event, FieldSpec, NewEvent
|
|
8
|
+
from plotroom.core.lanes import Lane
|
|
9
|
+
from plotroom.core.merge_gate import (
|
|
10
|
+
STALE_CI,
|
|
11
|
+
GatePolicy,
|
|
12
|
+
GateSnapshot,
|
|
13
|
+
current_label_evidence,
|
|
14
|
+
determine_main_verdict,
|
|
15
|
+
evaluate_gate,
|
|
16
|
+
)
|
|
17
|
+
from plotroom.core.merge_lane import lane_matches_branch
|
|
18
|
+
from plotroom.core.merge_overlap import ALLOW_OVERLAP
|
|
19
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
20
|
+
from plotroom.ports.github_write import BranchUpdateReceipt
|
|
21
|
+
|
|
22
|
+
BRANCH_UPDATE_STAGED = "core.branch_update_staged"
|
|
23
|
+
BRANCH_UPDATE_AUTHORIZED = "core.branch_update_authorized"
|
|
24
|
+
BRANCH_UPDATE_ATTEMPT_PIN = "core.branch_update_attempt_pin"
|
|
25
|
+
BRANCH_UPDATE_DECLINED = "core.branch_update_declined"
|
|
26
|
+
BRANCH_UPDATED = "core.branch_updated"
|
|
27
|
+
BRANCH_UPDATE_CONFLICT = "branch_update_conflict"
|
|
28
|
+
BRANCH_UPDATE_FIELDS = (
|
|
29
|
+
FieldSpec("repository", "str"),
|
|
30
|
+
FieldSpec("number", "int"),
|
|
31
|
+
FieldSpec("head_sha", "str"),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
BRANCH_UPDATED_FIELDS = (*BRANCH_UPDATE_FIELDS, FieldSpec("main_sha", "str"))
|
|
35
|
+
BRANCH_UPDATE_AUTHORIZED_FIELDS = (
|
|
36
|
+
*BRANCH_UPDATED_FIELDS,
|
|
37
|
+
FieldSpec("action_key", "str"),
|
|
38
|
+
FieldSpec("calls_before", "int"),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class BranchUpdate:
|
|
44
|
+
repository: str
|
|
45
|
+
number: int
|
|
46
|
+
branch: str
|
|
47
|
+
head_sha: str
|
|
48
|
+
main_sha: str
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def key(self) -> str:
|
|
52
|
+
return f"{BRANCH_UPDATE}:{self.number}:{self.head_sha}"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def eligible_branch_update(
|
|
56
|
+
snapshot: GateSnapshot, policy: GatePolicy, now: datetime
|
|
57
|
+
) -> BranchUpdate | None:
|
|
58
|
+
pull = snapshot.pull
|
|
59
|
+
labels = current_label_evidence(snapshot, policy, now)
|
|
60
|
+
if (
|
|
61
|
+
pull is None
|
|
62
|
+
or pull.draft is not False
|
|
63
|
+
or pull.head_repository != pull.repository
|
|
64
|
+
or snapshot.earlier_pull is not None
|
|
65
|
+
or snapshot.ambiguous_lane
|
|
66
|
+
or labels is None
|
|
67
|
+
or (
|
|
68
|
+
ALLOW_OVERLAP in labels.attributes["labels"]
|
|
69
|
+
and ALLOW_OVERLAP not in labels.attributes["label_provenance"]
|
|
70
|
+
)
|
|
71
|
+
):
|
|
72
|
+
return None
|
|
73
|
+
# The project capacity hold applies to merges. Rule 4 still uses this PR's gate evidence.
|
|
74
|
+
verdict = evaluate_gate(replace(snapshot, detail_capacity_exceeded=False), policy, now)
|
|
75
|
+
if not verdict.reasons or verdict.reasons[0].code != STALE_CI:
|
|
76
|
+
return None
|
|
77
|
+
main = determine_main_verdict(snapshot, policy, now)
|
|
78
|
+
if main.kind != "green" or main.head_sha is None:
|
|
79
|
+
return None
|
|
80
|
+
return BranchUpdate(pull.repository, pull.number, pull.branch, pull.head_sha, main.head_sha)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def stage_branch_update(uow: UnitOfWork, update: BranchUpdate) -> bool:
|
|
84
|
+
payload = {
|
|
85
|
+
"repository": update.repository,
|
|
86
|
+
"number": update.number,
|
|
87
|
+
"head_sha": update.head_sha,
|
|
88
|
+
}
|
|
89
|
+
cause = await uow.append(NewEvent("core", BRANCH_UPDATE_STAGED, update.key, payload))
|
|
90
|
+
if not cause.created:
|
|
91
|
+
return False
|
|
92
|
+
await uow.enqueue_action(
|
|
93
|
+
cause.event,
|
|
94
|
+
BRANCH_UPDATE,
|
|
95
|
+
{**payload, "branch": update.branch, "bound_receipt": True},
|
|
96
|
+
stable_key=update.key,
|
|
97
|
+
)
|
|
98
|
+
return True
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
async def authorize_branch_update(
|
|
102
|
+
uow: UnitOfWork, action: Action, update: BranchUpdate, *, calls_before: int
|
|
103
|
+
) -> tuple[Action, Event] | None:
|
|
104
|
+
key = f"{action.key}:{update.main_sha}"
|
|
105
|
+
fields = {
|
|
106
|
+
"action_key": action.key,
|
|
107
|
+
"repository": update.repository,
|
|
108
|
+
"number": update.number,
|
|
109
|
+
"head_sha": update.head_sha,
|
|
110
|
+
"main_sha": update.main_sha,
|
|
111
|
+
"calls_before": calls_before,
|
|
112
|
+
}
|
|
113
|
+
result = await uow.append(NewEvent("core", BRANCH_UPDATE_AUTHORIZED, key, fields))
|
|
114
|
+
if not result.created:
|
|
115
|
+
return None
|
|
116
|
+
attempted = await record_attempt(uow, action)
|
|
117
|
+
await uow.append(
|
|
118
|
+
NewEvent(
|
|
119
|
+
"core",
|
|
120
|
+
BRANCH_UPDATE_ATTEMPT_PIN,
|
|
121
|
+
f"{action.key}:{attempted.attempts}",
|
|
122
|
+
{"authorization": key},
|
|
123
|
+
)
|
|
124
|
+
)
|
|
125
|
+
return attempted, result.event
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
async def previous_branch_update(uow: UnitOfWork, action: Action) -> Event | None:
|
|
129
|
+
if not action.attempts:
|
|
130
|
+
return None
|
|
131
|
+
pointer = await uow.find_event(
|
|
132
|
+
"core", BRANCH_UPDATE_ATTEMPT_PIN, f"{action.key}:{action.attempts}"
|
|
133
|
+
)
|
|
134
|
+
if pointer is None:
|
|
135
|
+
return None
|
|
136
|
+
return await uow.find_event("core", BRANCH_UPDATE_AUTHORIZED, pointer.fields["authorization"])
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def receipt_matches(receipt: object, authorization: Event) -> bool:
|
|
140
|
+
fields = authorization.fields
|
|
141
|
+
return (
|
|
142
|
+
isinstance(receipt, BranchUpdateReceipt)
|
|
143
|
+
and receipt.operation == BRANCH_UPDATE
|
|
144
|
+
and receipt.outcome in ("updated", "conflict")
|
|
145
|
+
and receipt.action_key == fields["action_key"]
|
|
146
|
+
and receipt.repository == fields["repository"]
|
|
147
|
+
and type(receipt.number) is int
|
|
148
|
+
and receipt.number == fields["number"]
|
|
149
|
+
and receipt.head_sha == fields["head_sha"]
|
|
150
|
+
and receipt.main_sha == fields["main_sha"]
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
async def _conflict_lane(uow: UnitOfWork, action: Action, branch: str | None) -> Lane | None:
|
|
155
|
+
if branch is None:
|
|
156
|
+
return None
|
|
157
|
+
exact = await uow.branch_lanes(branch)
|
|
158
|
+
if exact:
|
|
159
|
+
return exact[0] if len(exact) == 1 else None
|
|
160
|
+
|
|
161
|
+
repository = action.payload["repository"]
|
|
162
|
+
pull = await uow.pull_request(repository, action.payload["number"])
|
|
163
|
+
if (
|
|
164
|
+
pull is None
|
|
165
|
+
or not pull.complete
|
|
166
|
+
or pull.head_repository != repository
|
|
167
|
+
or pull.head_sha != action.payload["head_sha"]
|
|
168
|
+
or pull.branch != branch
|
|
169
|
+
):
|
|
170
|
+
return None # A recovered receipt may belong to a different PR head.
|
|
171
|
+
matches = [lane for lane in await uow.active_lanes() if lane_matches_branch(lane, branch)]
|
|
172
|
+
return matches[0] if len(matches) == 1 else None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
async def complete_branch_update(
|
|
176
|
+
uow: UnitOfWork,
|
|
177
|
+
action: Action,
|
|
178
|
+
receipt: BranchUpdateReceipt,
|
|
179
|
+
branch: str | None,
|
|
180
|
+
) -> None:
|
|
181
|
+
if receipt.outcome == "conflict":
|
|
182
|
+
lane = await _conflict_lane(uow, action, branch)
|
|
183
|
+
role = f"worker:{lane.worker}" if lane is not None else "orchestrator"
|
|
184
|
+
await uow.raise_item(
|
|
185
|
+
BRANCH_UPDATE_CONFLICT,
|
|
186
|
+
action.key,
|
|
187
|
+
role,
|
|
188
|
+
{
|
|
189
|
+
**{
|
|
190
|
+
name: value for name, value in action.payload.items() if name != "bound_receipt"
|
|
191
|
+
},
|
|
192
|
+
"main_sha": receipt.main_sha,
|
|
193
|
+
"lane": lane.id if lane is not None else None,
|
|
194
|
+
},
|
|
195
|
+
)
|
|
196
|
+
else:
|
|
197
|
+
fields = {key: action.payload[key] for key in ("repository", "number", "head_sha")}
|
|
198
|
+
await uow.append(
|
|
199
|
+
NewEvent(
|
|
200
|
+
"core",
|
|
201
|
+
BRANCH_UPDATED,
|
|
202
|
+
action.key,
|
|
203
|
+
{**fields, "main_sha": receipt.main_sha},
|
|
204
|
+
f"BRANCH UPDATED #{fields['number']}",
|
|
205
|
+
)
|
|
206
|
+
)
|
|
207
|
+
await finish_action(uow, action, "done")
|
plotroom/core/bridge.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Switchboard ingress and writer-owned leases for a remote bridge."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import replace
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
from uuid import uuid4
|
|
7
|
+
|
|
8
|
+
from plotroom.core.actions import SWITCHBOARD_SEND, finish_action, record_attempt
|
|
9
|
+
from plotroom.core.budgets import BUDGET_ITEM
|
|
10
|
+
from plotroom.core.events import LedgerError, NewEvent, format_time
|
|
11
|
+
from plotroom.core.intake import append_inbound
|
|
12
|
+
from plotroom.core.lanes import infer_lane
|
|
13
|
+
from plotroom.core.outbox import LEASE_DURATION
|
|
14
|
+
from plotroom.core.trigger_actions import DeliveryRoute
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def record_inbound(
|
|
21
|
+
uow: UnitOfWork, board: str, senders: Mapping[str, str], message_id: int, sender: str, body: str
|
|
22
|
+
) -> dict[str, Any]:
|
|
23
|
+
if message_id < 1 or not sender:
|
|
24
|
+
raise LedgerError("invalid", "invalid Switchboard message identity")
|
|
25
|
+
try:
|
|
26
|
+
sender.encode("utf-8")
|
|
27
|
+
body.encode("utf-8")
|
|
28
|
+
except UnicodeEncodeError:
|
|
29
|
+
raise LedgerError("invalid", "Switchboard text must be valid UTF-8") from None
|
|
30
|
+
worker = senders.get(sender)
|
|
31
|
+
lane = await infer_lane(uow, worker=worker)
|
|
32
|
+
fields = {"sender": sender}
|
|
33
|
+
if worker is not None:
|
|
34
|
+
fields["worker"] = worker
|
|
35
|
+
result = await append_inbound(
|
|
36
|
+
uow,
|
|
37
|
+
NewEvent("switchboard", "switchboard.message", f"{board}:{message_id}", fields, body, lane),
|
|
38
|
+
)
|
|
39
|
+
return {"event": result.event.id}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def receive_bridge(
|
|
43
|
+
uow: UnitOfWork, args: dict[str, Any], *, board: str, senders: Mapping[str, str]
|
|
44
|
+
) -> dict[str, Any]:
|
|
45
|
+
if args["board"] != board:
|
|
46
|
+
raise LedgerError("forbidden", "the bridge is scoped to another board")
|
|
47
|
+
return await record_inbound(
|
|
48
|
+
uow, board, senders, args["message_id"], args["sender"], args["body"]
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
async def lease_bridge(
|
|
53
|
+
uow: UnitOfWork,
|
|
54
|
+
args: dict[str, Any],
|
|
55
|
+
*,
|
|
56
|
+
routes: Mapping[str, DeliveryRoute],
|
|
57
|
+
board: str,
|
|
58
|
+
action_attempts: int,
|
|
59
|
+
) -> dict[str, Any]:
|
|
60
|
+
if args["board"] != board:
|
|
61
|
+
raise LedgerError("forbidden", "the bridge is scoped to another board")
|
|
62
|
+
workers = tuple(routes)
|
|
63
|
+
now = uow.now()
|
|
64
|
+
while (action := await uow.bridge_action(workers, format_time(now))) is not None:
|
|
65
|
+
if action.attempts >= action_attempts:
|
|
66
|
+
await finish_action(uow, action, "failed")
|
|
67
|
+
continue
|
|
68
|
+
if action.kind == SWITCHBOARD_SEND:
|
|
69
|
+
address, body = action.payload["to"], action.payload["body"]
|
|
70
|
+
else:
|
|
71
|
+
worker = action.payload["worker"]
|
|
72
|
+
if action.key.startswith(f"{BUDGET_ITEM.name}:"):
|
|
73
|
+
await finish_action(
|
|
74
|
+
uow,
|
|
75
|
+
action,
|
|
76
|
+
"failed",
|
|
77
|
+
failure_reason="the remote bridge cannot fence this send to its original lane",
|
|
78
|
+
)
|
|
79
|
+
continue
|
|
80
|
+
address, body = routes[worker].destination, action.payload["text"]
|
|
81
|
+
act_id = f"bridge_{uuid4()}"
|
|
82
|
+
expires = format_time(uow.now() + LEASE_DURATION)
|
|
83
|
+
# Lease metadata travels with the existing action row, under the project's writer lock.
|
|
84
|
+
await record_attempt(
|
|
85
|
+
uow,
|
|
86
|
+
replace(
|
|
87
|
+
action,
|
|
88
|
+
payload={**action.payload, "_bridge_lease": {"id": act_id, "expires": expires}},
|
|
89
|
+
),
|
|
90
|
+
)
|
|
91
|
+
return {
|
|
92
|
+
"lease": {
|
|
93
|
+
"act_id": act_id,
|
|
94
|
+
"action_key": action.key,
|
|
95
|
+
"to": address,
|
|
96
|
+
"body": body,
|
|
97
|
+
"expires_at": expires,
|
|
98
|
+
"lease_seconds": LEASE_DURATION.total_seconds(),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return {"lease": None}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
async def complete_bridge(
|
|
105
|
+
uow: UnitOfWork, args: dict[str, Any], *, workers: tuple[str, ...]
|
|
106
|
+
) -> dict[str, Any]:
|
|
107
|
+
action = await uow.bridge_action(workers, format_time(uow.now()), args["act_id"])
|
|
108
|
+
if action is None:
|
|
109
|
+
raise LedgerError("conflict", "act_id does not identify a current bridge lease")
|
|
110
|
+
payload = {key: value for key, value in action.payload.items() if key != "_bridge_lease"}
|
|
111
|
+
await finish_action(uow, replace(action, payload=payload), "done")
|
|
112
|
+
return {"action_key": action.key, "state": "done"}
|
plotroom/core/briefs.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Render a lane brief from the project's current read-only facts."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from string import Formatter
|
|
5
|
+
|
|
6
|
+
from plotroom.core.claims import Claim
|
|
7
|
+
|
|
8
|
+
BRIEF = "brief"
|
|
9
|
+
DEFAULT_TEMPLATE = """# Lane brief for {worker}
|
|
10
|
+
|
|
11
|
+
## Work item {work_item}
|
|
12
|
+
|
|
13
|
+
{source_text}
|
|
14
|
+
|
|
15
|
+
## Paths
|
|
16
|
+
|
|
17
|
+
{paths}
|
|
18
|
+
|
|
19
|
+
## Don't touch
|
|
20
|
+
|
|
21
|
+
{dont_touch}
|
|
22
|
+
|
|
23
|
+
## Plan
|
|
24
|
+
|
|
25
|
+
{plan}
|
|
26
|
+
|
|
27
|
+
## RESULT
|
|
28
|
+
|
|
29
|
+
{result}
|
|
30
|
+
|
|
31
|
+
## Standing rules
|
|
32
|
+
|
|
33
|
+
{standing_rules}
|
|
34
|
+
"""
|
|
35
|
+
_REQUIRED_FIELDS = frozenset(
|
|
36
|
+
{"source_text", "paths", "dont_touch", "plan", "result", "standing_rules"}
|
|
37
|
+
)
|
|
38
|
+
_FIELDS = _REQUIRED_FIELDS | {"work_item", "worker"}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class BriefSettings:
|
|
43
|
+
template: str = DEFAULT_TEMPLATE
|
|
44
|
+
plan: str = "Scope, implementation steps, and verification."
|
|
45
|
+
result: str = "Status, changes, verification evidence, and any remaining blockers."
|
|
46
|
+
standing_rules: tuple[str, ...] = ()
|
|
47
|
+
|
|
48
|
+
def __post_init__(self) -> None:
|
|
49
|
+
fields: set[str] = set()
|
|
50
|
+
for _, field, spec, conversion in Formatter().parse(self.template):
|
|
51
|
+
if field is None:
|
|
52
|
+
continue
|
|
53
|
+
if field not in _FIELDS or spec or conversion is not None:
|
|
54
|
+
raise ValueError(f"invalid brief template field {field!r}")
|
|
55
|
+
fields.add(field)
|
|
56
|
+
if missing := _REQUIRED_FIELDS - fields:
|
|
57
|
+
raise ValueError(f"missing brief template fields: {', '.join(sorted(missing))}")
|
|
58
|
+
|
|
59
|
+
def render(
|
|
60
|
+
self,
|
|
61
|
+
work_item: str,
|
|
62
|
+
worker: str,
|
|
63
|
+
source_text: str,
|
|
64
|
+
lane: str | None,
|
|
65
|
+
claims: list[Claim],
|
|
66
|
+
) -> str:
|
|
67
|
+
own: list[str] = []
|
|
68
|
+
others: list[str] = []
|
|
69
|
+
for claim in claims:
|
|
70
|
+
if claim.lane == lane:
|
|
71
|
+
own.append(f"- {claim.glob} ({claim.reason})")
|
|
72
|
+
else:
|
|
73
|
+
others.append(f"- {claim.glob} ({claim.lane}: {claim.reason})")
|
|
74
|
+
return self.template.format(
|
|
75
|
+
work_item=work_item,
|
|
76
|
+
worker=worker,
|
|
77
|
+
source_text=source_text,
|
|
78
|
+
paths="\n".join(own),
|
|
79
|
+
dont_touch="\n".join(others),
|
|
80
|
+
plan=self.plan,
|
|
81
|
+
result=self.result,
|
|
82
|
+
standing_rules="\n".join(f"- {rule}" for rule in self.standing_rules),
|
|
83
|
+
)
|
plotroom/core/budgets.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Budget registration and once-only effects for cumulative usage observations."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
import uuid
|
|
6
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
7
|
+
from dataclasses import asdict, dataclass, replace
|
|
8
|
+
from datetime import datetime
|
|
9
|
+
from fractions import Fraction
|
|
10
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
11
|
+
|
|
12
|
+
from plotroom.core.events import FieldSpec, LedgerError, NewEvent
|
|
13
|
+
from plotroom.core.next_items import ItemKind
|
|
14
|
+
from plotroom.core.run_reports import validate_identity
|
|
15
|
+
from plotroom.core.trigger_actions import SEND
|
|
16
|
+
from plotroom.ports.usage_meter import UsageObservation
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
20
|
+
|
|
21
|
+
type KeyScope = Literal["staging", "production"]
|
|
22
|
+
OPENROUTER_PROVIDER = "openrouter"
|
|
23
|
+
_PROVIDER = re.compile(r"[a-z][a-z0-9_-]{0,63}")
|
|
24
|
+
BUDGET_ARGS = (
|
|
25
|
+
FieldSpec("run", "str"),
|
|
26
|
+
FieldSpec("lane", "str"),
|
|
27
|
+
FieldSpec("cap_usd", "number"),
|
|
28
|
+
FieldSpec("provider", "str"),
|
|
29
|
+
FieldSpec("key_scope", "str"),
|
|
30
|
+
)
|
|
31
|
+
BUDGET_THRESHOLD = "core.budget_threshold"
|
|
32
|
+
BUDGET_THRESHOLD_FIELDS = (
|
|
33
|
+
FieldSpec("budget_id", "str"),
|
|
34
|
+
FieldSpec("run", "str"),
|
|
35
|
+
FieldSpec("lane", "str"),
|
|
36
|
+
FieldSpec("percent", "int"),
|
|
37
|
+
FieldSpec("cap_usd", "number"),
|
|
38
|
+
FieldSpec("spent_usd", "number"),
|
|
39
|
+
FieldSpec("as_of", "str"),
|
|
40
|
+
)
|
|
41
|
+
BUDGET_ITEM = ItemKind("budget", 10, False, ("Review the run's spend",))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Budget:
|
|
46
|
+
id: str
|
|
47
|
+
run: str
|
|
48
|
+
lane: str
|
|
49
|
+
cap_usd: float
|
|
50
|
+
provider: str
|
|
51
|
+
key_scope: KeyScope
|
|
52
|
+
spent_usd: float = 0.0
|
|
53
|
+
as_of: str | None = None
|
|
54
|
+
|
|
55
|
+
def render(self) -> dict[str, Any]:
|
|
56
|
+
return asdict(self)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _budget_cap(value: Any) -> float:
|
|
60
|
+
try:
|
|
61
|
+
cap = float(value)
|
|
62
|
+
except OverflowError:
|
|
63
|
+
cap = math.inf
|
|
64
|
+
if not math.isfinite(cap) or cap <= 0:
|
|
65
|
+
raise LedgerError("invalid", "cap_usd must be positive and finite")
|
|
66
|
+
return cap
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _key_scope(value: str) -> KeyScope:
|
|
70
|
+
if value != "staging" and value != "production":
|
|
71
|
+
raise LedgerError("invalid", "key_scope must be staging or production")
|
|
72
|
+
return value
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
async def validate_openrouter_budget(
|
|
76
|
+
args: dict[str, Any], *, check: Callable[[str, float], Awaitable[bool]]
|
|
77
|
+
) -> None:
|
|
78
|
+
if args["provider"] == OPENROUTER_PROVIDER:
|
|
79
|
+
run: str = args["run"]
|
|
80
|
+
validate_identity(run, "run")
|
|
81
|
+
validate_identity(args["lane"], "lane")
|
|
82
|
+
_key_scope(args["key_scope"])
|
|
83
|
+
if not await check(run, _budget_cap(args["cap_usd"])):
|
|
84
|
+
raise LedgerError("invalid", "could not verify a capped OpenRouter key for this run")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def budget_open(
|
|
88
|
+
uow: UnitOfWork, args: dict[str, Any], *, openrouter_bindings: Mapping[str, str] | None = None
|
|
89
|
+
) -> dict[str, Any]:
|
|
90
|
+
run: str = args["run"]
|
|
91
|
+
lane: str = args["lane"]
|
|
92
|
+
provider: str = args["provider"]
|
|
93
|
+
key_scope = _key_scope(args["key_scope"])
|
|
94
|
+
validate_identity(run, "run")
|
|
95
|
+
validate_identity(lane, "lane")
|
|
96
|
+
if _PROVIDER.fullmatch(provider) is None:
|
|
97
|
+
raise LedgerError("invalid", "provider must be a named meter")
|
|
98
|
+
binding = None
|
|
99
|
+
if provider == OPENROUTER_PROVIDER:
|
|
100
|
+
binding = openrouter_bindings.get(run) if openrouter_bindings is not None else None
|
|
101
|
+
if binding is None:
|
|
102
|
+
raise LedgerError("invalid", "the run needs a configured OpenRouter key binding")
|
|
103
|
+
cap = _budget_cap(args["cap_usd"])
|
|
104
|
+
current = await uow.find_lane(lane)
|
|
105
|
+
if current is None or current.state == "archived":
|
|
106
|
+
raise LedgerError("conflict", "a budget requires a current lane")
|
|
107
|
+
if await uow.find_budget(run) is not None:
|
|
108
|
+
raise LedgerError("conflict", "this run already has a budget")
|
|
109
|
+
if binding is not None and not await uow.reserve_openrouter_key(binding, run):
|
|
110
|
+
raise LedgerError("conflict", "the OpenRouter key is already reserved for a budget")
|
|
111
|
+
budget = Budget(f"bud_{uuid.uuid7()}", run, lane, cap, provider, key_scope)
|
|
112
|
+
await uow.insert_budget(budget)
|
|
113
|
+
return budget.render()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def record_budget_observations(
|
|
117
|
+
uow: UnitOfWork, readings: tuple[UsageObservation, ...]
|
|
118
|
+
) -> None:
|
|
119
|
+
latest: dict[tuple[str, str], UsageObservation] = {}
|
|
120
|
+
for reading in readings:
|
|
121
|
+
if not reading.complete:
|
|
122
|
+
continue
|
|
123
|
+
pair = (reading.meter, reading.run)
|
|
124
|
+
previous = latest.get(pair)
|
|
125
|
+
if previous is None or reading.as_of > previous.as_of:
|
|
126
|
+
latest[pair] = reading
|
|
127
|
+
for reading in latest.values():
|
|
128
|
+
budget = await uow.find_budget(reading.run)
|
|
129
|
+
if budget is None or budget.provider != reading.meter:
|
|
130
|
+
continue
|
|
131
|
+
if budget.as_of is not None and reading.as_of <= datetime.fromisoformat(budget.as_of):
|
|
132
|
+
continue
|
|
133
|
+
# The current-key endpoint has no provider watermark. A repeated or lower counter
|
|
134
|
+
# cannot establish newer spend for this fixed, non-resetting key.
|
|
135
|
+
if (
|
|
136
|
+
budget.provider == OPENROUTER_PROVIDER
|
|
137
|
+
and budget.as_of is not None
|
|
138
|
+
and reading.spent_usd <= budget.spent_usd
|
|
139
|
+
):
|
|
140
|
+
continue
|
|
141
|
+
as_of = reading.as_of.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
|
142
|
+
budget = replace(budget, spent_usd=reading.spent_usd, as_of=as_of)
|
|
143
|
+
await uow.update_budget_spend(budget)
|
|
144
|
+
await _apply_thresholds(uow, budget)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def reaches_budget_ratio(budget: Budget, threshold: int | float | Fraction) -> bool:
|
|
148
|
+
if budget.as_of is None:
|
|
149
|
+
return False
|
|
150
|
+
# Use decimal spellings and exact products at the threshold boundary.
|
|
151
|
+
ratio = Fraction(str(threshold)) if isinstance(threshold, float) else threshold
|
|
152
|
+
return Fraction(str(budget.spent_usd)) >= Fraction(str(budget.cap_usd)) * ratio
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
async def _apply_thresholds(uow: UnitOfWork, budget: Budget) -> None:
|
|
156
|
+
for percent in (50, 80, 100):
|
|
157
|
+
if not reaches_budget_ratio(budget, Fraction(percent, 100)):
|
|
158
|
+
break
|
|
159
|
+
subject = f"{budget.id}:{percent}"
|
|
160
|
+
fields = {
|
|
161
|
+
"budget_id": budget.id,
|
|
162
|
+
"run": budget.run,
|
|
163
|
+
"lane": budget.lane,
|
|
164
|
+
"percent": percent,
|
|
165
|
+
"cap_usd": budget.cap_usd,
|
|
166
|
+
"spent_usd": budget.spent_usd,
|
|
167
|
+
"as_of": budget.as_of,
|
|
168
|
+
}
|
|
169
|
+
# Keep the lane in the fields so meter activity does not reset the lane's idle clock.
|
|
170
|
+
threshold = await uow.append(NewEvent("core", BUDGET_THRESHOLD, subject, fields))
|
|
171
|
+
if not threshold.created:
|
|
172
|
+
continue
|
|
173
|
+
item = await uow.raise_item(BUDGET_ITEM.name, subject, "orchestrator", fields)
|
|
174
|
+
if percent == 100:
|
|
175
|
+
lane = await uow.find_lane(budget.lane)
|
|
176
|
+
if lane is not None and lane.state != "archived":
|
|
177
|
+
await uow.enqueue_action(
|
|
178
|
+
threshold.event,
|
|
179
|
+
SEND,
|
|
180
|
+
{"worker": lane.worker, "lane": lane.id, "text": "stop"},
|
|
181
|
+
stable_key=item.dedup_key,
|
|
182
|
+
)
|