readthrough 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. readthrough/__init__.py +8 -0
  2. readthrough/__main__.py +3 -0
  3. readthrough/agents.py +344 -0
  4. readthrough/analyze.py +537 -0
  5. readthrough/assets/SKILL.md +86 -0
  6. readthrough/assets/defaults.toml +143 -0
  7. readthrough/assets/profile-reference.md +133 -0
  8. readthrough/assets/vendor/README.md +22 -0
  9. readthrough/assets/vendor/cose-base.js +3214 -0
  10. readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
  11. readthrough/assets/vendor/cytoscape.min.js +31 -0
  12. readthrough/assets/vendor/layout-base.js +5230 -0
  13. readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
  14. readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
  15. readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
  16. readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
  17. readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
  18. readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
  19. readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
  20. readthrough/assets/vendor/lucide-icons.js +36 -0
  21. readthrough/assets/vendor/marked.umd.js +82 -0
  22. readthrough/assets/vendor/purify.min.js +7 -0
  23. readthrough/assets/web/dashboard.css +202 -0
  24. readthrough/assets/web/dashboard.html +48 -0
  25. readthrough/assets/web/dashboard.js +937 -0
  26. readthrough/assets/web/setup.css +57 -0
  27. readthrough/assets/web/setup.html +28 -0
  28. readthrough/assets/web/setup.js +342 -0
  29. readthrough/assets/web/theme.css +36 -0
  30. readthrough/assistants.py +699 -0
  31. readthrough/brief.py +145 -0
  32. readthrough/build.py +616 -0
  33. readthrough/ci.py +107 -0
  34. readthrough/cli.py +958 -0
  35. readthrough/config.py +533 -0
  36. readthrough/contract.py +394 -0
  37. readthrough/engine.py +230 -0
  38. readthrough/faults.py +92 -0
  39. readthrough/files.py +110 -0
  40. readthrough/forges/__init__.py +614 -0
  41. readthrough/forges/azure_devops.py +658 -0
  42. readthrough/forges/forgejo.py +300 -0
  43. readthrough/forges/github.py +487 -0
  44. readthrough/forges/gitlab.py +335 -0
  45. readthrough/ledger.py +61 -0
  46. readthrough/limits.py +26 -0
  47. readthrough/logs.py +169 -0
  48. readthrough/membership.py +76 -0
  49. readthrough/model.py +177 -0
  50. readthrough/onboard.py +551 -0
  51. readthrough/onboard_model.py +319 -0
  52. readthrough/process.py +169 -0
  53. readthrough/profile.py +699 -0
  54. readthrough/py.typed +0 -0
  55. readthrough/registry.py +157 -0
  56. readthrough/review.py +394 -0
  57. readthrough/rules.py +111 -0
  58. readthrough/runtimes/__init__.py +297 -0
  59. readthrough/runtimes/anthropic.py +278 -0
  60. readthrough/runtimes/copilot.py +313 -0
  61. readthrough/runtimes/openai.py +307 -0
  62. readthrough/serve.py +817 -0
  63. readthrough/study.py +327 -0
  64. readthrough/system.py +205 -0
  65. readthrough/terminals.py +168 -0
  66. readthrough/tuning.py +266 -0
  67. readthrough/usage.py +169 -0
  68. readthrough/web_setup.py +635 -0
  69. readthrough-0.4.0.dist-info/METADATA +123 -0
  70. readthrough-0.4.0.dist-info/RECORD +73 -0
  71. readthrough-0.4.0.dist-info/WHEEL +4 -0
  72. readthrough-0.4.0.dist-info/entry_points.txt +2 -0
  73. readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,319 @@
