tempergraph 0.7.1__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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- tempergraph_pytest_plugin.py +64 -0
|
@@ -0,0 +1,520 @@
|
|
|
1
|
+
"""The code host client for filing (ADR `first-release-is-simple-trusted-workflows-on-one-machine` S5): GitHub through the person's own `gh` sign-in.
|
|
2
|
+
|
|
3
|
+
A sanctioned launch site (SEC-B7): constant subcommands as list argv, the repository checked as
|
|
4
|
+
`owner/name`, the issue number an int, and every user-derived text (title, body, comment) on stdin as JSON
|
|
5
|
+
through `gh api --input -`. Never imports or opens the evidence file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import subprocess
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from datetime import UTC, datetime
|
|
18
|
+
from typing import Any, Protocol
|
|
19
|
+
from urllib.parse import quote
|
|
20
|
+
|
|
21
|
+
REPO = re.compile(r"^[A-Za-z0-9_.-]{1,100}/[A-Za-z0-9_.-]{1,100}$")
|
|
22
|
+
LOOP_LABEL = "tempergraph-loop" # the label every loop issue carries (ISS-B1); its list read (ISS-B9) filters on it
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CodeHostError(Exception):
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class NotFound(CodeHostError):
|
|
30
|
+
"""The host answered `HTTP 404` or `HTTP 410`."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CodeHost(Protocol):
|
|
34
|
+
def loop_issues(self, repo: str, state: str) -> list[dict[str, Any]]:
|
|
35
|
+
"""The issues with the loop's label in `state`, each with `number`, `url`, `body`, `state_reason`,
|
|
36
|
+
`closed_at`, `created_at` (an ISO time, empty when unknown) and `comments` (ICAP-B4)."""
|
|
37
|
+
...
|
|
38
|
+
|
|
39
|
+
def create(self, repo: str, title: str, body: str, labels: list[str]) -> str: ...
|
|
40
|
+
def comment(self, repo: str, number: int, body: str) -> str: ...
|
|
41
|
+
def reopen(self, repo: str, number: int) -> None: ...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class IssueReadHost(Protocol):
|
|
45
|
+
"""Read-only questions about one issue, whatever labels it carries (BND-B12, BND-B13). A comment holds its
|
|
46
|
+
text, its author kind (`person`, `bot` or `other`) and its time; an issue holds `number`, `state`, `state_reason`
|
|
47
|
+
(lower case), `closed_at`, `url`, `comments` (a count) and `is_pull_request`. An issue the host does not hold
|
|
48
|
+
raises `NotFound`."""
|
|
49
|
+
|
|
50
|
+
def issue_comments(self, repo: str, number: int) -> list[dict[str, Any]]: ...
|
|
51
|
+
def issue(self, repo: str, number: int) -> dict[str, Any]: ...
|
|
52
|
+
|
|
53
|
+
def open_issues(self, repo: str) -> list[dict[str, Any]]:
|
|
54
|
+
"""The open issues of the repository that do not carry the loop's label, no pull request, each with
|
|
55
|
+
`number`, `title`, `body`, `author_kind` (`person`, `bot` or `other`) and `comments` (a count)."""
|
|
56
|
+
...
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class PullRequestHost(Protocol):
|
|
60
|
+
"""Draft pull requests for proposals (PRP-B8). There is no merge method, by design (PRP-AC2)."""
|
|
61
|
+
|
|
62
|
+
def default_branch(self, repo: str) -> str: ...
|
|
63
|
+
def create_draft_pr(self, repo: str, head: str, base: str, title: str, body: str, labels: list[str]) -> str: ...
|
|
64
|
+
def pull_state(self, repo: str, number: int) -> dict[str, Any]: ...
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class PullReviewHost(Protocol):
|
|
68
|
+
"""Read-only questions about a pull request's reviews, review comments and commits. Each answer holds an
|
|
69
|
+
author kind (`person`, `bot` or `other`); the text of a review or comment is for local use only. Only the
|
|
70
|
+
commits after `after` hold their changed files."""
|
|
71
|
+
|
|
72
|
+
def pull_reviews(self, repo: str, number: int) -> list[dict[str, Any]]: ...
|
|
73
|
+
def pull_comments(self, repo: str, number: int) -> list[dict[str, Any]]: ...
|
|
74
|
+
def pull_commits(self, repo: str, number: int, after: str = "") -> list[dict[str, Any]]: ...
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
REVIEW_STATES = ("approved", "changes_requested", "commented", "dismissed")
|
|
78
|
+
SHA = re.compile(r"^[0-9a-f]{7,64}$")
|
|
79
|
+
STANDING = ("OWNER", "MEMBER", "COLLABORATOR")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _kind(user: Any, association: Any = None) -> str:
|
|
83
|
+
"""`bot` for a `Bot` account or a `[bot]` login; `person` only for a `User` whose standing the host gives
|
|
84
|
+
(`association` of `OWNER`, `MEMBER` or `COLLABORATOR`); `other` for anything else, a missing user included."""
|
|
85
|
+
if not isinstance(user, dict):
|
|
86
|
+
return "other"
|
|
87
|
+
login = str(user.get("login") or "")
|
|
88
|
+
if user.get("type") == "Bot" or login.endswith("[bot]"):
|
|
89
|
+
return "bot"
|
|
90
|
+
return "person" if user.get("type") == "User" and association in STANDING else "other"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _records(text: str) -> list[dict[str, Any]]:
|
|
94
|
+
out: list[dict[str, Any]] = []
|
|
95
|
+
for ln in text.splitlines():
|
|
96
|
+
if not ln.strip():
|
|
97
|
+
continue
|
|
98
|
+
try:
|
|
99
|
+
r = json.loads(ln)
|
|
100
|
+
except ValueError:
|
|
101
|
+
raise CodeHostError("the pull request answer is not JSON") from None
|
|
102
|
+
if not isinstance(r, dict):
|
|
103
|
+
raise CodeHostError("the pull request answer has no known shape")
|
|
104
|
+
out.append(r)
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
BRANCH = re.compile(r"^(improve/[A-Za-z0-9_.-]{1,80}|tempergraph/upgrade/[A-Za-z0-9_.-]{1,80}/[A-Za-z0-9_.-]{1,40})$")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _check_branch(head: str) -> str:
|
|
112
|
+
if not BRANCH.match(head):
|
|
113
|
+
raise CodeHostError(f"branch {head!r} is not an improve/<proposal> or upgrade branch")
|
|
114
|
+
return head
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _check(repo: str) -> str:
|
|
118
|
+
if not REPO.match(repo):
|
|
119
|
+
raise CodeHostError(f"repository {repo!r} is not owner/name")
|
|
120
|
+
return repo
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _number(value: Any) -> int:
|
|
124
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
125
|
+
raise CodeHostError("the issue number is not a whole number")
|
|
126
|
+
return value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(kw_only=True)
|
|
130
|
+
class GhCodeHost:
|
|
131
|
+
timeout_s: float = 60.0
|
|
132
|
+
|
|
133
|
+
def _gh(self, args: list[str], payload: dict[str, Any] | None = None) -> Any:
|
|
134
|
+
out = self._run(args, payload)
|
|
135
|
+
return json.loads(out) if out.strip() else None
|
|
136
|
+
|
|
137
|
+
def _run(self, args: list[str], payload: dict[str, Any] | None = None) -> str:
|
|
138
|
+
exe = shutil.which("gh")
|
|
139
|
+
if exe is None:
|
|
140
|
+
raise CodeHostError("gh is not installed")
|
|
141
|
+
try:
|
|
142
|
+
proc = subprocess.run( # noqa: S603 - constant subcommands, text on stdin (SEC-B7)
|
|
143
|
+
[exe, *args], input=json.dumps(payload) if payload is not None else None, capture_output=True,
|
|
144
|
+
text=True, timeout=self.timeout_s)
|
|
145
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
146
|
+
raise CodeHostError(type(exc).__name__) from None
|
|
147
|
+
if proc.returncode != 0:
|
|
148
|
+
err = proc.stderr or ""
|
|
149
|
+
if "HTTP 404" in err or "HTTP 410" in err:
|
|
150
|
+
raise NotFound("HTTP 404" if "HTTP 404" in err else "HTTP 410")
|
|
151
|
+
raise CodeHostError(f"gh exited {proc.returncode}")
|
|
152
|
+
return proc.stdout
|
|
153
|
+
|
|
154
|
+
def loop_issues(self, repo: str, state: str) -> list[dict[str, Any]]:
|
|
155
|
+
"""ISS-B9: every issue of the repository in `state` (`open` or `closed`) that carries the loop's label, read
|
|
156
|
+
page by page through the REST list endpoint, not the search index: an issue is listed the moment it exists,
|
|
157
|
+
and the call needs no GraphQL. Pull requests are left out."""
|
|
158
|
+
if state not in ("open", "closed"):
|
|
159
|
+
raise CodeHostError("state is not open or closed")
|
|
160
|
+
text = self._run(["api", "--method", "GET", f"repos/{_check(repo)}/issues", "-f", f"state={state}",
|
|
161
|
+
"-f", f"labels={LOOP_LABEL}", "-f", "per_page=100", "--paginate", "--jq", ".[]"])
|
|
162
|
+
out: list[dict[str, Any]] = []
|
|
163
|
+
for ln in text.splitlines():
|
|
164
|
+
try:
|
|
165
|
+
r = json.loads(ln)
|
|
166
|
+
except ValueError:
|
|
167
|
+
continue
|
|
168
|
+
if not isinstance(r, dict) or r.get("pull_request"):
|
|
169
|
+
continue
|
|
170
|
+
out.append({"number": r.get("number"), "url": r.get("html_url"), "body": r.get("body") or "",
|
|
171
|
+
"state_reason": str(r.get("state_reason") or "").lower(), "closed_at": r.get("closed_at") or "",
|
|
172
|
+
"created_at": r.get("created_at") or "",
|
|
173
|
+
"comments": r.get("comments") if isinstance(r.get("comments"), int) else 0})
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
def open_issues(self, repo: str) -> list[dict[str, Any]]:
|
|
177
|
+
"""PBD-B1: every open issue without the loop's label, read page by page through the REST list endpoint, with
|
|
178
|
+
number, title, body, author kind and comment count. Pull requests are left out."""
|
|
179
|
+
text = self._run(["api", "--method", "GET", f"repos/{_check(repo)}/issues", "-f", "state=open",
|
|
180
|
+
"-f", "per_page=100", "--paginate", "--jq", ".[]"])
|
|
181
|
+
out: list[dict[str, Any]] = []
|
|
182
|
+
for ln in text.splitlines():
|
|
183
|
+
try:
|
|
184
|
+
r = json.loads(ln)
|
|
185
|
+
except ValueError:
|
|
186
|
+
continue
|
|
187
|
+
if not isinstance(r, dict) or r.get("pull_request"):
|
|
188
|
+
continue
|
|
189
|
+
names = [str(lb.get("name")) if isinstance(lb, dict) else str(lb) for lb in r.get("labels") or []]
|
|
190
|
+
if LOOP_LABEL in names:
|
|
191
|
+
continue
|
|
192
|
+
out.append({"number": r.get("number"), "title": str(r.get("title") or ""), "body": str(r.get("body") or ""),
|
|
193
|
+
"author_kind": _kind(r.get("user"), r.get("author_association")),
|
|
194
|
+
"comments": r.get("comments") if isinstance(r.get("comments"), int) else 0})
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
def issue_comments(self, repo: str, number: int) -> list[dict[str, Any]]:
|
|
198
|
+
"""BND-B12: every page of one issue's comments through one paged REST GET, each with its author kind."""
|
|
199
|
+
n = _number(number)
|
|
200
|
+
text = self._run(["api", "--method", "GET", f"repos/{_check(repo)}/issues/{n}/comments",
|
|
201
|
+
"-f", "per_page=100", "--paginate", "--jq", ".[]"])
|
|
202
|
+
return [{"text": str(r.get("body") or ""), "author_kind": _kind(r.get("user"), r.get("author_association")),
|
|
203
|
+
"created_at": str(r.get("created_at") or "")} for r in _records(text)]
|
|
204
|
+
|
|
205
|
+
def issue(self, repo: str, number: int) -> dict[str, Any]:
|
|
206
|
+
"""BND-B13: one REST GET of an issue by number, whatever labels it carries."""
|
|
207
|
+
n = _number(number)
|
|
208
|
+
try:
|
|
209
|
+
got = self._gh(["api", "--method", "GET", f"repos/{_check(repo)}/issues/{n}"])
|
|
210
|
+
except ValueError:
|
|
211
|
+
raise CodeHostError("the issue answer is not JSON") from None
|
|
212
|
+
if not isinstance(got, dict):
|
|
213
|
+
raise CodeHostError("the issue answer has no known shape")
|
|
214
|
+
count = got.get("comments")
|
|
215
|
+
return {"number": got.get("number"), "state": str(got.get("state") or ""),
|
|
216
|
+
"state_reason": str(got.get("state_reason") or "").lower(), "closed_at": got.get("closed_at") or "",
|
|
217
|
+
"url": got.get("html_url") or "", "comments": count if isinstance(count, int) else 0,
|
|
218
|
+
"is_pull_request": bool(got.get("pull_request"))}
|
|
219
|
+
|
|
220
|
+
def create(self, repo: str, title: str, body: str, labels: list[str]) -> str:
|
|
221
|
+
got = self._gh(["api", f"repos/{_check(repo)}/issues", "--method", "POST", "--input", "-"],
|
|
222
|
+
{"title": title, "body": body, "labels": labels})
|
|
223
|
+
return str((got or {}).get("html_url") or "")
|
|
224
|
+
|
|
225
|
+
def comment(self, repo: str, number: int, body: str) -> str:
|
|
226
|
+
got = self._gh(["api", f"repos/{_check(repo)}/issues/{int(number)}/comments", "--method", "POST",
|
|
227
|
+
"--input", "-"], {"body": body})
|
|
228
|
+
return str((got or {}).get("html_url") or "")
|
|
229
|
+
|
|
230
|
+
def issue_state(self, repo: str, number: int) -> str | None:
|
|
231
|
+
"""DRV-B2: `open` or `closed`, None when the issue cannot be read."""
|
|
232
|
+
try:
|
|
233
|
+
got = self._gh(["api", f"repos/{_check(repo)}/issues/{int(number)}"])
|
|
234
|
+
except CodeHostError:
|
|
235
|
+
return None
|
|
236
|
+
state = str((got or {}).get("state") or "")
|
|
237
|
+
return state if state in ("open", "closed") else None
|
|
238
|
+
|
|
239
|
+
def reopen(self, repo: str, number: int) -> None:
|
|
240
|
+
self._gh(["api", f"repos/{_check(repo)}/issues/{int(number)}", "--method", "PATCH", "--input", "-"],
|
|
241
|
+
{"state": "open"})
|
|
242
|
+
|
|
243
|
+
def default_branch(self, repo: str) -> str:
|
|
244
|
+
got = self._gh(["api", f"repos/{_check(repo)}"])
|
|
245
|
+
return str((got or {}).get("default_branch") or "main")
|
|
246
|
+
|
|
247
|
+
def create_draft_pr(self, repo: str, head: str, base: str, title: str, body: str, labels: list[str]) -> str:
|
|
248
|
+
"""Always a draft; labels go on through the issues endpoint, best effort."""
|
|
249
|
+
got = self._gh(["api", f"repos/{_check(repo)}/pulls", "--method", "POST", "--input", "-"],
|
|
250
|
+
{"title": title, "body": body, "head": _check_branch(head), "base": base, "draft": True})
|
|
251
|
+
number = (got or {}).get("number")
|
|
252
|
+
if labels and isinstance(number, int):
|
|
253
|
+
with contextlib.suppress(CodeHostError):
|
|
254
|
+
self._gh(["api", f"repos/{_check(repo)}/issues/{number}/labels", "--method", "POST", "--input", "-"],
|
|
255
|
+
{"labels": labels})
|
|
256
|
+
return str((got or {}).get("html_url") or "")
|
|
257
|
+
|
|
258
|
+
def pull_state(self, repo: str, number: int) -> dict[str, Any]:
|
|
259
|
+
"""PRP-B26: one read-only GET of the pull request: `open`, `merged` or `closed` (without a merge), and the
|
|
260
|
+
merge time the host reports."""
|
|
261
|
+
got = self._read_pull(repo, number)
|
|
262
|
+
if not isinstance(got, dict):
|
|
263
|
+
raise CodeHostError("the pull request answer has no known shape")
|
|
264
|
+
merged_at = got.get("merged_at")
|
|
265
|
+
if got.get("merged") is True or (merged_at and got.get("state") == "closed"):
|
|
266
|
+
return {"state": "merged", "merged_at": str(merged_at) if merged_at else None}
|
|
267
|
+
state = got.get("state")
|
|
268
|
+
if state not in ("open", "closed"):
|
|
269
|
+
raise CodeHostError("the pull request answer has no known state")
|
|
270
|
+
return {"state": str(state), "merged_at": None}
|
|
271
|
+
|
|
272
|
+
def _paged(self, repo: str, number: int, part: str) -> list[dict[str, Any]]:
|
|
273
|
+
text = self._run(["api", "--method", "GET", f"repos/{_check(repo)}/pulls/{int(number)}/{part}",
|
|
274
|
+
"-f", "per_page=100", "--paginate", "--jq", ".[]"])
|
|
275
|
+
return _records(text)
|
|
276
|
+
|
|
277
|
+
def pull_reviews(self, repo: str, number: int) -> list[dict[str, Any]]:
|
|
278
|
+
"""One read-only GET: each review with its lower-case state and author kind; a pending review is left out."""
|
|
279
|
+
out: list[dict[str, Any]] = []
|
|
280
|
+
for r in self._paged(repo, number, "reviews"):
|
|
281
|
+
state = str(r.get("state") or "").lower()
|
|
282
|
+
if state == "pending":
|
|
283
|
+
continue
|
|
284
|
+
if state not in REVIEW_STATES:
|
|
285
|
+
raise CodeHostError("the review answer has no known state")
|
|
286
|
+
out.append({"state": state, "author_kind": _kind(r.get("user"), r.get("author_association")),
|
|
287
|
+
"text": str(r.get("body") or ""),
|
|
288
|
+
"submitted_at": str(r.get("submitted_at") or "")})
|
|
289
|
+
return out
|
|
290
|
+
|
|
291
|
+
def pull_comments(self, repo: str, number: int) -> list[dict[str, Any]]:
|
|
292
|
+
"""One read-only GET: each review comment with its author kind."""
|
|
293
|
+
return [{"author_kind": _kind(r.get("user"), r.get("author_association")), "text": str(r.get("body") or ""),
|
|
294
|
+
"path": str(r.get("path") or ""), "created_at": str(r.get("created_at") or "")}
|
|
295
|
+
for r in self._paged(repo, number, "comments")]
|
|
296
|
+
|
|
297
|
+
def _collaborator(self, repo: str, login: str) -> bool:
|
|
298
|
+
"""One read-only GET of the repository's collaborator check: no answer body is a yes, `HTTP 404` a no."""
|
|
299
|
+
try:
|
|
300
|
+
self._run(["api", "--method", "GET", f"repos/{_check(repo)}/collaborators/{quote(login, safe='')}"])
|
|
301
|
+
except NotFound:
|
|
302
|
+
return False
|
|
303
|
+
return True
|
|
304
|
+
|
|
305
|
+
def pull_commits(self, repo: str, number: int, after: str = "") -> list[dict[str, Any]]:
|
|
306
|
+
"""Each commit of the pull request with its author kind. One GET for the list, and one for each commit after
|
|
307
|
+
the commit `after` (a sha or its prefix) for its changed files; none when `after` is empty or not in the
|
|
308
|
+
list, and a commit up to `after` holds kind `other` and no files. A commit after `after` is a `person` only
|
|
309
|
+
with an account of type `User`, exactly one parent and a yes from the collaborator check (one GET for each
|
|
310
|
+
distinct login)."""
|
|
311
|
+
listed = self._paged(repo, number, "commits")
|
|
312
|
+
for r in listed:
|
|
313
|
+
sha = r.get("sha")
|
|
314
|
+
if not isinstance(sha, str) or not SHA.match(sha):
|
|
315
|
+
raise CodeHostError("the commit answer has no known sha")
|
|
316
|
+
cut = -1
|
|
317
|
+
if after:
|
|
318
|
+
for i, r in enumerate(listed):
|
|
319
|
+
sha = str(r["sha"])
|
|
320
|
+
if sha.startswith(after) or after.startswith(sha):
|
|
321
|
+
cut = i
|
|
322
|
+
break
|
|
323
|
+
standing: dict[str, bool] = {}
|
|
324
|
+
out: list[dict[str, Any]] = []
|
|
325
|
+
for i, r in enumerate(listed):
|
|
326
|
+
sha = str(r["sha"])
|
|
327
|
+
commit = r.get("commit") if isinstance(r.get("commit"), dict) else {}
|
|
328
|
+
when = (commit.get("committer") or {}).get("date") if isinstance(commit, dict) else None
|
|
329
|
+
kind, files = "other", []
|
|
330
|
+
if cut >= 0 and i > cut:
|
|
331
|
+
try:
|
|
332
|
+
one = self._gh(["api", "--method", "GET", f"repos/{_check(repo)}/commits/{sha}"])
|
|
333
|
+
except ValueError:
|
|
334
|
+
raise CodeHostError("the commit answer is not JSON") from None
|
|
335
|
+
if not isinstance(one, dict):
|
|
336
|
+
raise CodeHostError("the commit answer has no known shape")
|
|
337
|
+
files = [str(f.get("filename")) for f in one.get("files") or []
|
|
338
|
+
if isinstance(f, dict) and f.get("filename")]
|
|
339
|
+
author = r.get("author")
|
|
340
|
+
login = str(author.get("login") or "") if isinstance(author, dict) else ""
|
|
341
|
+
if not isinstance(author, dict) or not login:
|
|
342
|
+
kind = "other"
|
|
343
|
+
elif author.get("type") == "Bot" or login.endswith("[bot]"):
|
|
344
|
+
kind = "bot"
|
|
345
|
+
elif author.get("type") == "User" and len(r.get("parents") or []) == 1:
|
|
346
|
+
if login not in standing:
|
|
347
|
+
standing[login] = self._collaborator(repo, login)
|
|
348
|
+
kind = "person" if standing[login] else "other"
|
|
349
|
+
out.append({"sha": sha, "author_kind": kind, "files": files, "committed_at": str(when or "")})
|
|
350
|
+
return out
|
|
351
|
+
|
|
352
|
+
def _read_pull(self, repo: str, number: int) -> Any:
|
|
353
|
+
try:
|
|
354
|
+
return self._gh(["api", f"repos/{_check(repo)}/pulls/{int(number)}"])
|
|
355
|
+
except ValueError:
|
|
356
|
+
raise CodeHostError("the pull request answer is not JSON") from None
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
@dataclass(kw_only=True)
|
|
360
|
+
class MemoryCodeHost:
|
|
361
|
+
"""A code host in memory, for tests and dry runs."""
|
|
362
|
+
|
|
363
|
+
issues: list[dict[str, Any]] = field(default_factory=list)
|
|
364
|
+
comments: list[dict[str, Any]] = field(default_factory=list)
|
|
365
|
+
pulls: list[dict[str, Any]] = field(default_factory=list)
|
|
366
|
+
reviews: dict[tuple[str, int], list[dict[str, Any]]] = field(default_factory=dict)
|
|
367
|
+
review_comments: dict[tuple[str, int], list[dict[str, Any]]] = field(default_factory=dict)
|
|
368
|
+
commits: dict[tuple[str, int], list[dict[str, Any]]] = field(default_factory=dict)
|
|
369
|
+
files_asked: list[str] = field(default_factory=list)
|
|
370
|
+
fail_search: int = 0
|
|
371
|
+
fail_closed: int = 0
|
|
372
|
+
fail_issue: int = 0
|
|
373
|
+
fail_comments: int = 0
|
|
374
|
+
fail_open_issues: int = 0
|
|
375
|
+
thread: list[dict[str, Any]] = field(default_factory=list)
|
|
376
|
+
down: bool = False
|
|
377
|
+
clock: Callable[[], datetime] = lambda: datetime.now(UTC) # a test sets it; stamps `created_at` (ICAP-B4)
|
|
378
|
+
|
|
379
|
+
def add_comment(self, repo: str, number: int, body: str, author_kind: str, at: str) -> None:
|
|
380
|
+
"""Seeds a comment of a given author kind (`person`, `bot` or `other`) at an ISO time."""
|
|
381
|
+
self.thread.append({"repo": repo, "number": number, "text": body, "author_kind": author_kind, "created_at": at})
|
|
382
|
+
|
|
383
|
+
def _count(self, repo: str, number: int) -> int:
|
|
384
|
+
return sum(1 for c in self.thread if c["repo"] == repo and c["number"] == number)
|
|
385
|
+
|
|
386
|
+
def _find(self, repo: str, number: int) -> dict[str, Any]:
|
|
387
|
+
for i in self.issues:
|
|
388
|
+
if i["repo"] == repo and i["number"] == number:
|
|
389
|
+
return i
|
|
390
|
+
raise NotFound("HTTP 404")
|
|
391
|
+
|
|
392
|
+
def issue_comments(self, repo: str, number: int) -> list[dict[str, Any]]:
|
|
393
|
+
if self.down:
|
|
394
|
+
raise CodeHostError("unreachable")
|
|
395
|
+
if self.fail_comments:
|
|
396
|
+
self.fail_comments -= 1
|
|
397
|
+
raise CodeHostError("comments read failed")
|
|
398
|
+
self._find(repo, number)
|
|
399
|
+
return [{"text": c["text"], "author_kind": c["author_kind"], "created_at": c["created_at"]}
|
|
400
|
+
for c in self.thread if c["repo"] == repo and c["number"] == number]
|
|
401
|
+
|
|
402
|
+
def issue(self, repo: str, number: int) -> dict[str, Any]:
|
|
403
|
+
if self.down:
|
|
404
|
+
raise CodeHostError("unreachable")
|
|
405
|
+
if self.fail_issue:
|
|
406
|
+
self.fail_issue -= 1
|
|
407
|
+
raise CodeHostError("issue read failed")
|
|
408
|
+
i = self._find(repo, number)
|
|
409
|
+
return {"number": i["number"], "state": i["state"], "state_reason": str(i.get("state_reason") or "").lower(),
|
|
410
|
+
"closed_at": i.get("closed_at") or "", "url": i["url"], "comments": self._count(repo, number),
|
|
411
|
+
"is_pull_request": bool(i.get("pull_request"))}
|
|
412
|
+
|
|
413
|
+
def open_issues(self, repo: str) -> list[dict[str, Any]]:
|
|
414
|
+
"""Open issues that are no pull request and lack the loop's label (an issue with no `labels` key is a loop
|
|
415
|
+
issue, as in `loop_issues`); `fail_open_issues` fails reads on demand."""
|
|
416
|
+
if self.down:
|
|
417
|
+
raise CodeHostError("unreachable")
|
|
418
|
+
if self.fail_open_issues:
|
|
419
|
+
self.fail_open_issues -= 1
|
|
420
|
+
raise CodeHostError("open issues read failed")
|
|
421
|
+
return [{"number": i["number"], "title": str(i.get("title") or ""), "body": str(i.get("body") or ""),
|
|
422
|
+
"author_kind": str(i.get("author_kind") or "person"), "comments": self._count(repo, i["number"])}
|
|
423
|
+
for i in self.issues if i["repo"] == repo and i["state"] == "open" and not i.get("pull_request")
|
|
424
|
+
and LOOP_LABEL not in i.get("labels", [LOOP_LABEL])]
|
|
425
|
+
|
|
426
|
+
def pull_reviews(self, repo: str, number: int) -> list[dict[str, Any]]:
|
|
427
|
+
if self.down:
|
|
428
|
+
raise CodeHostError("unreachable")
|
|
429
|
+
return list(self.reviews.get((repo, number), []))
|
|
430
|
+
|
|
431
|
+
def pull_comments(self, repo: str, number: int) -> list[dict[str, Any]]:
|
|
432
|
+
if self.down:
|
|
433
|
+
raise CodeHostError("unreachable")
|
|
434
|
+
return list(self.review_comments.get((repo, number), []))
|
|
435
|
+
|
|
436
|
+
def pull_commits(self, repo: str, number: int, after: str = "") -> list[dict[str, Any]]:
|
|
437
|
+
"""The commits given, with `files` emptied for each commit up to and including `after` (for all when `after`
|
|
438
|
+
is empty or not among them); the sha of each commit after it is added to `files_asked`."""
|
|
439
|
+
if self.down:
|
|
440
|
+
raise CodeHostError("unreachable")
|
|
441
|
+
given = [dict(c) for c in self.commits.get((repo, number), [])]
|
|
442
|
+
cut = -1
|
|
443
|
+
if after:
|
|
444
|
+
for i, c in enumerate(given):
|
|
445
|
+
sha = str(c.get("sha") or "")
|
|
446
|
+
if sha and (sha.startswith(after) or after.startswith(sha)):
|
|
447
|
+
cut = i
|
|
448
|
+
break
|
|
449
|
+
for i, c in enumerate(given):
|
|
450
|
+
if cut >= 0 and i > cut:
|
|
451
|
+
self.files_asked.append(str(c.get("sha") or ""))
|
|
452
|
+
else:
|
|
453
|
+
c["files"] = []
|
|
454
|
+
return given
|
|
455
|
+
|
|
456
|
+
def loop_issues(self, repo: str, state: str) -> list[dict[str, Any]]:
|
|
457
|
+
"""Issues in `state` with the loop's label; `fail_search` fails open reads, `fail_closed` closed ones."""
|
|
458
|
+
if self.down:
|
|
459
|
+
raise CodeHostError("unreachable")
|
|
460
|
+
if state == "open" and self.fail_search:
|
|
461
|
+
self.fail_search -= 1
|
|
462
|
+
raise CodeHostError("search failed")
|
|
463
|
+
if state == "closed" and self.fail_closed:
|
|
464
|
+
self.fail_closed -= 1
|
|
465
|
+
raise CodeHostError("closed search failed")
|
|
466
|
+
return [{"number": i["number"], "url": i["url"], "body": i["body"], "state_reason": i.get("state_reason") or "",
|
|
467
|
+
"closed_at": i.get("closed_at") or "", "created_at": i.get("created_at") or "",
|
|
468
|
+
"comments": self._count(repo, i["number"])}
|
|
469
|
+
for i in self.issues if i["repo"] == repo and i["state"] == state
|
|
470
|
+
and LOOP_LABEL in (i.get("labels") or [LOOP_LABEL])]
|
|
471
|
+
|
|
472
|
+
def close(self, repo: str, number: int, reason: str, at: str) -> None:
|
|
473
|
+
"""Closes an issue with a reason (`not_planned`, `completed`, `duplicate` or empty) at an ISO time."""
|
|
474
|
+
for i in self.issues:
|
|
475
|
+
if i["repo"] == repo and i["number"] == number:
|
|
476
|
+
i.update(state="closed", state_reason=reason, closed_at=at)
|
|
477
|
+
|
|
478
|
+
def create(self, repo: str, title: str, body: str, labels: list[str]) -> str:
|
|
479
|
+
if self.down:
|
|
480
|
+
raise CodeHostError("unreachable")
|
|
481
|
+
n = len(self.issues) + 1
|
|
482
|
+
self.issues.append({"repo": _check(repo), "number": n, "title": title, "body": body, "labels": labels,
|
|
483
|
+
"state": "open", "url": f"https://example.test/{repo}/issues/{n}",
|
|
484
|
+
"created_at": self.clock().astimezone(UTC).isoformat()})
|
|
485
|
+
return self.issues[-1]["url"]
|
|
486
|
+
|
|
487
|
+
def comment(self, repo: str, number: int, body: str) -> str:
|
|
488
|
+
if self.down:
|
|
489
|
+
raise CodeHostError("unreachable")
|
|
490
|
+
self.comments.append({"repo": repo, "number": number, "body": body})
|
|
491
|
+
self.add_comment(repo, number, body, "other", "")
|
|
492
|
+
return f"https://example.test/{repo}/issues/{number}#c{len(self.comments)}"
|
|
493
|
+
|
|
494
|
+
def reopen(self, repo: str, number: int) -> None:
|
|
495
|
+
if self.down:
|
|
496
|
+
raise CodeHostError("unreachable")
|
|
497
|
+
for i in self.issues:
|
|
498
|
+
if i["repo"] == repo and i["number"] == number:
|
|
499
|
+
i.update(state="open", state_reason=None, closed_at=None)
|
|
500
|
+
|
|
501
|
+
def default_branch(self, repo: str) -> str:
|
|
502
|
+
if self.down:
|
|
503
|
+
raise CodeHostError("unreachable")
|
|
504
|
+
return "main"
|
|
505
|
+
|
|
506
|
+
def create_draft_pr(self, repo: str, head: str, base: str, title: str, body: str, labels: list[str]) -> str:
|
|
507
|
+
if self.down:
|
|
508
|
+
raise CodeHostError("unreachable")
|
|
509
|
+
n = len(self.pulls) + 1
|
|
510
|
+
self.pulls.append({"repo": _check(repo), "number": n, "head": _check_branch(head), "base": base,
|
|
511
|
+
"title": title, "body": body, "labels": labels, "draft": True, "state": "open"})
|
|
512
|
+
return f"https://example.test/{repo}/pull/{n}"
|
|
513
|
+
|
|
514
|
+
def pull_state(self, repo: str, number: int) -> dict[str, Any]:
|
|
515
|
+
if self.down:
|
|
516
|
+
raise CodeHostError("unreachable")
|
|
517
|
+
for p in self.pulls:
|
|
518
|
+
if p["repo"] == repo and p["number"] == number:
|
|
519
|
+
return {"state": p["state"], "merged_at": p.get("merged_at")}
|
|
520
|
+
raise CodeHostError("no such pull request")
|