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
readthrough/py.typed ADDED
File without changes
@@ -0,0 +1,157 @@
1
+ """Registries for the parts a user picks between: terminal launchers, study assistants, profile sources.
2
+
3
+ A plugin is a name, a one-line summary, an implementation, and a dataclass of options. The options a
4
+ user writes in ``config.toml`` (``[terminals.wt]``, say) are checked against that dataclass, so a typo in
5
+ an option name or a value of the wrong type is refused with a suggestion instead of being ignored. The
6
+ same goes for the plugin name itself.
7
+
8
+ Nothing here knows what a terminal or an assistant is; see ``terminals.py``, ``assistants.py``, and the
9
+ profile finders in ``profile.py``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import difflib
15
+ import types
16
+ from collections.abc import Callable, Iterator, Mapping
17
+ from dataclasses import dataclass, fields, is_dataclass
18
+ from pathlib import Path
19
+ from typing import Any, Generic, TypeVar, cast, get_args, get_origin, get_type_hints
20
+
21
+ T = TypeVar("T")
22
+ Impl = TypeVar("Impl") # the exact type of one registered implementation, so decorating a class keeps its type
23
+
24
+
25
+ class RegistryError(ValueError):
26
+ pass
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class NoOptions:
31
+ """For plugins that take no options."""
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Plugin(Generic[T]):
36
+ name: str
37
+ summary: str
38
+ impl: T
39
+ options: type[Any]
40
+
41
+
42
+ class Registry(Generic[T]):
43
+ """An ordered, name-keyed set of plugins of one kind."""
44
+
45
+ def __init__(self, what: str) -> None:
46
+ self.what = what
47
+ self._plugins: dict[str, Plugin[T]] = {}
48
+
49
+ def add(self, name: str, summary: str, *, options: type[Any] = NoOptions) -> Callable[[Impl], Impl]:
50
+ """Register the decorated implementation under ``name``. The decorated object comes back unchanged."""
51
+ if not is_dataclass(options):
52
+ raise TypeError(f"{self.what} {name!r}: options must be a dataclass")
53
+
54
+ def register(impl: Impl) -> Impl:
55
+ if name in self._plugins:
56
+ raise RegistryError(f"{self.what} {name!r} is registered twice")
57
+ self._plugins[name] = Plugin(name, summary, cast("T", impl), options)
58
+ return impl
59
+
60
+ return register
61
+
62
+ def names(self) -> list[str]:
63
+ return list(self._plugins)
64
+
65
+ def __iter__(self) -> Iterator[Plugin[T]]:
66
+ return iter(self._plugins.values())
67
+
68
+ def __contains__(self, name: object) -> bool:
69
+ return name in self._plugins
70
+
71
+ def get(self, name: str) -> Plugin[T]:
72
+ try:
73
+ return self._plugins[name]
74
+ except KeyError:
75
+ raise RegistryError(f"unknown {self.what} {name!r}{_suggest(name, self._plugins)}") from None
76
+
77
+ def options_for(self, name: str, raw: Mapping[str, Any] | None, *, where: str, base: Path | None = None) -> Any:
78
+ """The plugin's options from a config table, validated. Missing options take the dataclass defaults.
79
+
80
+ Relative paths are resolved against ``base`` (the config file's directory), so a shared config
81
+ works from any working directory.
82
+ """
83
+ plugin = self.get(name)
84
+ raw = dict(raw or {})
85
+ declared = {f.name: f for f in fields(plugin.options)}
86
+ unknown = set(raw) - set(declared)
87
+ if unknown:
88
+ key = min(unknown)
89
+ raise RegistryError(f"{where}: unknown option {key!r} for {self.what} {name!r}{_suggest(key, declared)}")
90
+ hints = get_type_hints(plugin.options)
91
+ values = {key: _coerce(f"{where}.{key}", hints[key], value, base) for key, value in raw.items()}
92
+ try:
93
+ return plugin.options(**values)
94
+ except TypeError as exc: # a required option (no default) is missing
95
+ raise RegistryError(f"{where}: {self.what} {name!r} needs {_missing(plugin.options, values)}") from exc
96
+
97
+ def defaults_for(self, name: str) -> Any:
98
+ """The plugin's options with nothing set."""
99
+ return self.options_for(name, None, where=name)
100
+
101
+
102
+ def _missing(options: type[Any], values: dict[str, Any]) -> str:
103
+ from dataclasses import MISSING
104
+
105
+ needed = [f.name for f in fields(options) if f.default is MISSING and f.default_factory is MISSING]
106
+ return ", ".join(n for n in needed if n not in values) or "a value"
107
+
108
+
109
+ def _suggest(name: str, options: Any) -> str:
110
+ """A typo gets its likely correction; a name nothing resembles (one that was renamed, say) gets the list."""
111
+ close = difflib.get_close_matches(name, list(options), n=1)
112
+ if close:
113
+ return f" (did you mean {close[0]!r}?)"
114
+ known = ", ".join(sorted(options))
115
+ return f" (one of: {known})" if known else ""
116
+
117
+
118
+ def _coerce(where: str, hint: Any, value: Any, base: Path | None) -> Any:
119
+ """Check ``value`` against a simple type hint: str, int, float, bool, Path, list[...], or X | None."""
120
+ if get_origin(hint) is types.UnionType or get_origin(hint) is _typing_union():
121
+ members = [m for m in get_args(hint) if m is not type(None)]
122
+ if value is None:
123
+ return None
124
+ return _coerce(where, members[0], value, base)
125
+ if get_origin(hint) is list:
126
+ (item,) = get_args(hint)
127
+ if not isinstance(value, list):
128
+ raise RegistryError(f"{where} must be a list, not {value!r}")
129
+ return [_coerce(f"{where}[{i}]", item, v, base) for i, v in enumerate(value)]
130
+ if hint is bool:
131
+ if not isinstance(value, bool):
132
+ raise RegistryError(f"{where} must be true or false, not {value!r}")
133
+ return value
134
+ if hint is int:
135
+ if isinstance(value, bool) or not isinstance(value, int):
136
+ raise RegistryError(f"{where} must be a whole number, not {value!r}")
137
+ return value
138
+ if hint is float:
139
+ if isinstance(value, bool) or not isinstance(value, int | float):
140
+ raise RegistryError(f"{where} must be a number, not {value!r}")
141
+ return float(value)
142
+ if hint is str:
143
+ if not isinstance(value, str):
144
+ raise RegistryError(f"{where} must be text, not {value!r}")
145
+ return value
146
+ if hint is Path:
147
+ if not isinstance(value, str) or not value.strip():
148
+ raise RegistryError(f"{where} must be a path, not {value!r}")
149
+ path = Path(value).expanduser()
150
+ return path if path.is_absolute() or base is None else (base / path).resolve()
151
+ raise TypeError(f"{where}: unsupported option type {hint!r}")
152
+
153
+
154
+ def _typing_union() -> Any:
155
+ import typing
156
+
157
+ return typing.Union
readthrough/review.py ADDED
@@ -0,0 +1,394 @@
1
+ """Deep-review sessions: one persistent agent session per PR (Copilot CLI or Claude Code), plus an isolated
2
+ git worktree.
3
+
4
+ The session ID is derived from the PR URL, so the same button starts the session the first time and
5
+ resumes it afterwards. ``review --fresh`` starts over with a random ID and remembers it in the ledger.
6
+
7
+ Sessions started anywhere else (VS Code's agent window, a pasted prompt) get IDs readthrough didn't choose.
8
+ Every prompt readthrough writes starts with a marker like ``[readthrough:github/owner/name#123]`` (the repo's
9
+ slug: its forge, then its path there), and ``SessionIndex`` links any session of any installed agent whose
10
+ first message carries one back to its PR.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import datetime as dt
16
+ import json
17
+ import logging
18
+ import re
19
+ import threading
20
+ import time
21
+ import uuid
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from urllib.parse import quote, unquote, urlsplit
25
+
26
+ from readthrough import agents, forges
27
+ from readthrough.agents import Agent, SessionInfo
28
+ from readthrough.config import Config
29
+ from readthrough.faults import ForgeError
30
+ from readthrough.model import PATH_SEGMENT, PR_NUMBER
31
+ from readthrough.process import run
32
+ from readthrough.tuning import default_tuning
33
+
34
+ log = logging.getLogger(__name__)
35
+
36
+ URL_SCHEME = "readthrough"
37
+ URL_ACTIONS = ("review", "refresh", "open")
38
+ _SEGMENT_RE = re.compile(rf"^{PATH_SEGMENT}$")
39
+
40
+ MARKER_RE = re.compile(rf"\[readthrough:({PATH_SEGMENT}(?:/{PATH_SEGMENT})+)#({PR_NUMBER})\]")
41
+
42
+
43
+ def pr_marker(slug: str, number: int) -> str:
44
+ return f"[readthrough:{slug}#{number}]"
45
+
46
+
47
+ def _same_repo(found: str, slug: str) -> bool:
48
+ """Markers name the repo by slug; ones written before there were forges name GitHub repos by path alone."""
49
+ found, slug = found.lower(), slug.lower()
50
+ return found == slug or (slug.startswith(f"{forges.DEFAULT}/") and found == slug.split("/", 1)[1])
51
+
52
+
53
+ def _agents(cfg: Config) -> list[Agent]:
54
+ """Every agent this machine has, so sessions started in any of them are found."""
55
+ return [a for a in agents.all_agents(cfg.agent_options) if a.available()]
56
+
57
+
58
+ class SessionIndex:
59
+ """Which agent sessions belong to which PR, found by the marker in their first message.
60
+
61
+ The answer for a session never changes, so it's cached in ``session-index.json``; each scan only
62
+ reads sessions it hasn't seen. Sessions without a first message yet are checked again later.
63
+ """
64
+
65
+ def __init__(self, path: Path, available: list[Agent]) -> None:
66
+ self.path = path
67
+ self.agents = available
68
+ self._lock = threading.Lock()
69
+ self._last = 0.0
70
+ try:
71
+ self._known: dict[str, dict[str, str] | None] = json.loads(path.read_text(encoding="utf-8"))
72
+ except (FileNotFoundError, ValueError):
73
+ self._known = {}
74
+
75
+ def scan(self, *, force: bool = False) -> bool:
76
+ with self._lock:
77
+ if not force and time.monotonic() - self._last < default_tuning().sessions.scan_seconds:
78
+ return False
79
+ self._last = time.monotonic()
80
+ records = {r.id: (agent, r) for agent in self.agents for r in agent.sessions()}
81
+ changed = False
82
+ for gone in set(self._known) - set(records):
83
+ del self._known[gone]
84
+ changed = True
85
+ for sid in set(records) - set(self._known):
86
+ agent, record = records[sid]
87
+ first = agent.first_user_message(record)
88
+ if first is None:
89
+ # Still starting up? Look again later. Long-idle sessions that never got a message are settled.
90
+ if time.time() - record.updated < 3600:
91
+ continue
92
+ first = ""
93
+ match = MARKER_RE.search(first[:2000])
94
+ meta = agent.session_meta(record)
95
+ self._known[sid] = (
96
+ {
97
+ "pr": f"{match.group(1).lower()}#{match.group(2)}",
98
+ "agent": agent.name,
99
+ "client": meta.get("client", ""),
100
+ "name": meta.get("name", ""),
101
+ }
102
+ if match
103
+ else None
104
+ )
105
+ changed = True
106
+ if changed:
107
+ self.path.parent.mkdir(parents=True, exist_ok=True)
108
+ tmp = self.path.with_suffix(".tmp")
109
+ tmp.write_text(json.dumps(self._known), encoding="utf-8")
110
+ tmp.replace(self.path)
111
+ return changed
112
+
113
+ def sessions_for(self, slug: str, number: int) -> dict[str, dict[str, str]]:
114
+ with self._lock:
115
+ out = {}
116
+ for sid, meta in self._known.items():
117
+ if meta:
118
+ found, _, n = meta["pr"].rpartition("#")
119
+ if n == str(number) and _same_repo(found, slug):
120
+ out[sid] = meta
121
+ return out
122
+
123
+ def agent_of(self, session_id: str) -> str | None:
124
+ with self._lock:
125
+ meta = self._known.get(session_id)
126
+ return meta.get("agent") if meta else None
127
+
128
+
129
+ _indexes: dict[Path, SessionIndex] = {}
130
+ _indexes_lock = threading.Lock()
131
+
132
+
133
+ def session_index(cfg: Config) -> SessionIndex:
134
+ with _indexes_lock:
135
+ if cfg.home not in _indexes:
136
+ _indexes[cfg.home] = SessionIndex(cfg.home / "session-index.json", _agents(cfg))
137
+ return _indexes[cfg.home]
138
+
139
+
140
+ @dataclass(frozen=True)
141
+ class AgentSet:
142
+ """The configured agent and every installed one, resolved once. Finding a program on PATH costs several
143
+ milliseconds on Windows, and a refresh asks about every PR, so the answer is looked up per pass, not per PR."""
144
+
145
+ configured: Agent
146
+ installed: list[Agent]
147
+
148
+
149
+ def agent_set(cfg: Config) -> AgentSet:
150
+ return AgentSet(agents.resolve(cfg.agent, cfg.agent_options), _agents(cfg))
151
+
152
+
153
+ def agent_for(cfg: Config, session_id: str | None = None, *, known: AgentSet | None = None) -> Agent:
154
+ """The agent a session belongs to (by the index, else by asking each), or the configured one for a new session."""
155
+ known = known or agent_set(cfg)
156
+ if session_id is None:
157
+ return known.configured
158
+ name = session_index(cfg).agent_of(session_id)
159
+ if name:
160
+ return agents.make(name, cfg.agent_options)
161
+ for agent in known.installed:
162
+ if agent.name != known.configured.name and agent.session_info(session_id).exists:
163
+ return agent
164
+ return known.configured
165
+
166
+
167
+ def pr_sessions(cfg: Config, number: int, primary: str, *, known: AgentSet | None = None) -> list[dict[str, object]]:
168
+ """Every agent session for this PR, the default one first, then the most recently used."""
169
+ known = known or agent_set(cfg)
170
+ found = session_index(cfg).sessions_for(cfg.slug, number)
171
+ out = []
172
+ for sid in dict.fromkeys([primary, *found]):
173
+ agent = agent_for(cfg, sid, known=known)
174
+ info = agent.session_info(sid)
175
+ if info.exists:
176
+ meta = found.get(sid) or {}
177
+ client = meta.get("client", "")
178
+ terminal = sid == primary or any(k in client for k in ("cli", "autopilot", "claude"))
179
+ out.append({
180
+ **info.payload(),
181
+ "where": "VS Code" if "vscode" in client else "terminal" if terminal else client or "other",
182
+ "name": meta.get("name", ""),
183
+ "agent": agent.name,
184
+ "agent_label": agent.label,
185
+ "editor_url": agent.editor_url(sid),
186
+ }) # fmt: skip
187
+
188
+ def newest_first(info: dict[str, object]) -> float:
189
+ updated = info.get("updated", 0)
190
+ return -float(updated) if isinstance(updated, int | float) else 0.0
191
+
192
+ return out[:1] + sorted(out[1:], key=newest_first)
193
+
194
+
195
+ def default_session_id(cfg: Config, number: int) -> str:
196
+ """Derived from the PR's URL on its forge, so the same PR always gets the same session."""
197
+ return str(uuid.uuid5(uuid.NAMESPACE_URL, forges.make(cfg).pr_url(number)))
198
+
199
+
200
+ def session_id_for(cfg: Config, number: int, ledger_entry: dict | None) -> str:
201
+ return (ledger_entry or {}).get("session") or default_session_id(cfg, number)
202
+
203
+
204
+ def session_info(cfg: Config, session_id: str, *, known: AgentSet | None = None) -> dict[str, object]:
205
+ """Whether the session exists, when it was last written, and whether it's open now (when the agent can say)."""
206
+ info: SessionInfo = agent_for(cfg, session_id, known=known).session_info(session_id)
207
+ return info.payload()
208
+
209
+
210
+ def review_prompt(cfg: Config, number: int, brief: Path) -> str:
211
+ return (
212
+ f"{pr_marker(cfg.slug, number)} Use the readthrough skill to run a deep review session for {cfg.repo}#{number}. "
213
+ f"The study brief is at {brief.as_posix()}"
214
+ )
215
+
216
+
217
+ @dataclass
218
+ class ReviewLaunch:
219
+ argv: list[str]
220
+ cwd: Path
221
+ session_id: str
222
+ resuming: bool
223
+ title: str
224
+ agent: str = "copilot"
225
+
226
+
227
+ def plan_review(
228
+ cfg: Config, number: int, *, ledger_entry: dict | None, fresh: bool = False, session_id: str | None = None
229
+ ) -> ReviewLaunch:
230
+ """Start or resume this PR's session. ``session_id`` resumes a specific session already linked to the PR.
231
+
232
+ A new session runs in the configured agent; an existing one is resumed in the agent that owns it, so a
233
+ Claude Code session linked by its marker resumes in Claude Code even when Copilot is the default.
234
+ """
235
+ if cfg.clone is None:
236
+ raise RuntimeError(
237
+ f"No local clone of {cfg.repo} configured. Set it with `readthrough onboard {cfg.repo} --clone PATH`."
238
+ )
239
+ if session_id is not None:
240
+ linked = {s["id"] for s in pr_sessions(cfg, number, session_id_for(cfg, number, ledger_entry))}
241
+ if session_id not in linked:
242
+ raise ValueError(f"Session {session_id} isn't linked to #{number}")
243
+ else:
244
+ session_id = str(uuid.uuid4()) if fresh else session_id_for(cfg, number, ledger_entry)
245
+ agent = agent_for(cfg, session_id)
246
+ if not agent.available():
247
+ raise RuntimeError(f"{agent.label} (`{agent.program}`) is not on PATH. Install it with `{agent.install_hint}`.")
248
+ resuming = agent.session_info(session_id).exists
249
+ short = cfg.repo.rsplit("/", 1)[-1]
250
+ if resuming:
251
+ argv = agent.resume_argv(session_id, add_dirs=[cfg.repo_dir], extra=cfg.agent_args)
252
+ else:
253
+ brief = cfg.briefs_dir / f"pr-{number}.md"
254
+ argv = agent.new_session_argv(
255
+ session_id=session_id, name=f"{short} #{number} deep review", prompt=review_prompt(cfg, number, brief),
256
+ add_dirs=[cfg.repo_dir], extra=cfg.agent_args,
257
+ ) # fmt: skip
258
+ return ReviewLaunch(argv=argv, cwd=cfg.clone, session_id=session_id, resuming=resuming, title=f"{short} #{number}",
259
+ agent=agent.name) # fmt: skip
260
+
261
+
262
+ def launch_in_terminal(launch: ReviewLaunch, cfg: Config) -> str:
263
+ """Open a new terminal window running the session, with the terminal chosen in config. Returns its name."""
264
+ from readthrough import terminals
265
+
266
+ command = terminals.Command(argv=launch.argv, cwd=launch.cwd, title=launch.title)
267
+ return terminals.launch(command, terminal=cfg.terminal, options=cfg.terminal_options)
268
+
269
+
270
+ @dataclass
271
+ class ReadthroughUrl:
272
+ action: str
273
+ repo: str | None = None
274
+ number: int | None = None
275
+
276
+
277
+ def parse_readthrough_url(url: str, *, allowed_repos: list[str]) -> ReadthroughUrl:
278
+ """Parse ``readthrough://<action>/<forge>/<owner>/<repo>[/<pr>]``. Anything unexpected is rejected.
279
+
280
+ Any web page can try to open this scheme, so this is strict: a fixed set of actions, a numeric PR,
281
+ and only repos you've onboarded (``allowed_repos`` holds their slugs; a GitHub repo may also be named
282
+ by its bare ``owner/repo``). ``readthrough://open`` with no repo opens the dashboard's front page.
283
+ """
284
+ parts = urlsplit(url.strip())
285
+ if parts.scheme.lower() != URL_SCHEME:
286
+ raise ValueError(f"Not a {URL_SCHEME}: URL")
287
+ action = parts.netloc.lower()
288
+ if action not in URL_ACTIONS:
289
+ raise ValueError(f"Unknown action {action!r}")
290
+ if parts.query or parts.fragment:
291
+ raise ValueError("Unexpected query or fragment")
292
+ segments = [unquote(s) for s in parts.path.split("/") if s] # a project called "Delivery Team" travels as %20
293
+ if action == "open" and not segments:
294
+ return ReadthroughUrl(action)
295
+ if not all(_SEGMENT_RE.match(s) for s in segments):
296
+ raise ValueError("Unexpected characters in the path")
297
+ number: int | None = None
298
+ if action == "review":
299
+ if len(segments) < 3 or not re.fullmatch(PR_NUMBER, segments[-1]):
300
+ raise ValueError(f"review needs a repo and a PR number, e.g. {URL_SCHEME}://review/github/owner/name/1234")
301
+ number = int(segments.pop())
302
+ if len(segments) < 2:
303
+ raise ValueError(f"{action} needs a repo, e.g. {URL_SCHEME}://{action}/github/owner/name")
304
+ repo = "/".join(segments)
305
+ match = next((slug for slug in allowed_repos if _same_repo(repo, slug)), None)
306
+ if match is None:
307
+ raise ValueError(f"{repo!r} isn't an onboarded repo")
308
+ return ReadthroughUrl(action, match, number)
309
+
310
+
311
+ def review_url(slug: str, number: int) -> str:
312
+ return f"{URL_SCHEME}://review/{quote(slug)}/{number}"
313
+
314
+
315
+ def vscode_new_session_url(prompt: str, workspace: Path | None) -> str:
316
+ """Start a VS Code agent session with the prompt prefilled. VS Code does not auto-submit it."""
317
+ url = f"vscode://agents/new?prompt={quote(prompt, safe='')}"
318
+ return url + (f"&workspace={quote(workspace.resolve().as_uri(), safe='')}" if workspace else "")
319
+
320
+
321
+ # ---------------------------------------------------------------- worktrees
322
+
323
+
324
+ def worktree_path(cfg: Config, number: int) -> Path:
325
+ return cfg.worktrees_dir / f"pr-{number}"
326
+
327
+
328
+ def repo_remote(cfg: Config) -> str:
329
+ """The clone's remote for this repo: as configured, else the one whose URL points at it, else origin."""
330
+ if cfg.remote:
331
+ return cfg.remote
332
+ from readthrough.config import remote_for
333
+
334
+ return (remote_for(cfg.clone, cfg.repo, cfg.forge) if cfg.clone else None) or "origin"
335
+
336
+
337
+ _worktree_locks: dict[Path, threading.Lock] = {}
338
+
339
+
340
+ def _worktree_lock(path: Path) -> threading.Lock:
341
+ with _indexes_lock:
342
+ return _worktree_locks.setdefault(path, threading.Lock())
343
+
344
+
345
+ def ensure_worktree(cfg: Config, number: int, *, base: str = "main") -> tuple[Path, str, str]:
346
+ """Check out the PR's current head in its own worktree. Returns (path, merge_base, head_sha).
347
+
348
+ One at a time per worktree: the study assistant's tools and a deep review launched from the page can ask
349
+ for the same PR within a second of each other, and two `git worktree add`s of one path can't both win.
350
+ """
351
+ if cfg.clone is None:
352
+ raise RuntimeError(f"No local clone of {cfg.repo} configured.")
353
+ with _worktree_lock(worktree_path(cfg, number)):
354
+ return _ensure_worktree(cfg, number, base)
355
+
356
+
357
+ def _ensure_worktree(cfg: Config, number: int, base: str) -> tuple[Path, str, str]:
358
+ clone, ref, remote = str(cfg.clone), f"refs/remotes/readthrough/pr-{number}", repo_remote(cfg)
359
+ run(["git", "-C", clone, "fetch", "--quiet", remote, f"+{forges.make(cfg).pr_ref(number)}:{ref}", base])
360
+ path = worktree_path(cfg, number)
361
+ if (path / ".git").exists() and not _worktree_attached(clone, path):
362
+ # The clone or the data directory moved since this was made, so its `.git` file points nowhere.
363
+ aside = path.with_name(f"{path.name}.detached-{dt.datetime.now(dt.UTC):%Y%m%dT%H%M%S}")
364
+ path.rename(aside)
365
+ log.warning(
366
+ "The worktree for #%d no longer belonged to %s; moved it to %s and made a fresh one", number, clone, aside
367
+ )
368
+ if (path / ".git").exists():
369
+ run(["git", "-C", str(path), "checkout", "--quiet", "--detach", ref])
370
+ else:
371
+ path.parent.mkdir(parents=True, exist_ok=True)
372
+ run(["git", "-C", clone, "worktree", "add", "--quiet", "--detach", str(path), ref])
373
+ head = run(["git", "-C", str(path), "rev-parse", "HEAD"]).strip()
374
+ merge_base = run(["git", "-C", clone, "merge-base", ref, f"{remote}/{base}"]).strip()
375
+ return path, merge_base, head
376
+
377
+
378
+ def _worktree_attached(clone: str, path: Path) -> bool:
379
+ """Whether git still knows ``path`` as a worktree of ``clone``, repairing the link if moving broke it."""
380
+ run(["git", "-C", clone, "worktree", "repair", str(path)], check=False)
381
+ try:
382
+ common = run(["git", "-C", str(path), "rev-parse", "--git-common-dir"]).strip()
383
+ except ForgeError:
384
+ return False
385
+ return Path(path, common).resolve() == Path(clone, ".git").resolve()
386
+
387
+
388
+ def remove_worktree(cfg: Config, number: int) -> bool:
389
+ path = worktree_path(cfg, number)
390
+ if cfg.clone is None or not path.exists():
391
+ return False
392
+ run(["git", "-C", str(cfg.clone), "worktree", "remove", "--force", str(path)])
393
+ run(["git", "-C", str(cfg.clone), "update-ref", "-d", f"refs/remotes/readthrough/pr-{number}"], check=False)
394
+ return True
readthrough/rules.py ADDED
@@ -0,0 +1,111 @@
1
+ """Parse a repo's own review rules: architecture contracts in markdown, and .github/instructions applyTo globs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+
10
+ @dataclass
11
+ class Contract:
12
+ responsibility: str = ""
13
+ does_not_own: str = ""
14
+
15
+
16
+ @dataclass
17
+ class Instruction:
18
+ name: str
19
+ patterns: list[str]
20
+ headings: list[str]
21
+ url: str
22
+ regexes: list[re.Pattern[str]] = field(default_factory=list, repr=False)
23
+
24
+ def __post_init__(self) -> None:
25
+ self.regexes = [glob_to_regex(p) for p in self.patterns]
26
+
27
+ def applies_to(self, path: str) -> bool:
28
+ return any(r.match(path) for r in self.regexes)
29
+
30
+
31
+ def parse_contracts(
32
+ text: str, *, responsibility: str = "Responsibility", does_not_own: str = "Does not own"
33
+ ) -> dict[str, Contract]:
34
+ """Return the responsibility and "does not own" text for every ``##`` section of an architecture doc.
35
+
36
+ A section's responsibility is any ``**... <responsibility>**: text`` line (so "**Executor
37
+ Responsibility**:" counts). Its "does not own" contract is the bullet starting ``- **<does_not_own>**``
38
+ plus everything nested under it.
39
+ """
40
+ resp_re = re.compile(rf"^\*\*[^*]*{re.escape(responsibility)}\*\*:\s*(.+)$", flags=re.MULTILINE)
41
+ sections: dict[str, Contract] = {}
42
+ for chunk in re.split(r"^## ", text, flags=re.MULTILINE)[1:]:
43
+ heading, _, body = chunk.partition("\n")
44
+ title = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", heading).strip()
45
+ sections[title] = Contract(
46
+ " ".join(m.strip() for m in resp_re.findall(body)), _does_not_own_block(body, does_not_own)
47
+ )
48
+ return sections
49
+
50
+
51
+ def _does_not_own_block(body: str, label: str) -> str:
52
+ lines = body.splitlines()
53
+ for idx, line in enumerate(lines):
54
+ if not line.lstrip().startswith(f"- **{label}**"):
55
+ continue
56
+ indent = len(line) - len(line.lstrip())
57
+ block = [line.strip()]
58
+ for nxt in lines[idx + 1 :]:
59
+ if nxt.strip() and len(nxt) - len(nxt.lstrip()) <= indent:
60
+ break
61
+ if nxt.strip():
62
+ block.append(nxt.strip())
63
+ return "\n".join(block)
64
+ return ""
65
+
66
+
67
+ def contracts_for(profile: Any, doc_text: str | None) -> dict[str, Contract]:
68
+ """Each component's contract, keyed by component id: from the architecture doc or written inline."""
69
+ sections = parse_contracts(doc_text, **profile.contracts_labels) if doc_text and profile.contracts_source else {}
70
+ out: dict[str, Contract] = {}
71
+ for comp in profile.components:
72
+ if comp.responsibility or comp.does_not_own:
73
+ dno = comp.does_not_own or ""
74
+ out[comp.id] = Contract(
75
+ comp.responsibility or "", f"- **Does not own**: {dno}" if dno and not dno.startswith("- ") else dno
76
+ )
77
+ elif comp.contract and comp.contract in sections:
78
+ out[comp.id] = sections[comp.contract]
79
+ return out
80
+
81
+
82
+ def glob_to_regex(pattern: str) -> re.Pattern[str]:
83
+ """Translate a VS Code style glob (``**``, ``*``, ``?``, ``{a,b}``) into an anchored regex."""
84
+ out, i = "", 0
85
+ while i < len(pattern):
86
+ if pattern.startswith("**/", i):
87
+ out, i = out + "(?:.*/)?", i + 3
88
+ elif pattern.startswith("**", i):
89
+ out, i = out + ".*", i + 2
90
+ elif pattern[i] == "*":
91
+ out, i = out + "[^/]*", i + 1
92
+ elif pattern[i] == "?":
93
+ out, i = out + "[^/]", i + 1
94
+ elif pattern[i] == "{" and "}" in pattern[i:]:
95
+ end = pattern.index("}", i)
96
+ out += "(?:" + "|".join(re.escape(o) for o in pattern[i + 1 : end].split(",")) + ")"
97
+ i = end + 1
98
+ else:
99
+ out, i = out + re.escape(pattern[i]), i + 1
100
+ return re.compile("^" + out + "$")
101
+
102
+
103
+ def parse_instruction(name: str, text: str, url: str) -> Instruction:
104
+ apply_to = ""
105
+ front = re.match(r"^---\s*\n(.*?)\n---", text, flags=re.DOTALL)
106
+ if front:
107
+ match = re.search(r"^applyTo:\s*(.+)$", front.group(1), flags=re.MULTILINE)
108
+ apply_to = match.group(1).strip().strip("'\"") if match else ""
109
+ patterns = [p.strip() for p in re.split(r",(?![^{]*\})", apply_to) if p.strip()]
110
+ headings = [h.strip() for h in re.findall(r"^## (.+)$", text, flags=re.MULTILINE)][:14]
111
+ return Instruction(name=name, patterns=patterns, headings=headings, url=url)