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,51 @@
|
|
|
1
|
+
"""Poll explicitly bound local sessions and submit their observations to core."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
|
|
7
|
+
from plotroom.core.events import LedgerError
|
|
8
|
+
from plotroom.core.intake import record_claude
|
|
9
|
+
from plotroom.core.lanes import infer_lane
|
|
10
|
+
from plotroom.core.ledger import Ledger
|
|
11
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
12
|
+
from plotroom.ports.session_reader import SessionEvent, SessionReader
|
|
13
|
+
|
|
14
|
+
log = logging.getLogger("plotroom.session_intake")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SessionIntake:
|
|
18
|
+
def __init__(
|
|
19
|
+
self, ledger: Ledger, reader: SessionReader, sessions: Mapping[str, str], seconds: int
|
|
20
|
+
) -> None:
|
|
21
|
+
self._ledger = ledger
|
|
22
|
+
self._reader = reader
|
|
23
|
+
self._sessions = sessions
|
|
24
|
+
self._seconds = seconds
|
|
25
|
+
|
|
26
|
+
async def poll(self) -> None:
|
|
27
|
+
for session, worker in self._sessions.items():
|
|
28
|
+
observed = await self._reader.read(session)
|
|
29
|
+
if not observed or await self._record(worker, observed):
|
|
30
|
+
self._reader.accept(session)
|
|
31
|
+
|
|
32
|
+
async def _record(self, worker: str, events: tuple[SessionEvent, ...]) -> bool:
|
|
33
|
+
async def record(uow: UnitOfWork) -> bool:
|
|
34
|
+
lane = await infer_lane(uow, worker=worker)
|
|
35
|
+
if lane is None:
|
|
36
|
+
return False
|
|
37
|
+
for event in events:
|
|
38
|
+
try:
|
|
39
|
+
await record_claude(uow, event, lane=lane)
|
|
40
|
+
except LedgerError as exc:
|
|
41
|
+
if exc.code != "invalid":
|
|
42
|
+
raise
|
|
43
|
+
log.warning("invalid Desktop observation", extra={"kind": event.kind})
|
|
44
|
+
return True
|
|
45
|
+
|
|
46
|
+
return await self._ledger.run("system", record)
|
|
47
|
+
|
|
48
|
+
async def run(self) -> None:
|
|
49
|
+
while True:
|
|
50
|
+
await self.poll()
|
|
51
|
+
await asyncio.sleep(self._seconds)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""The SQLite floor (AD-4): older builds can corrupt a WAL database.
|
|
2
|
+
|
|
3
|
+
Fixed in 3.51.3, and backported to 3.44.6 and 3.50.7. Below that the server reports not ready and
|
|
4
|
+
never opens a project file.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sqlite3
|
|
10
|
+
|
|
11
|
+
FLOOR_TEXT = "3.51.3 or later (or 3.44.6 / 3.50.7 backports)"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_version(text: str) -> tuple[int, int, int]:
|
|
15
|
+
parts = [int(p) for p in text.split(".")[:3]]
|
|
16
|
+
while len(parts) < 3:
|
|
17
|
+
parts.append(0)
|
|
18
|
+
return parts[0], parts[1], parts[2]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def meets_floor(version: str) -> bool:
|
|
22
|
+
major, minor, patch = parse_version(version)
|
|
23
|
+
if (major, minor) == (3, 44):
|
|
24
|
+
return patch >= 6
|
|
25
|
+
if (major, minor) == (3, 50):
|
|
26
|
+
return patch >= 7
|
|
27
|
+
return (major, minor, patch) >= (3, 51, 3)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def floor_problem(version: str | None = None) -> str | None:
|
|
31
|
+
"""``None`` when the SQLite in use meets the floor, else a sentence saying why not."""
|
|
32
|
+
found = version if version is not None else sqlite3.sqlite_version
|
|
33
|
+
if meets_floor(found):
|
|
34
|
+
return None
|
|
35
|
+
return f"SQLite {found} is below the floor ({FLOOR_TEXT}); use a uv-managed Python"
|
plotroom/app/tokens.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""Offline token administration and request-time authentication (AD-8)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import errno
|
|
8
|
+
import fcntl
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import secrets
|
|
15
|
+
import stat
|
|
16
|
+
import tempfile
|
|
17
|
+
from collections.abc import Generator
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, TypedDict, cast
|
|
21
|
+
|
|
22
|
+
from plotroom.core.roles import Identity, validate_token_role
|
|
23
|
+
|
|
24
|
+
INSTANCE_TOKEN_FILE_NAME = "instance-tokens.json" # noqa: S105
|
|
25
|
+
LOCAL_TOKEN_FILE_NAME = "tokens.json" # noqa: S105
|
|
26
|
+
_ID = re.compile(r"[a-f0-9]{24}")
|
|
27
|
+
_BEARER = re.compile(r"([a-f0-9]{24})\.[A-Za-z0-9_-]{43}")
|
|
28
|
+
_HASH = re.compile(r"[a-f0-9]{64}")
|
|
29
|
+
_PRIVATE_MODE = 0o600
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class TokenError(Exception):
|
|
33
|
+
"""The credential store or token selection could not be used."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class LocalCleanupError(TokenError):
|
|
37
|
+
"""The instance token is revoked and removing its local copy failed."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, failure: TokenError | OSError) -> None:
|
|
40
|
+
super().__init__("token is revoked. local credential cleanup failed")
|
|
41
|
+
self.failure = failure
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _InstanceRecord(TypedDict):
|
|
45
|
+
hash: str
|
|
46
|
+
project: str
|
|
47
|
+
role: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class IssuedToken:
|
|
52
|
+
token_id: str
|
|
53
|
+
bearer: str = field(repr=False)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def local_token_path() -> Path:
|
|
57
|
+
return Path.home() / ".config" / "plotroom" / LOCAL_TOKEN_FILE_NAME
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _digest(bearer: str) -> str:
|
|
61
|
+
return hashlib.sha256(bearer.encode("ascii")).hexdigest()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@contextlib.contextmanager
|
|
65
|
+
def _locked(path: Path) -> Generator[None]:
|
|
66
|
+
# Atomic replacement changes the data file's inode, so writers lock a separate file.
|
|
67
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
68
|
+
lock = path.with_suffix(".lock")
|
|
69
|
+
fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, _PRIVATE_MODE)
|
|
70
|
+
try:
|
|
71
|
+
fcntl.flock(fd, fcntl.LOCK_EX)
|
|
72
|
+
yield
|
|
73
|
+
finally:
|
|
74
|
+
os.close(fd)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _read(path: Path) -> dict[str, Any]:
|
|
78
|
+
try:
|
|
79
|
+
fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
80
|
+
except FileNotFoundError:
|
|
81
|
+
return {}
|
|
82
|
+
except OSError as exc:
|
|
83
|
+
if exc.errno == errno.ELOOP:
|
|
84
|
+
raise TokenError(f"token file {path} must be a regular file with mode 0600") from exc
|
|
85
|
+
raise
|
|
86
|
+
try:
|
|
87
|
+
info = os.fstat(fd)
|
|
88
|
+
if not stat.S_ISREG(info.st_mode) or stat.S_IMODE(info.st_mode) != _PRIVATE_MODE:
|
|
89
|
+
raise TokenError(f"token file {path} must be a regular file with mode 0600")
|
|
90
|
+
with os.fdopen(fd, encoding="utf-8", closefd=False) as handle:
|
|
91
|
+
raw: Any = json.load(handle)
|
|
92
|
+
except ValueError, RecursionError:
|
|
93
|
+
raise TokenError(f"invalid token file {path}") from None
|
|
94
|
+
finally:
|
|
95
|
+
os.close(fd)
|
|
96
|
+
if not isinstance(raw, dict):
|
|
97
|
+
raise TokenError(f"invalid token file {path}")
|
|
98
|
+
return cast("dict[str, Any]", raw)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _read_instance(path: Path) -> dict[str, _InstanceRecord]:
|
|
102
|
+
return _validate_instance(path, _read(path))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _validate_instance(path: Path, records: dict[str, Any]) -> dict[str, _InstanceRecord]:
|
|
106
|
+
for token_id, raw in records.items():
|
|
107
|
+
if not _ID.fullmatch(token_id) or not isinstance(raw, dict):
|
|
108
|
+
raise TokenError(f"invalid instance token file {path}")
|
|
109
|
+
record = cast("dict[str, Any]", raw)
|
|
110
|
+
digest, project, role = record.get("hash"), record.get("project"), record.get("role")
|
|
111
|
+
if (
|
|
112
|
+
record.keys() != {"hash", "project", "role"}
|
|
113
|
+
or not isinstance(digest, str)
|
|
114
|
+
or not _HASH.fullmatch(digest)
|
|
115
|
+
or not isinstance(project, str)
|
|
116
|
+
or not project
|
|
117
|
+
or not isinstance(role, str)
|
|
118
|
+
):
|
|
119
|
+
raise TokenError(f"invalid instance token file {path}")
|
|
120
|
+
try:
|
|
121
|
+
validate_token_role(role)
|
|
122
|
+
except ValueError:
|
|
123
|
+
raise TokenError(f"invalid instance token file {path}") from None
|
|
124
|
+
return cast("dict[str, _InstanceRecord]", records)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _read_local(path: Path) -> dict[str, dict[str, str]]:
|
|
128
|
+
records = _read(path)
|
|
129
|
+
for raw in records.values():
|
|
130
|
+
if not isinstance(raw, dict):
|
|
131
|
+
raise TokenError(f"invalid local token file {path}")
|
|
132
|
+
for token_id, bearer in cast("dict[str, Any]", raw).items():
|
|
133
|
+
match = _BEARER.fullmatch(bearer) if isinstance(bearer, str) else None
|
|
134
|
+
if match is None or match[1] != token_id:
|
|
135
|
+
raise TokenError(f"invalid local token file {path}")
|
|
136
|
+
return cast("dict[str, dict[str, str]]", records)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _write(path: Path, records: dict[str, Any]) -> None:
|
|
140
|
+
fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
|
|
141
|
+
try:
|
|
142
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
143
|
+
os.fchmod(handle.fileno(), _PRIVATE_MODE)
|
|
144
|
+
json.dump(records, handle, indent=2, sort_keys=True)
|
|
145
|
+
handle.write("\n")
|
|
146
|
+
handle.flush()
|
|
147
|
+
os.fsync(handle.fileno())
|
|
148
|
+
os.replace(temporary, path)
|
|
149
|
+
finally:
|
|
150
|
+
with contextlib.suppress(OSError):
|
|
151
|
+
Path(temporary).unlink(missing_ok=True)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def select_local_token(data_dir: Path, token_id: str | None) -> str | None:
|
|
155
|
+
"""Select the credential keyed by the connection's already-canonical data directory."""
|
|
156
|
+
entries = _read_local(local_token_path()).get(str(data_dir), {})
|
|
157
|
+
if token_id is not None:
|
|
158
|
+
if token_id not in entries:
|
|
159
|
+
raise TokenError("no local token with the selected ID for this data directory")
|
|
160
|
+
return entries[token_id]
|
|
161
|
+
if len(entries) > 1:
|
|
162
|
+
raise TokenError("several local tokens exist for this data directory; use --token-id")
|
|
163
|
+
return next(iter(entries.values()), None)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class TokenRegistry:
|
|
167
|
+
"""The authoritative instance file contains only public IDs, hashes, projects and roles."""
|
|
168
|
+
|
|
169
|
+
def __init__(self, data_dir: Path) -> None:
|
|
170
|
+
self._data_dir = data_dir.resolve()
|
|
171
|
+
self.path = self._data_dir / INSTANCE_TOKEN_FILE_NAME
|
|
172
|
+
|
|
173
|
+
def issue(self, project_id: str, role: str, *, local: bool = True) -> IssuedToken:
|
|
174
|
+
if not project_id:
|
|
175
|
+
raise TokenError("invalid token project ID")
|
|
176
|
+
validate_token_role(role)
|
|
177
|
+
with _locked(self.path):
|
|
178
|
+
records = _read_instance(self.path)
|
|
179
|
+
token_id = secrets.token_hex(12)
|
|
180
|
+
while token_id in records:
|
|
181
|
+
token_id = secrets.token_hex(12)
|
|
182
|
+
bearer = f"{token_id}.{secrets.token_urlsafe(32)}"
|
|
183
|
+
records[token_id] = {"hash": _digest(bearer), "project": project_id, "role": role}
|
|
184
|
+
if local:
|
|
185
|
+
self._save_locally(token_id, bearer, records)
|
|
186
|
+
else:
|
|
187
|
+
_write(self.path, records)
|
|
188
|
+
return IssuedToken(token_id, bearer)
|
|
189
|
+
|
|
190
|
+
def _save_locally(
|
|
191
|
+
self, token_id: str, bearer: str, records: dict[str, _InstanceRecord]
|
|
192
|
+
) -> None:
|
|
193
|
+
local = local_token_path()
|
|
194
|
+
with _locked(local):
|
|
195
|
+
local_records = _read_local(local)
|
|
196
|
+
entries = local_records.get(str(self._data_dir), {})
|
|
197
|
+
local_records[str(self._data_dir)] = {**entries, token_id: bearer}
|
|
198
|
+
_write(self.path, records)
|
|
199
|
+
try:
|
|
200
|
+
_write(local, local_records)
|
|
201
|
+
except OSError:
|
|
202
|
+
# The local credential was never published. Remove its orphan hash if possible.
|
|
203
|
+
del records[token_id]
|
|
204
|
+
with contextlib.suppress(OSError):
|
|
205
|
+
_write(self.path, records)
|
|
206
|
+
raise
|
|
207
|
+
|
|
208
|
+
def revoke(self, token_id: str, *, local: bool = True) -> None:
|
|
209
|
+
if not _ID.fullmatch(token_id):
|
|
210
|
+
raise TokenError("invalid token ID")
|
|
211
|
+
with _locked(self.path):
|
|
212
|
+
records = _read_instance(self.path)
|
|
213
|
+
if token_id in records:
|
|
214
|
+
del records[token_id]
|
|
215
|
+
_write(self.path, records)
|
|
216
|
+
if local:
|
|
217
|
+
try:
|
|
218
|
+
self._remove_local(token_id)
|
|
219
|
+
except (TokenError, OSError) as exc:
|
|
220
|
+
raise LocalCleanupError(exc) from exc
|
|
221
|
+
|
|
222
|
+
def _remove_local(self, token_id: str) -> None:
|
|
223
|
+
path = local_token_path()
|
|
224
|
+
with _locked(path):
|
|
225
|
+
local_records = _read_local(path)
|
|
226
|
+
entries = local_records.get(str(self._data_dir), {})
|
|
227
|
+
if token_id in entries:
|
|
228
|
+
del entries[token_id]
|
|
229
|
+
_write(path, local_records)
|
|
230
|
+
|
|
231
|
+
async def has_role(self, project_id: str, role: str) -> bool:
|
|
232
|
+
"""Check whether the instance has a token for the project role."""
|
|
233
|
+
try:
|
|
234
|
+
records = await asyncio.to_thread(_read_instance, self.path)
|
|
235
|
+
except OSError, TokenError:
|
|
236
|
+
return False
|
|
237
|
+
return any(
|
|
238
|
+
record["project"] == project_id and record["role"] == role
|
|
239
|
+
for record in records.values()
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
async def authenticate(self, bearer: str) -> Identity | None:
|
|
243
|
+
"""Read the current atomic snapshot so the next request sees issue and revoke."""
|
|
244
|
+
match = _BEARER.fullmatch(bearer)
|
|
245
|
+
if match is None:
|
|
246
|
+
return None
|
|
247
|
+
try:
|
|
248
|
+
return await asyncio.to_thread(self._authenticate_from_disk, match[1], bearer)
|
|
249
|
+
except OSError, TokenError:
|
|
250
|
+
return None
|
|
251
|
+
|
|
252
|
+
def _authenticate_from_disk(self, token_id: str, bearer: str) -> Identity | None:
|
|
253
|
+
records = _read(self.path)
|
|
254
|
+
raw: Any = records.get(token_id)
|
|
255
|
+
if not isinstance(raw, dict):
|
|
256
|
+
return None
|
|
257
|
+
digest = cast("dict[str, Any]", raw).get("hash")
|
|
258
|
+
if (
|
|
259
|
+
not isinstance(digest, str)
|
|
260
|
+
or not _HASH.fullmatch(digest)
|
|
261
|
+
or not hmac.compare_digest(_digest(bearer), digest)
|
|
262
|
+
):
|
|
263
|
+
return None
|
|
264
|
+
record = _validate_instance(self.path, records)[token_id]
|
|
265
|
+
return Identity(record["project"], record["role"])
|
|
File without changes
|
plotroom/core/actions.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Cause-derived actions committed with their originating unit of work (AD-14)."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, replace
|
|
4
|
+
from typing import TYPE_CHECKING, Any
|
|
5
|
+
|
|
6
|
+
from plotroom.core.events import FieldSpec, LedgerError, NewEvent
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
10
|
+
|
|
11
|
+
FAILED_ACTION = "failed_action"
|
|
12
|
+
BRANCH_UPDATE = "branch_update"
|
|
13
|
+
CONTROLLER_MERGE = "controller_merge"
|
|
14
|
+
SWITCHBOARD_SEND = "switchboard.send"
|
|
15
|
+
ACTION_FIELDS = (FieldSpec("action_key", "str"), FieldSpec("attempt", "int"))
|
|
16
|
+
ACTION_PAGE_SIZE = 32
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Action:
|
|
21
|
+
key: str
|
|
22
|
+
kind: str
|
|
23
|
+
cause_id: str
|
|
24
|
+
payload: dict[str, Any]
|
|
25
|
+
attempts: int = 0
|
|
26
|
+
state: str = "pending"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class QueuedAction:
|
|
31
|
+
position: int
|
|
32
|
+
action: Action
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
async def record_attempt(uow: UnitOfWork, action: Action) -> Action:
|
|
36
|
+
attempted = replace(action, attempts=action.attempts + 1)
|
|
37
|
+
await uow.append(
|
|
38
|
+
NewEvent(
|
|
39
|
+
"core",
|
|
40
|
+
"core.action_attempt",
|
|
41
|
+
f"{action.key}:{attempted.attempts}",
|
|
42
|
+
{"action_key": action.key, "attempt": attempted.attempts},
|
|
43
|
+
)
|
|
44
|
+
)
|
|
45
|
+
await uow.update_action(attempted)
|
|
46
|
+
return attempted
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def finish_action(
|
|
50
|
+
uow: UnitOfWork, action: Action, state: str, *, failure_reason: str | None = None
|
|
51
|
+
) -> None:
|
|
52
|
+
if state not in {"done", "failed"}:
|
|
53
|
+
raise LedgerError("invalid", "invalid action result")
|
|
54
|
+
await uow.append(
|
|
55
|
+
NewEvent(
|
|
56
|
+
"core",
|
|
57
|
+
f"core.action_{state}",
|
|
58
|
+
action.key,
|
|
59
|
+
{"action_key": action.key, "attempt": action.attempts},
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
await uow.update_action(replace(action, state=state))
|
|
63
|
+
if state == "failed":
|
|
64
|
+
context = {"action_key": action.key, "kind": action.kind, "attempts": action.attempts}
|
|
65
|
+
if failure_reason is not None:
|
|
66
|
+
context["reason"] = failure_reason
|
|
67
|
+
await uow.raise_item(FAILED_ACTION, action.key, "orchestrator", context)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Pure conditions for the orchestrator's GitHub ask queue."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from plotroom.core.next_items import ItemKind
|
|
8
|
+
|
|
9
|
+
ASK_BURIED = "ask_buried"
|
|
10
|
+
ASK_OPTIONLESS = "ask_optionless"
|
|
11
|
+
ASK_STALE = "ask_stale"
|
|
12
|
+
ASK_ORPHANED = "ask_orphaned"
|
|
13
|
+
DEFAULT_ASK_STALE_DAYS = 7
|
|
14
|
+
ASK_ITEMS = (
|
|
15
|
+
ItemKind(ASK_BURIED, 20, True, ("Review the ask and the latest issue comments",)),
|
|
16
|
+
ItemKind(ASK_OPTIONLESS, 20, True, ("Record the options for the ask",)),
|
|
17
|
+
ItemKind(ASK_STALE, 20, True, ("Review the outstanding ask",)),
|
|
18
|
+
ItemKind(ASK_ORPHANED, 20, True, ("Review the ask on the closed issue",)),
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Ask:
|
|
24
|
+
ask_id: str
|
|
25
|
+
repository: str
|
|
26
|
+
issue: int
|
|
27
|
+
text: str
|
|
28
|
+
options: tuple[str, ...]
|
|
29
|
+
comment_id: int
|
|
30
|
+
comment_created_at: str
|
|
31
|
+
created_at: str
|
|
32
|
+
settled_by: str | None = None
|
|
33
|
+
|
|
34
|
+
def render(self) -> dict[str, Any]:
|
|
35
|
+
return {
|
|
36
|
+
"ask_id": self.ask_id,
|
|
37
|
+
"repository": self.repository,
|
|
38
|
+
"issue": self.issue,
|
|
39
|
+
"text": self.text,
|
|
40
|
+
"options": list(self.options),
|
|
41
|
+
"comment_id": self.comment_id,
|
|
42
|
+
"comment_created_at": self.comment_created_at,
|
|
43
|
+
"created_at": self.created_at,
|
|
44
|
+
"settled_by": self.settled_by,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class IssueComment:
|
|
50
|
+
id: int
|
|
51
|
+
author: str | None
|
|
52
|
+
created_at: datetime | None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def comment_time(value: str) -> datetime | None:
|
|
56
|
+
try:
|
|
57
|
+
time = datetime.fromisoformat(value)
|
|
58
|
+
except ValueError:
|
|
59
|
+
return None
|
|
60
|
+
return time if time.utcoffset() is not None else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def ask_conditions(
|
|
64
|
+
ask: Ask,
|
|
65
|
+
comments: list[IssueComment],
|
|
66
|
+
*,
|
|
67
|
+
issue_state: str | None,
|
|
68
|
+
history_complete: bool,
|
|
69
|
+
human_login: str | None,
|
|
70
|
+
stale_days: int,
|
|
71
|
+
now: datetime,
|
|
72
|
+
) -> dict[str, bool | None]:
|
|
73
|
+
"""Unknown conditions preserve any existing item while evidence catches up."""
|
|
74
|
+
if ask.settled_by is not None:
|
|
75
|
+
return dict.fromkeys((kind.name for kind in ASK_ITEMS), False)
|
|
76
|
+
|
|
77
|
+
posted = datetime.fromisoformat(ask.comment_created_at)
|
|
78
|
+
known_human = human_login.casefold() if human_login else None
|
|
79
|
+
later: list[tuple[datetime, str | None]] = []
|
|
80
|
+
uncertain = False
|
|
81
|
+
for comment in comments:
|
|
82
|
+
if comment.id == ask.comment_id:
|
|
83
|
+
continue
|
|
84
|
+
author = comment.author.casefold() if comment.author else None
|
|
85
|
+
moment = comment.created_at
|
|
86
|
+
if moment is not None and moment > posted:
|
|
87
|
+
later.append((moment, author))
|
|
88
|
+
elif (moment is None or moment == posted) and author in (known_human, None):
|
|
89
|
+
uncertain = True
|
|
90
|
+
|
|
91
|
+
buried: bool | None = None
|
|
92
|
+
replied = known_human is not None and any(author == known_human for _, author in later)
|
|
93
|
+
if known_human is not None:
|
|
94
|
+
latest = max((moment for moment, _ in later), default=None)
|
|
95
|
+
latest_authors = {author for moment, author in later if moment == latest}
|
|
96
|
+
if known_human in latest_authors:
|
|
97
|
+
buried = False
|
|
98
|
+
elif latest_authors and None not in latest_authors and not uncertain:
|
|
99
|
+
buried = True
|
|
100
|
+
elif not latest_authors and history_complete and not uncertain:
|
|
101
|
+
buried = False
|
|
102
|
+
|
|
103
|
+
orphaned: bool | None = None
|
|
104
|
+
if issue_state == "open" or (history_complete and replied):
|
|
105
|
+
orphaned = False
|
|
106
|
+
elif (
|
|
107
|
+
issue_state == "closed"
|
|
108
|
+
and history_complete
|
|
109
|
+
and known_human is not None
|
|
110
|
+
and not uncertain
|
|
111
|
+
and all(author is not None for _, author in later)
|
|
112
|
+
):
|
|
113
|
+
orphaned = True
|
|
114
|
+
|
|
115
|
+
age = now - posted
|
|
116
|
+
stale = age.days > stale_days or (
|
|
117
|
+
age.days == stale_days and (age.seconds > 0 or age.microseconds > 0)
|
|
118
|
+
)
|
|
119
|
+
return {
|
|
120
|
+
ASK_BURIED: buried,
|
|
121
|
+
ASK_OPTIONLESS: not ask.options,
|
|
122
|
+
ASK_STALE: stale,
|
|
123
|
+
ASK_ORPHANED: orphaned,
|
|
124
|
+
}
|
plotroom/core/asks.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Record projected GitHub asks and reconcile their state-backed next items."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import replace
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from plotroom.core.ask_checks import ASK_ITEMS, Ask, ask_conditions, comment_time
|
|
10
|
+
from plotroom.core.events import LedgerError, format_time
|
|
11
|
+
from plotroom.core.github_projection import (
|
|
12
|
+
ISSUES,
|
|
13
|
+
ask_history_version,
|
|
14
|
+
projected_comment,
|
|
15
|
+
projected_issues,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from plotroom.core.unit_of_work import UnitOfWork
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
async def record_ask(
|
|
23
|
+
uow: UnitOfWork, args: dict[str, Any], *, repository: str | None
|
|
24
|
+
) -> dict[str, Any]:
|
|
25
|
+
if repository is None:
|
|
26
|
+
raise LedgerError("unavailable", "the project has no GitHub issue projection")
|
|
27
|
+
issue: int = args["issue"]
|
|
28
|
+
comment_id: int = args["comment_id"]
|
|
29
|
+
text: str = args["text"]
|
|
30
|
+
options: list[Any] = args["options"]
|
|
31
|
+
if not (0 < issue < 2**63 and 0 < comment_id < 2**63):
|
|
32
|
+
raise LedgerError("invalid", "issue and comment_id must be positive GitHub numbers")
|
|
33
|
+
if not text.strip() or not all(
|
|
34
|
+
isinstance(option, str) and option.strip() for option in options
|
|
35
|
+
):
|
|
36
|
+
raise LedgerError("invalid", "ask text and each option must be nonempty text")
|
|
37
|
+
try:
|
|
38
|
+
for option in options:
|
|
39
|
+
option.encode("utf-8")
|
|
40
|
+
except UnicodeEncodeError:
|
|
41
|
+
raise LedgerError("invalid", "ask options must be valid UTF-8 text") from None
|
|
42
|
+
comment = await projected_comment(uow, repository, issue, comment_id)
|
|
43
|
+
if issue not in projected_issues(await uow.github_resource(repository, ISSUES)):
|
|
44
|
+
raise LedgerError("unavailable", "the issue is not in a complete GitHub issue projection")
|
|
45
|
+
if text not in comment.body:
|
|
46
|
+
raise LedgerError("invalid", "ask text does not occur in the projected comment")
|
|
47
|
+
posted = comment_time(comment.fields["created_at"])
|
|
48
|
+
if posted is None:
|
|
49
|
+
raise LedgerError("unavailable", "the projected comment has no usable creation time")
|
|
50
|
+
existing = await uow.ask_for_comment(repository, comment_id)
|
|
51
|
+
if existing is None:
|
|
52
|
+
record = Ask(
|
|
53
|
+
f"ask_{uuid.uuid7()}",
|
|
54
|
+
repository,
|
|
55
|
+
issue,
|
|
56
|
+
text,
|
|
57
|
+
tuple(options),
|
|
58
|
+
comment_id,
|
|
59
|
+
format_time(posted),
|
|
60
|
+
format_time(uow.now()),
|
|
61
|
+
)
|
|
62
|
+
else:
|
|
63
|
+
record = replace(existing, text=text, options=tuple(options))
|
|
64
|
+
if existing == record:
|
|
65
|
+
return {"ask_id": existing.ask_id}
|
|
66
|
+
if existing.settled_by is not None:
|
|
67
|
+
raise LedgerError("conflict", "the ask has already been settled")
|
|
68
|
+
await uow.save_ask(record)
|
|
69
|
+
return {"ask_id": record.ask_id}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def reconcile_asks(
|
|
73
|
+
uow: UnitOfWork, repository: str | None, human_login: str | None, stale_days: int
|
|
74
|
+
) -> None:
|
|
75
|
+
if repository is None:
|
|
76
|
+
return
|
|
77
|
+
asks = await uow.unsettled_asks(repository)
|
|
78
|
+
if not asks:
|
|
79
|
+
return
|
|
80
|
+
numbers = {ask.issue for ask in asks}
|
|
81
|
+
issues = projected_issues(await uow.github_resource(repository, ISSUES))
|
|
82
|
+
histories = await uow.ask_comment_histories(repository, numbers & issues.keys())
|
|
83
|
+
comments = await uow.ask_comments(repository, numbers)
|
|
84
|
+
now = uow.now()
|
|
85
|
+
for ask in asks:
|
|
86
|
+
issue = issues.get(ask.issue)
|
|
87
|
+
coverage = ask_history_version(issue) if issue is not None else None
|
|
88
|
+
history = histories.get(ask.issue)
|
|
89
|
+
current_history = coverage is not None and history is not None and coverage[0] == history[0]
|
|
90
|
+
issue_comments = comments.get(ask.issue, [])
|
|
91
|
+
if current_history and history is not None:
|
|
92
|
+
issue_comments = [comment for comment in issue_comments if comment.id in history[1]]
|
|
93
|
+
conditions = ask_conditions(
|
|
94
|
+
ask,
|
|
95
|
+
issue_comments,
|
|
96
|
+
issue_state=issue.fields["state"] if issue is not None else None,
|
|
97
|
+
history_complete=current_history,
|
|
98
|
+
human_login=human_login,
|
|
99
|
+
stale_days=stale_days,
|
|
100
|
+
now=now,
|
|
101
|
+
)
|
|
102
|
+
for kind, applies in conditions.items():
|
|
103
|
+
if applies is True:
|
|
104
|
+
await uow.raise_item(
|
|
105
|
+
kind,
|
|
106
|
+
ask.ask_id,
|
|
107
|
+
"orchestrator",
|
|
108
|
+
{
|
|
109
|
+
"ask_id": ask.ask_id,
|
|
110
|
+
"repository": ask.repository,
|
|
111
|
+
"issue": ask.issue,
|
|
112
|
+
"comment_id": ask.comment_id,
|
|
113
|
+
},
|
|
114
|
+
)
|
|
115
|
+
elif applies is False:
|
|
116
|
+
await uow.clear_item(kind, ask.ask_id)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def settle_asks(uow: UnitOfWork, asks: list[Ask], decision_id: str) -> None:
|
|
120
|
+
for ask in asks:
|
|
121
|
+
await uow.save_ask(replace(ask, settled_by=decision_id))
|
|
122
|
+
for kind in ASK_ITEMS:
|
|
123
|
+
await uow.clear_item(kind.name, ask.ask_id)
|