1
+ """Model-assisted onboarding: a model reads the repo and proposes a profile.
2
+
3
+ The conversation runs on the configured model runtime (``runtime`` in config.toml: the Copilot SDK, Anthropic,
4
+ or OpenAI; see ``runtimes/``) with read-only tools over the repo and one tool to propose a profile. Each
5
+ proposal is validated and measured with the same checks ``readthrough onboard --accept`` uses, and the
6
+ result goes back to the model so it can fix problems. The best proposal wins; you still review it before
7
+ accepting, and the profile says a model drafted it, and which.
8
+ """
9
+
10
+ # No `from __future__ import annotations`: the Copilot SDK reads tool parameter types at runtime.
11
+
12
+ import asyncio
13
+ import logging
14
+ import tomllib
15
+ import uuid
16
+ from collections import Counter
17
+ from collections.abc import Callable
18
+ from importlib.resources import files
19
+ from typing import Any
20
+
21
+ from readthrough import runtimes
22
+ from readthrough.config import Config
23
+ from readthrough.files import inside
24
+ from readthrough.forges import Forge
25
+ from readthrough.onboard import RepoFacts, author_table, check_profile_text, draft_profile, measure, report
26
+ from readthrough.process import run
27
+ from readthrough.profile import ProfileError, parse_profile
28
+ from readthrough.rules import glob_to_regex
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ MODEL_DRAFTER = "model" # the drafted_by a model's draft carries (profile.DRAFTERS); the header names the model
33
+
34
+
35
+ SYSTEM_MESSAGE = """\
36
+ You are drafting an architecture profile for {repo}. readthrough uses it to place each open pull request
37
+ on the repo's architecture, tell reviewers which component owns what, and ask them good questions.
38
+
39
+ How to work:
40
+ - Start from the heuristic draft you're given. Its directory-based components are a starting point,
41
+ not the answer: find the real boundaries (packages, layers, plugin families, entry points) by
42
+ reading the code and docs with your tools.
43
+ - Aim for 6 to 20 components a newcomer would recognise, grouped into 3 to 6 layers ordered from
44
+ entry points down to shared foundations, plus a support layer for tests, docs, and infra.
45
+ - For each source component, write `responsibility` and `does_not_own` only when the code or docs
46
+ back them up. `does_not_own` should name the neighbouring component that owns each thing. If you
47
+ aren't sure, leave both out; a wrong contract is worse than none.
48
+ - If the repo has an architecture doc with one section per component, point [contracts] at it and set
49
+ each component's `contract` to its heading instead of writing responsibilities inline.
50
+ - Add a few [[signals]] for risky paths you can see (migrations, auth, public API, dependency
51
+ manifests, CI config) and [review] guidance distilled from the contributing docs.
52
+ - Keep an [authors] section. Fill internal_teams or internal_orgs only if the docs or CODEOWNERS
53
+ make the maintainer group obvious; otherwise leave it empty.
54
+ - Call propose_profile with the complete TOML. It replies with coverage and problems. Fix them and
55
+ propose again until there are no problems. Stop after that; don't polish forever.
56
+ - Finish with 3 to 6 short lines: what you based the map on, and what the maintainer should check.
57
+ - You can't edit files or run commands. The tools listed are everything you have.
58
+ """
59
+
60
+
61
+ def model_draft(
62
+ cfg: Config, forge: Forge | None, facts: RepoFacts, *, on_progress: Callable[[str], None] = log.info
63
+ ) -> str:
64
+ """Run a drafting conversation on the configured runtime and return the best profile it proposed (TOML)."""
65
+ _, ok, why = runtimes.resolve(cfg.runtime, cfg.runtime_options)
66
+ if not ok:
67
+ raise RuntimeError(f"--assisted needs a model runtime: {why}.")
68
+ drafter = _Drafter(cfg, forge, facts, on_progress)
69
+ asyncio.run(drafter.run())
70
+ if drafter.best is None:
71
+ raise RuntimeError(
72
+ "The model didn't propose a valid profile. Try again, or start from the plain draft (--update)."
73
+ )
74
+ problems, share, text = drafter.best
75
+ on_progress(f"Best proposal: {share:.0%} coverage, {len(problems)} problem(s) left")
76
+ if drafter.summary:
77
+ on_progress("The model's notes:\n" + drafter.summary.strip())
78
+ who = (
79
+ f"{drafter.model} ({drafter.runtime_name} runtime)" if drafter.model else f"the {drafter.runtime_name} runtime"
80
+ )
81
+ header = f"# Drafted with {who} by `readthrough onboard {facts.repo} --assisted`. Review it before accepting.\n"
82
+ return header + mark_drafter(text.lstrip(), MODEL_DRAFTER)
83
+
84
+
85
+ def mark_drafter(text: str, drafter: str) -> str:
86
+ """Set the profile's top-level ``drafted_by`` (it must sit before the first table header)."""
87
+ lines = [line for line in text.splitlines() if not line.startswith("drafted_by")]
88
+ at = next((i + 1 for i, line in enumerate(lines) if line.startswith("schema")), 0)
89
+ lines.insert(at, f'drafted_by = "{drafter}"')
90
+ return "\n".join(lines) + "\n"
91
+
92
+
93
+ class _Drafter:
94
+ def __init__(self, cfg: Config, forge: Forge | None, facts: RepoFacts, on_progress: Callable[[str], None]) -> None:
95
+ self.cfg, self.forge, self.facts, self.say = cfg, forge, facts, on_progress
96
+ self.tree = set(facts.tree)
97
+ self.clone = cfg.clone if cfg.clone and (cfg.clone / ".git").exists() else None
98
+ self.best: tuple[list[str], float, str] | None = None
99
+ self.proposals = 0
100
+ self.summary = ""
101
+ self.runtime_name = ""
102
+ self.model: str | None = None # the model the runtime reported using, for the profile's header
103
+
104
+ # ---- the session
105
+
106
+ async def run(self) -> None:
107
+ runtime = runtimes.make(self.cfg.runtime, self.cfg.runtime_options)
108
+ self.runtime_name = runtime.name
109
+ try:
110
+ conversation = runtimes.Conversation(
111
+ key=f"readthrough:onboarding:{uuid.uuid4()}",
112
+ system=SYSTEM_MESSAGE.format(repo=self.facts.repo),
113
+ tools=self._tools(),
114
+ working_directory=str(self.clone or self.cfg.home),
115
+ model=self.cfg.study_model,
116
+ resume=False,
117
+ )
118
+ session = await runtime.open(conversation)
119
+ try:
120
+ self.summary = await self._send(session, self._first_prompt())
121
+ finally:
122
+ await session.close()
123
+ finally:
124
+ await runtime.stop()
125
+
126
+ def _record_usage(self, used: runtimes.Usage) -> None:
127
+ from readthrough.assistants import record_usage
128
+
129
+ self.model = used.model or self.model
130
+ try:
131
+ record_usage(self.cfg, used, purpose="draft", ref="onboarding", by=MODEL_DRAFTER)
132
+ except Exception:
133
+ log.exception("Couldn't record model usage for the onboarding draft")
134
+
135
+ async def _send(self, session: runtimes.Session, prompt: str) -> str:
136
+ final = ""
137
+ error: str | None = None
138
+
139
+ async def consume() -> None:
140
+ nonlocal final, error
141
+ async for event in session.send(prompt):
142
+ if event.kind == "usage" and event.usage is not None:
143
+ self._record_usage(event.usage)
144
+ elif event.kind == "tool" and event.name != "propose_profile":
145
+ self.say(f"model: {event.name.replace('_', ' ')}")
146
+ elif event.kind == "error":
147
+ error = event.text
148
+ elif event.kind == "done":
149
+ final = event.text
150
+
151
+ await asyncio.wait_for(consume(), timeout=self.cfg.tuning.study.onboarding_turn_timeout_seconds)
152
+ if error and self.best is None:
153
+ raise RuntimeError(error)
154
+ return final
155
+
156
+ def _first_prompt(self) -> str:
157
+ f = self.facts
158
+ reference = files("readthrough").joinpath("assets/profile-reference.md").read_text(encoding="utf-8")
159
+ draft = draft_profile(f)
160
+ profile = parse_profile(tomllib.loads(draft), origin="heuristic draft")
161
+ cov = measure(profile, f, raw=tomllib.loads(draft))
162
+ docs = "\n\n".join(
163
+ f"<doc path={p!r}>\n{text[: self.cfg.tuning.study.onboarding_doc_excerpt_chars]}\n</doc>"
164
+ for p, text in f.docs.items()
165
+ if text
166
+ )
167
+ owners = "\n".join(f"{glob} {' '.join(o)}" for glob, o in f.codeowners[:60]) or "(no CODEOWNERS)"
168
+ parts = [
169
+ f"Draft the architecture profile for {f.repo} (default branch {f.default_branch}).",
170
+ f"<profile_reference>\n{reference}\n</profile_reference>",
171
+ f"<top_directories>\n{self._dirs('', 2)}\n</top_directories>",
172
+ f"<codeowners>\n{owners}\n</codeowners>",
173
+ f"<docs>\n{docs or '(no architecture or contributing docs found)'}\n</docs>",
174
+ f"<recent_authors>\n{self._authors(profile)}\n</recent_authors>",
175
+ f"<heuristic_draft>\n{draft}\n</heuristic_draft>",
176
+ f"<heuristic_draft_check>\n{report(cov, profile, [])}\n</heuristic_draft_check>",
177
+ ""
178
+ if self.clone
179
+ else "There's no local clone, so search_code isn't available; read_file works through the API.",
180
+ ]
181
+ return "\n\n".join(p for p in parts if p)
182
+
183
+ # ---- helpers behind the tools
184
+
185
+ def _dirs(self, prefix: str, depth: int) -> str:
186
+ prefix = prefix.strip("/")
187
+ base = prefix.count("/") + 1 if prefix else 0
188
+ counts: Counter[str] = Counter()
189
+ churn: Counter[str] = Counter()
190
+ for path in self.facts.tree:
191
+ if prefix and not path.startswith(prefix + "/"):
192
+ continue
193
+ parts = path.split("/")
194
+ key = "/".join(parts[: base + depth]) + ("/" if len(parts) > base + depth else "")
195
+ counts[key] += 1
196
+ churn[key] += self.facts.churn.get(path, 0)
197
+ rows = [f"{k} files={counts[k]} recent_churn={churn[k]}" for k in sorted(counts)]
198
+ if len(rows) > 400:
199
+ rows = [*rows[:400], f"... {len(rows) - 400} more; list a narrower prefix"]
200
+ return "\n".join(rows) or f"Nothing under {prefix!r}"
201
+
202
+ def _authors(self, profile: Any) -> str:
203
+ rows = author_table(profile, self.facts)
204
+ return "\n".join(f"{login} association={assoc} kind={kind} prs={n}" for login, assoc, kind, n in rows[:60])
205
+
206
+ def _read(self, path: str, start: int, end: int) -> str:
207
+ path = path.strip().lstrip("/")
208
+ if path not in self.tree:
209
+ return f"{path} isn't a file in the repo. Use list_directory to find paths."
210
+ if self.clone:
211
+ # Being in the tree is not enough: a committed symlink can point anywhere on this machine.
212
+ try:
213
+ target = inside(self.clone, path)
214
+ except ValueError:
215
+ return f"{path} points outside the clone and can't be read."
216
+ text = target.read_text(encoding="utf-8", errors="replace")
217
+ elif self.forge is not None:
218
+ text = self.forge.read_file(path) or ""
219
+ else:
220
+ return "read_file needs a local clone or forge access."
221
+ lines = text.splitlines()
222
+ end = min(end, start + 399, len(lines))
223
+ body = "\n".join(f"{i:>5} {lines[i - 1]}" for i in range(start, end + 1))
224
+ return f"{path} lines {start}-{end} of {len(lines)}\n{body}"
225
+
226
+ def _search(self, pattern: str, path_glob: str | None) -> str:
227
+ if not self.clone:
228
+ return "search_code needs a local clone; use read_file and list_directory instead."
229
+ cmd = ["git", "-C", str(self.clone), "grep", "-n", "-I", "-E", "--max-count=20", "-e", pattern]
230
+ if path_glob:
231
+ cmd += ["--", path_glob]
232
+ return _clip(run(cmd, check=False), limit=self.cfg.tuning.study.onboarding_tool_output_chars) or "No matches."
233
+
234
+ def _propose(self, text: str) -> str:
235
+ self.proposals += 1
236
+ try:
237
+ profile, cov = check_profile_text(text, self.facts, origin="proposal")
238
+ except (ProfileError, tomllib.TOMLDecodeError) as exc:
239
+ self.say(f"Proposal {self.proposals}: invalid ({str(exc)[:120]})")
240
+ return f"Invalid profile: {exc}\nFix it and propose again."
241
+ if profile.repo.lower() != self.facts.repo.lower():
242
+ return f"repo must be {self.facts.repo!r}."
243
+ problems = cov.problems()
244
+ self.say(f"Proposal {self.proposals}: {cov.share:.0%} coverage, {len(problems)} problem(s)")
245
+ key = (len(problems), -cov.share)
246
+ if self.best is None or key < (len(self.best[0]), -self.best[1]):
247
+ self.best = (problems, cov.share, text)
248
+ verdict = (
249
+ "No problems: this is good enough to accept. Stop and summarise."
250
+ if not problems
251
+ else "Fix these and propose again."
252
+ )
253
+ return report(cov, profile, author_table(profile, self.facts)) + "\n\n" + verdict
254
+
255
+ # ---- tools
256
+
257
+ def _tools(self) -> list[runtimes.ToolSpec]:
258
+ drafter = self
259
+
260
+ async def list_directory(args: dict[str, Any]) -> str:
261
+ return drafter._dirs(args.get("prefix") or "", int(args.get("depth") or 2))
262
+
263
+ async def read_file(args: dict[str, Any]) -> str:
264
+ return await asyncio.to_thread(
265
+ drafter._read, args["path"], int(args.get("start_line") or 1), int(args.get("end_line") or 200)
266
+ )
267
+
268
+ async def search_code(args: dict[str, Any]) -> str:
269
+ return await asyncio.to_thread(drafter._search, args["pattern"], args.get("path_glob"))
270
+
271
+ async def match_glob(args: dict[str, Any]) -> str:
272
+ rx = glob_to_regex(args["glob"])
273
+ hits = [p for p in drafter.facts.tree if rx.match(p)]
274
+ churn = sum(drafter.facts.churn.get(p, 0) for p in hits)
275
+ return (
276
+ f"{len(hits)} files, recent churn {churn}\n"
277
+ + "\n".join(hits[:40])
278
+ + ("\n..." if len(hits) > 40 else "")
279
+ )
280
+
281
+ async def propose_profile(args: dict[str, Any]) -> str:
282
+ return drafter._propose(args["toml"])
283
+
284
+ s = runtimes.ToolSpec
285
+ return [
286
+ s("list_directory", "Directories and files with file counts and recent PR churn.", {
287
+ "properties": {
288
+ "prefix": {"type": "string", "description": "Directory to list, e.g. 'src/app'. Empty for the repo root.", "default": ""},
289
+ "depth": {"type": "integer", "minimum": 1, "maximum": 4, "description": "How many levels below the prefix to show", "default": 2},
290
+ },
291
+ }, list_directory),
292
+ s("read_file", "Read lines of a file on the default branch. Lines are numbered.", {
293
+ "properties": {
294
+ "path": {"type": "string", "description": "Repo-relative file path"},
295
+ "start_line": {"type": "integer", "minimum": 1, "default": 1},
296
+ "end_line": {"type": "integer", "minimum": 1, "default": 200},
297
+ },
298
+ "required": ["path"],
299
+ }, read_file),
300
+ s("search_code", "git grep the repo. Returns path:line:text matches.", {
301
+ "properties": {
302
+ "pattern": {"type": "string", "description": "Extended regex for git grep -E"},
303
+ "path_glob": {"type": "string", "description": "Optional pathspec, e.g. 'src/**/*.py'"},
304
+ },
305
+ "required": ["pattern"],
306
+ }, search_code),
307
+ s("match_glob", "Which repo files a profile glob matches, and their recent churn.", {
308
+ "properties": {"glob": {"type": "string", "description": "A profile path glob, e.g. 'src/app/score/**'"}},
309
+ "required": ["glob"],
310
+ }, match_glob),
311
+ s("propose_profile", "Validate and measure a complete profile. Returns coverage and problems.", {
312
+ "properties": {"toml": {"type": "string", "description": "The complete profile as TOML"}},
313
+ "required": ["toml"],
314
+ }, propose_profile),
315
+ ] # fmt: skip
316
+
317
+
318
+ def _clip(text: str, *, limit: int) -> str:
319
+ return text if len(text) <= limit else text[:limit] + f"\n... [truncated {len(text) - limit} characters]"
readthrough/process.py ADDED
@@ -0,0 +1,169 @@
1
+ """Running other programs (``gh``, ``glab``, ``az``, ``git``) and keeping their secrets out of sight.
2
+
3
+ Every outside program goes through ``run`` with an argument list, never a shell string. Programs are
4
+ resolved with ``shutil.which`` so ``.cmd`` shims and wrappers are found on Windows, output is decoded as
5
+ UTF-8, every call has a timeout, and failures come back as classified ``ForgeError``s. ``READTHROUGH_GH``
6
+ (or ``READTHROUGH_GIT``, ...) substitutes a program; the tests use that to stand in for ``gh``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import logging
13
+ import os
14
+ import re
15
+ import secrets
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import threading
20
+ import time
21
+ from pathlib import Path
22
+ from typing import Any, Literal, overload
23
+
24
+ from readthrough.faults import ForgeError, Timeout, classify_stderr
25
+ from readthrough.tuning import default_tuning
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ # Keep child consoles from flashing when we run windowless (scheduled task, URL handler).
30
+ NO_WINDOW = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
31
+ FORGE_CLIS = ("gh", "glab", "az") # their stderr is classified; anything else is a plain error
32
+
33
+
34
+ class Secret:
35
+ """A value that must never appear in logs, errors, or bundles. Only ``reveal()`` gives it back."""
36
+
37
+ __slots__ = ("_value",)
38
+
39
+ def __init__(self, value: str) -> None:
40
+ self._value = value
41
+
42
+ def reveal(self) -> str:
43
+ return self._value
44
+
45
+ def __repr__(self) -> str:
46
+ return "Secret(***)"
47
+
48
+ __str__ = __repr__
49
+
50
+ def __eq__(self, other: object) -> bool:
51
+ return isinstance(other, Secret) and secrets.compare_digest(self._value, other._value)
52
+
53
+ def __hash__(self) -> int:
54
+ return hash(self._value)
55
+
56
+
57
+ _seen_secrets: list[Secret] = []
58
+ _secrets_lock = threading.Lock()
59
+
60
+
61
+ def remember(secret: Secret) -> Secret:
62
+ """Register a secret so ``redact`` can blank it out of anything we log or raise."""
63
+ with _secrets_lock:
64
+ if secret not in _seen_secrets:
65
+ _seen_secrets.append(secret)
66
+ return secret
67
+
68
+
69
+ def redact(text: str) -> str:
70
+ """Blank out every secret this process has seen, in case a program echoed one into an error."""
71
+ with _secrets_lock:
72
+ values = [s.reveal() for s in _seen_secrets]
73
+ for value in values:
74
+ if value:
75
+ text = text.replace(value, "***")
76
+ return text
77
+
78
+
79
+ def which(program: str) -> list[str]:
80
+ """How to invoke ``program``: its resolved path, or the command ``READTHROUGH_<PROGRAM>`` names.
81
+
82
+ The override is a path, or a JSON list for a command with arguments (``["python", "fake_gh.py"]``).
83
+ Unknown programs are returned as given, so the failure is reported where they're run.
84
+ """
85
+ override = os.environ.get(f"READTHROUGH_{program.upper()}")
86
+ if override:
87
+ return json.loads(override) if override.startswith("[") else [override]
88
+ return [shutil.which(program) or program]
89
+
90
+
91
+ def installed(program: str) -> bool:
92
+ return bool(os.environ.get(f"READTHROUGH_{program.upper()}") or shutil.which(program))
93
+
94
+
95
+ def describe(cmd: list[str]) -> str:
96
+ """A short, readable name for a command: `graphql PullRequests`, `GET repos/o/r/branches/main`, `pr diff #12`."""
97
+ if cmd[:3] == ["gh", "api", "graphql"]:
98
+ query = next((a[6:] for a in cmd if a.startswith("query=")), "")
99
+ name = re.search(r"query\s+(\w+)", query)
100
+ number = next((a.split("=", 1)[1] for a in cmd if a.startswith("number=")), "")
101
+ return f"graphql {name.group(1) if name else 'query'}{' #' + number if number else ''}"
102
+ if cmd[:2] in (["gh", "api"], ["glab", "api"]):
103
+ method = cmd[cmd.index("-X") + 1] if "-X" in cmd else "GET"
104
+ path = next((a for a in reversed(cmd[2:]) if not a.startswith("-") and ":" not in a), "?")
105
+ return f"{method} {path}"
106
+ if cmd[:3] == ["gh", "pr", "diff"]:
107
+ return f"pr diff #{cmd[3]}"
108
+ return " ".join(cmd[:4])
109
+
110
+
111
+ def run(
112
+ cmd: list[str], *, check: bool = True, cwd: Path | None = None, env: dict[str, str] | None = None,
113
+ timeout: float | None = None,
114
+ ) -> str: # fmt: skip
115
+ """Run a command and return its output. Failures raise a classified ``ForgeError`` (when ``check``)."""
116
+ what = describe(cmd)
117
+ if timeout is None:
118
+ timeout = (default_tuning().forge if cmd[0] in FORGE_CLIS else default_tuning().git).timeout_seconds
119
+ started = time.monotonic()
120
+ try:
121
+ proc = subprocess.run(
122
+ [*which(cmd[0]), *cmd[1:]], capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=cwd,
123
+ creationflags=NO_WINDOW, env={**os.environ, **env} if env else None, timeout=timeout, check=False,
124
+ ) # fmt: skip
125
+ except subprocess.TimeoutExpired as exc:
126
+ log.debug("%s: timed out after %.0fs", what, timeout)
127
+ raise Timeout(
128
+ f"{what} timed out after {timeout:.0f}s", what=what, stderr=f"timed out after {timeout:.0f}s"
129
+ ) from exc
130
+ except FileNotFoundError as exc:
131
+ raise ForgeError(f"{cmd[0]} isn't installed or isn't on PATH", what=what) from exc
132
+ took = time.monotonic() - started
133
+ log.debug("%s: exit %d in %.2fs", what, proc.returncode, took)
134
+ if check and proc.returncode != 0:
135
+ stderr = redact(proc.stderr.strip())
136
+ cls = classify_stderr(stderr) if cmd[0] in FORGE_CLIS else ForgeError
137
+ first = next((line.strip() for line in stderr.splitlines() if line.strip()), f"exit code {proc.returncode}")
138
+ raise cls(f"{what} failed: {first[:300]}", what=what, stderr=stderr[:4000], returncode=proc.returncode)
139
+ return proc.stdout
140
+
141
+
142
+ @overload
143
+ def quiet_output(cmd: list[str], *, with_stderr: bool = False) -> str | None: ...
144
+ @overload
145
+ def quiet_output(
146
+ cmd: list[str], *, with_stderr: bool = False, with_failure: Literal[True]
147
+ ) -> tuple[str | None, str]: ...
148
+
149
+
150
+ def quiet_output(cmd: list[str], *, with_stderr: bool = False, with_failure: bool = False) -> Any:
151
+ """A program's stdout, or None if it isn't installed or failed. For looking things up (tokens, sign-ins).
152
+
153
+ ``with_stderr`` appends what the program wrote to stderr: ``glab auth status`` reports there, not to stdout.
154
+ ``with_failure`` returns ``(stdout or None, why)`` instead, where ``why`` is the redacted stderr of a
155
+ failed run (or what kept it from running), for telling the user what the program said.
156
+ """
157
+ try:
158
+ proc = subprocess.run(
159
+ [*which(cmd[0]), *cmd[1:]], capture_output=True, text=True, encoding="utf-8", errors="replace",
160
+ creationflags=NO_WINDOW, check=False, timeout=default_tuning().forge.timeout_seconds,
161
+ ) # fmt: skip
162
+ except FileNotFoundError:
163
+ return (None, f"{cmd[0]} isn't installed or isn't on PATH") if with_failure else None
164
+ except subprocess.TimeoutExpired:
165
+ return (None, f"{cmd[0]} didn't answer in time") if with_failure else None
166
+ if proc.returncode != 0:
167
+ return (None, redact(proc.stderr.strip())) if with_failure else None
168
+ out = proc.stdout + ("\n" + proc.stderr if with_stderr and proc.stderr else "")
169
+ return (out, "") if with_failure else out