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.
Files changed (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. 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")