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/config.py ADDED
@@ -0,0 +1,533 @@
1
+ """Configuration: a global ``config.toml`` listing the repos you've onboarded, plus each repo's data directory.
2
+
3
+ Layout (``READTHROUGH_HOME``, default ``~/.readthrough``)::
4
+
5
+ config.toml global settings and one [[repos]] entry per onboarded repo
6
+ readthrough.log
7
+ repos/<forge>/<owner>/<name>/ everything for one repo (GitLab groups and ADO projects add segments)
8
+ profile.toml local architecture profile (from onboarding), if any
9
+ data.json index.html seen.json ledger.json
10
+ briefs/ cache/ study/ worktrees/
11
+
12
+ ``Config`` is the per-repo view the rest of the code works with; ``Settings`` is the whole file.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime as dt
18
+ import json
19
+ import os
20
+ import tomllib
21
+ from dataclasses import dataclass, field, fields
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from readthrough.files import write_atomic
26
+ from readthrough.registry import RegistryError
27
+ from readthrough.tuning import Tuning, TuningError, default_tuning, load_tuning
28
+
29
+ DEFAULT_HOME = Path(os.environ.get("READTHROUGH_HOME", Path.home() / ".readthrough"))
30
+ CONFIG_SCHEMA = 2 # 2: repos name their forge, and data lives under repos/<forge>/...
31
+ AUTO = "auto"
32
+
33
+
34
+ class ConfigError(ValueError):
35
+ pass
36
+
37
+
38
+ @dataclass
39
+ class Config:
40
+ """One repo's settings, with global settings folded in."""
41
+
42
+ home: Path
43
+ repo: str
44
+ forge: str = "github"
45
+ clone: Path | None = None
46
+ remote: str | None = None
47
+ account: str | None = None
48
+ profile: Path | None = None
49
+ onboarded: str | None = None
50
+ session_minutes: int = 60
51
+ limit: int = 100
52
+ internal_authors: list[str] = field(default_factory=list)
53
+ external_authors: list[str] = field(default_factory=list)
54
+ study_model: str | None = None
55
+ agent_args: list[str] = field(default_factory=list) # extra flags for the review agent, for this repo
56
+ port: int = 8765
57
+ refresh_minutes: int = 10
58
+ tuning: Tuning = field(default_factory=default_tuning)
59
+ # Machine-wide choices from the top of config.toml; see terminals.py, assistants.py, agents.py, profile.py.
60
+ # The option dicts map a plugin name to its validated options object.
61
+ terminal: str = AUTO
62
+ assistant: str = AUTO
63
+ runtime: str = AUTO # the model the study assistant and the drafter run on; see runtimes/
64
+ agent: str = AUTO
65
+ terminal_options: dict[str, Any] = field(default_factory=dict)
66
+ assistant_options: dict[str, Any] = field(default_factory=dict)
67
+ runtime_options: dict[str, Any] = field(default_factory=dict)
68
+ agent_options: dict[str, Any] = field(default_factory=dict)
69
+ profile_source_options: dict[str, Any] = field(default_factory=dict)
70
+ forge_options: dict[str, Any] = field(default_factory=dict)
71
+
72
+ @property
73
+ def slug(self) -> str:
74
+ """``<forge>/<repo path>``: the key for URLs and the data directory."""
75
+ return f"{self.forge}/{self.repo}"
76
+
77
+ @property
78
+ def repo_dir(self) -> Path:
79
+ return self.home.joinpath("repos", *self.slug.split("/"))
80
+
81
+ @property
82
+ def briefs_dir(self) -> Path:
83
+ return self.repo_dir / "briefs"
84
+
85
+ @property
86
+ def cache_dir(self) -> Path:
87
+ return self.repo_dir / "cache"
88
+
89
+ @property
90
+ def study_dir(self) -> Path:
91
+ return self.repo_dir / "study"
92
+
93
+ @property
94
+ def worktrees_dir(self) -> Path:
95
+ return self.repo_dir / "worktrees"
96
+
97
+ @property
98
+ def data_path(self) -> Path:
99
+ return self.repo_dir / "data.json"
100
+
101
+ @property
102
+ def dashboard_path(self) -> Path:
103
+ return self.repo_dir / "index.html"
104
+
105
+ @property
106
+ def ledger_path(self) -> Path:
107
+ return self.repo_dir / "ledger.json"
108
+
109
+ @property
110
+ def seen_path(self) -> Path:
111
+ return self.repo_dir / "seen.json"
112
+
113
+ @property
114
+ def local_profile_path(self) -> Path:
115
+ return self.repo_dir / "profile.toml"
116
+
117
+ @property
118
+ def log_path(self) -> Path:
119
+ return self.home / "readthrough.log"
120
+
121
+ @property
122
+ def config_path(self) -> Path:
123
+ return self.home / "config.toml"
124
+
125
+
126
+ MACHINE_CHOICES = ("terminal", "assistant", "runtime", "agent") # `name = "..."` keys at the top of config.toml
127
+ MACHINE_KEYS = {
128
+ *MACHINE_CHOICES,
129
+ "terminal_options",
130
+ "assistant_options",
131
+ "runtime_options",
132
+ "agent_options",
133
+ "profile_source_options",
134
+ "forge_options",
135
+ }
136
+ REPO_KEYS = ({f.name for f in fields(Config)} - {"home", "repo", "port", "refresh_minutes"} - MACHINE_KEYS) | {"name"}
137
+ GLOBAL_KEYS = {
138
+ "schema", "default_repo", "port", "refresh_minutes", "defaults", "tuning", "repos",
139
+ *MACHINE_CHOICES, "terminals", "assistants", "runtimes", "agents", "profile_sources", "forges",
140
+ } # fmt: skip
141
+ PATH_KEYS = {"clone", "profile"}
142
+ # config.toml table -> the Settings attribute holding its validated per-plugin options.
143
+ PLUGIN_TABLES = {
144
+ "terminals": "terminal_options",
145
+ "assistants": "assistant_options",
146
+ "runtimes": "runtime_options",
147
+ "agents": "agent_options",
148
+ "profile_sources": "profile_source_options",
149
+ "forges": "forge_options",
150
+ }
151
+
152
+
153
+ @dataclass
154
+ class Settings:
155
+ home: Path = DEFAULT_HOME
156
+ default_repo: str | None = None
157
+ port: int = 8765
158
+ refresh_minutes: int = 10
159
+ defaults: dict[str, Any] = field(default_factory=dict)
160
+ repos: list[dict[str, Any]] = field(default_factory=list)
161
+ tuning_raw: dict[str, Any] = field(default_factory=dict)
162
+ config_file: Path | None = None
163
+ terminal: str = AUTO
164
+ assistant: str = AUTO
165
+ runtime: str = AUTO # the model the study assistant and the drafter run on; see runtimes/
166
+ agent: str = AUTO
167
+ terminal_options: dict[str, Any] = field(default_factory=dict)
168
+ assistant_options: dict[str, Any] = field(default_factory=dict)
169
+ runtime_options: dict[str, Any] = field(default_factory=dict)
170
+ agent_options: dict[str, Any] = field(default_factory=dict)
171
+ profile_source_options: dict[str, Any] = field(default_factory=dict)
172
+ forge_options: dict[str, Any] = field(default_factory=dict)
173
+ plugin_raw: dict[str, dict[str, Any]] = field(default_factory=dict) # the option tables as written, for saving
174
+
175
+ @property
176
+ def path(self) -> Path:
177
+ """config.toml: in the data directory, unless READTHROUGH_CONFIG points somewhere else (a dotfiles repo, say)."""
178
+ return self.config_file or self.home / "config.toml"
179
+
180
+ @property
181
+ def tuning(self) -> Tuning:
182
+ return load_tuning(self.tuning_raw)
183
+
184
+ @property
185
+ def log_path(self) -> Path:
186
+ return self.home / "readthrough.log"
187
+
188
+ def names(self) -> list[str]:
189
+ """Each repo as the user refers to it: the plain name when that's unambiguous, else ``forge/name``."""
190
+ counts: dict[str, int] = {}
191
+ for r in self.repos:
192
+ counts[r["name"].lower()] = counts.get(r["name"].lower(), 0) + 1
193
+ return [r["name"] if counts[r["name"].lower()] == 1 else _slug(r) for r in self.repos]
194
+
195
+ def display_name(self, repo: str) -> str:
196
+ """How to refer to a configured repo in messages and ``default_repo``: see ``names()``."""
197
+ entry = self.entry(repo)
198
+ if entry is None:
199
+ raise ConfigError(f"{repo} isn't configured")
200
+ return self.names()[self.repos.index(entry)]
201
+
202
+ def entry(self, repo: str, forge: str | None = None) -> dict[str, Any] | None:
203
+ """The entry ``repo`` names: a ``forge/owner/name`` slug, or a plain name (with ``forge`` to disambiguate)."""
204
+ want = repo.lower()
205
+ by_slug = [r for r in self.repos if _slug(r).lower() == want]
206
+ if by_slug:
207
+ return by_slug[0]
208
+ by_name = [r for r in self.repos if r["name"].lower() == want and (forge is None or _forge_of(r) == forge)]
209
+ if len(by_name) > 1:
210
+ raise ConfigError(
211
+ f"{repo} is onboarded on several forges ({', '.join(_slug(r) for r in by_name)}); name one"
212
+ )
213
+ return by_name[0] if by_name else None
214
+
215
+ def config_for(self, repo: str | None = None, *, forge: str | None = None) -> Config:
216
+ """The per-repo view. With no repo given, the default repo, or the only one.
217
+
218
+ A repo that isn't configured yet gets a config too (onboarding starts that way); ``forge`` says
219
+ which platform it's on, and the name is checked against that platform's shape.
220
+ """
221
+ if repo is None:
222
+ repo = self.default_repo or (self.repos[0]["name"] if len(self.repos) == 1 else None)
223
+ if repo is None:
224
+ if not self.repos:
225
+ raise ConfigError("No repos yet. Onboard one with `readthrough onboard owner/name`.")
226
+ raise ConfigError(f"Several repos are configured ({', '.join(self.names())}); pick one with --repo.")
227
+ entry = self.entry(repo, forge)
228
+ if entry is None:
229
+ forge_name, name = _split_slug(repo, forge)
230
+ problem = _validate_repo(forge_name, name)
231
+ if problem:
232
+ raise ConfigError(problem)
233
+ entry = {"name": name, "forge": forge_name}
234
+ merged = {**self.defaults, **{k: v for k, v in entry.items() if k not in ("name", "tuning")}}
235
+ try:
236
+ tuning = load_tuning(
237
+ self.tuning_raw, repo_overrides=entry.get("tuning"), where=f"tuning for {entry['name']}"
238
+ )
239
+ except TuningError as exc:
240
+ raise ConfigError(f"{self.path}: {exc}") from exc
241
+ cfg = Config(
242
+ home=self.home,
243
+ repo=entry["name"],
244
+ port=self.port,
245
+ refresh_minutes=self.refresh_minutes,
246
+ tuning=tuning,
247
+ **{key: getattr(self, key) for key in MACHINE_KEYS},
248
+ )
249
+ for key, value in merged.items():
250
+ setattr(cfg, key, Path(value).expanduser() if key in PATH_KEYS and value else value)
251
+ return cfg
252
+
253
+ def all(self) -> list[Config]:
254
+ return [self.config_for(_slug(r)) for r in self.repos]
255
+
256
+ def upsert(self, repo: str, *, forge: str | None = None, **values: Any) -> dict[str, Any]:
257
+ entry = self.entry(repo, forge)
258
+ if entry is None:
259
+ forge_name, name = _split_slug(repo, forge)
260
+ entry = {"name": name, "forge": forge_name}
261
+ self.repos.append(entry)
262
+ for key, value in values.items():
263
+ if key not in REPO_KEYS:
264
+ raise ConfigError(f"unknown repo setting {key!r}")
265
+ if value is None:
266
+ entry.pop(key, None)
267
+ else:
268
+ entry[key] = str(value) if isinstance(value, Path) else value
269
+ return entry
270
+
271
+ def remove(self, repo: str) -> bool:
272
+ entry = self.entry(repo)
273
+ if entry is None:
274
+ return False
275
+ self.repos.remove(entry)
276
+ if self.default_repo and self.default_repo.lower() in (
277
+ repo.lower(),
278
+ entry["name"].lower(),
279
+ _slug(entry).lower(),
280
+ ):
281
+ self.default_repo = None
282
+ return True
283
+
284
+ def save(self) -> None:
285
+ self.home.mkdir(parents=True, exist_ok=True)
286
+ write_atomic(self.path, dump_settings(self))
287
+
288
+
289
+ def load_settings(home: Path | None = None) -> Settings:
290
+ """Read config.toml. ``READTHROUGH_CONFIG`` names another file, unless a home directory is given explicitly."""
291
+ env_file = os.environ.get("READTHROUGH_CONFIG")
292
+ settings = Settings(
293
+ home=home or DEFAULT_HOME, config_file=Path(env_file).expanduser() if env_file and home is None else None
294
+ )
295
+ if not settings.path.exists():
296
+ return settings
297
+ try:
298
+ raw = tomllib.loads(settings.path.read_text(encoding="utf-8"))
299
+ except tomllib.TOMLDecodeError as exc:
300
+ raise ConfigError(f"{settings.path}: {exc}") from exc
301
+ unknown = set(raw) - GLOBAL_KEYS
302
+ if unknown:
303
+ hints = "".join(_did_you_mean(k, GLOBAL_KEYS) for k in sorted(unknown))
304
+ raise ConfigError(f"Unknown key(s) {', '.join(sorted(unknown))} in {settings.path}{hints}")
305
+ found = raw.get("schema", CONFIG_SCHEMA)
306
+ if found > CONFIG_SCHEMA:
307
+ raise ConfigError(
308
+ f"{settings.path} is schema {found}; this readthrough reads schema {CONFIG_SCHEMA}. Upgrade readthrough."
309
+ )
310
+ if found < CONFIG_SCHEMA:
311
+ raise ConfigError(
312
+ f"{settings.path} is schema {found}; this readthrough reads schema {CONFIG_SCHEMA}. "
313
+ f"Schema 2 files each repo's data under repos/<forge>/..., so move repos/<owner>/<name> to "
314
+ f"repos/github/<owner>/<name>, rename [tuning.github] to [tuning.forge], and set schema = {CONFIG_SCHEMA}."
315
+ )
316
+ settings.default_repo = raw.get("default_repo")
317
+ settings.port = int(raw.get("port", settings.port))
318
+ settings.refresh_minutes = int(raw.get("refresh_minutes", settings.refresh_minutes))
319
+ settings.defaults = dict(raw.get("defaults") or {})
320
+ settings.tuning_raw = dict(raw.get("tuning") or {})
321
+ try:
322
+ load_tuning(settings.tuning_raw)
323
+ _load_plugins(settings, raw)
324
+ except (TuningError, RegistryError) as exc:
325
+ raise ConfigError(f"{settings.path}: {exc}") from exc
326
+ for i, entry in enumerate(raw.get("repos") or []):
327
+ bad = set(entry) - REPO_KEYS
328
+ if bad:
329
+ hints = "".join(_did_you_mean(k, REPO_KEYS) for k in sorted(bad))
330
+ raise ConfigError(f"Unknown key(s) {', '.join(sorted(bad))} in repos[{i}] of {settings.path}{hints}")
331
+ forge_name = str(entry.get("forge", "github"))
332
+ from readthrough.forges import FORGES
333
+
334
+ try:
335
+ FORGES.get(forge_name)
336
+ except RegistryError as exc:
337
+ raise ConfigError(f"repos[{i}] in {settings.path}: {exc}") from exc
338
+ problem = _validate_repo(forge_name, str(entry.get("name", "")))
339
+ if problem:
340
+ raise ConfigError(f"repos[{i}] in {settings.path}: {problem}")
341
+ settings.repos.append(dict(entry))
342
+ bad = set(settings.defaults) - (REPO_KEYS - {"tuning", "forge"})
343
+ if bad:
344
+ raise ConfigError(f"Unknown key(s) {', '.join(sorted(bad))} in [defaults] of {settings.path}")
345
+ for entry in settings.repos:
346
+ settings.config_for(_slug(entry)) # validates the repo's own tuning
347
+ return settings
348
+
349
+
350
+ def _forge_of(entry: dict[str, Any]) -> str:
351
+ return str(entry.get("forge") or "github")
352
+
353
+
354
+ def _slug(entry: dict[str, Any]) -> str:
355
+ return f"{_forge_of(entry)}/{entry['name']}"
356
+
357
+
358
+ def _split_slug(repo: str, forge: str | None) -> tuple[str, str]:
359
+ """``forge/owner/name`` -> (forge, owner/name); a plain name takes ``forge`` or the default.
360
+
361
+ The first segment only counts as a forge when what follows is a valid locator there, so a GitHub owner
362
+ that happens to be called ``gitlab`` still reads as ``gitlab/<name>`` on GitHub.
363
+ """
364
+ from readthrough.forges import FORGES, validate_repo
365
+
366
+ head, _, rest = repo.partition("/")
367
+ if forge is None and head in FORGES and rest and validate_repo(head, rest) is None:
368
+ return head, rest
369
+ return forge or "github", repo
370
+
371
+
372
+ def _validate_repo(forge: str, repo: str) -> str | None:
373
+ from readthrough.forges import FORGES, validate_repo
374
+
375
+ try:
376
+ FORGES.get(forge)
377
+ except RegistryError as exc:
378
+ return str(exc)
379
+ return validate_repo(forge, repo)
380
+
381
+
382
+ def _load_plugins(settings: Settings, raw: dict[str, Any]) -> None:
383
+ """``terminal``, ``assistant``, ``agent``, and the ``[terminals.*]``, ``[assistants.*]``, ``[agents.*]``,
384
+ ``[profile_sources.*]``, ``[forges.*]`` tables.
385
+
386
+ Each name is checked against its registry and each table against the plugin's options, so a typo
387
+ fails here, where the message can say what was meant, rather than when a review is launched.
388
+ """
389
+ from readthrough.agents import AGENTS
390
+ from readthrough.assistants import ASSISTANTS
391
+ from readthrough.forges import FORGES
392
+ from readthrough.profile import PROFILE_SOURCES
393
+ from readthrough.runtimes import RUNTIMES
394
+ from readthrough.terminals import TERMINALS
395
+
396
+ base = settings.path.parent
397
+ for key, registry in (("terminal", TERMINALS), ("assistant", ASSISTANTS), ("runtime", RUNTIMES), ("agent", AGENTS)):
398
+ name = raw.get(key, AUTO)
399
+ if not isinstance(name, str):
400
+ raise ConfigError(f"{key} must be a name, not {name!r}")
401
+ if name != AUTO:
402
+ registry.get(name)
403
+ setattr(settings, key, name)
404
+ registries = {
405
+ "terminals": TERMINALS,
406
+ "assistants": ASSISTANTS,
407
+ "runtimes": RUNTIMES,
408
+ "agents": AGENTS,
409
+ "profile_sources": PROFILE_SOURCES,
410
+ "forges": FORGES,
411
+ }
412
+ for key, attr in PLUGIN_TABLES.items():
413
+ tables = raw.get(key) or {}
414
+ if not isinstance(tables, dict) or not all(isinstance(t, dict) for t in tables.values()):
415
+ raise ConfigError(f"[{key}] must hold one [{key}.<name>] table per plugin")
416
+ validated = {
417
+ name: registries[key].options_for(name, table, where=f"[{key}.{name}]", base=base)
418
+ for name, table in tables.items()
419
+ }
420
+ setattr(settings, attr, validated)
421
+ settings.plugin_raw[key] = {name: dict(table) for name, table in tables.items()}
422
+
423
+
424
+ def _did_you_mean(key: str, options: Any) -> str:
425
+ import difflib
426
+
427
+ close = difflib.get_close_matches(key, sorted(options), n=1)
428
+ return f" ({key}: did you mean {close[0]!r}?)" if close else ""
429
+
430
+
431
+ def portable_path(value: Any) -> str:
432
+ """Write paths under your home directory as ``~/...`` so the file works on another machine or account."""
433
+ path = Path(value).expanduser()
434
+ try:
435
+ return "~/" + path.resolve().relative_to(Path.home().resolve()).as_posix()
436
+ except ValueError:
437
+ return str(value)
438
+
439
+
440
+ # ---------------------------------------------------------------- writing (tomllib only reads)
441
+
442
+
443
+ def _value(value: Any) -> str:
444
+ if isinstance(value, bool):
445
+ return "true" if value else "false"
446
+ if isinstance(value, int | float):
447
+ return str(value)
448
+ if isinstance(value, list):
449
+ return "[" + ", ".join(_value(v) for v in value) + "]"
450
+ if isinstance(value, dt.datetime):
451
+ return value.isoformat()
452
+ return json.dumps(str(value), ensure_ascii=False)
453
+
454
+
455
+ def _tables(prefix: str, raw: dict[str, Any]) -> list[str]:
456
+ out = []
457
+ for section, values in raw.items():
458
+ out.append(f"[{prefix}.{section}]")
459
+ out += [f"{k} = {_value(v)}" for k, v in values.items()]
460
+ out.append("")
461
+ return out
462
+
463
+
464
+ def dump_settings(settings: Settings) -> str:
465
+ out = [
466
+ '# readthrough configuration. See docs/guide.md, "Configuration". Tunable settings and their',
467
+ "# defaults: `readthrough config --defaults`.",
468
+ f"schema = {CONFIG_SCHEMA}",
469
+ "",
470
+ ]
471
+ if settings.default_repo:
472
+ out.append(f"default_repo = {_value(settings.default_repo)}")
473
+ out += [f"port = {settings.port}", f"refresh_minutes = {settings.refresh_minutes}"]
474
+ for key in MACHINE_CHOICES:
475
+ if getattr(settings, key) != AUTO:
476
+ out.append(f"{key} = {_value(getattr(settings, key))}")
477
+ out.append("")
478
+ if settings.defaults:
479
+ out.append("[defaults] # apply to every repo unless the repo sets its own")
480
+ out += [f"{k} = {_value(portable_path(v) if k in PATH_KEYS else v)}" for k, v in settings.defaults.items()]
481
+ out.append("")
482
+ for key in PLUGIN_TABLES:
483
+ out += _tables(key, settings.plugin_raw.get(key) or {})
484
+ out += _tables("tuning", settings.tuning_raw)
485
+ for entry in settings.repos:
486
+ out.append("[[repos]]")
487
+ out.append(f"name = {_value(entry['name'])}")
488
+ out += [
489
+ f"{k} = {_value(portable_path(v) if k in PATH_KEYS else v)}"
490
+ for k, v in entry.items()
491
+ if k not in ("name", "tuning") and not (k == "forge" and v == "github")
492
+ ]
493
+ out.append("")
494
+ out += _tables("repos.tuning", entry.get("tuning") or {})
495
+ return "\n".join(out)
496
+
497
+
498
+ # ---------------------------------------------------------------- local clones
499
+
500
+
501
+ def _git(args: list[str]) -> str:
502
+ from readthrough.faults import ForgeError
503
+ from readthrough.process import run
504
+
505
+ try:
506
+ return run(["git", *args])
507
+ except ForgeError:
508
+ return ""
509
+
510
+
511
+ def remote_for(clone: Path, repo: str, forge: str = "github") -> str | None:
512
+ """The name of the remote in ``clone`` that points at ``repo`` (https or ssh, any host alias).
513
+
514
+ What a remote URL for ``repo`` looks like is the forge's to say (``Forge.remote_matches``).
515
+ """
516
+ from readthrough.forges import adapter
517
+
518
+ matches = adapter(forge).remote_matches
519
+ for line in _git(["-C", str(clone), "remote", "-v"]).splitlines():
520
+ parts = line.split()
521
+ if len(parts) >= 2 and matches(parts[1], repo):
522
+ return parts[0]
523
+ return None
524
+
525
+
526
+ def guess_clone(repo: str, forge: str = "github") -> Path | None:
527
+ """Look for an existing clone of ``repo`` in the usual places."""
528
+ name = repo.rsplit("/", 1)[1] # the repo's own name: the last segment on every forge
529
+ for base in (Path.home() / "src", Path.home() / "source" / "repos", Path.home() / "code", Path.home()):
530
+ for candidate in (base / name, base / name.lower()):
531
+ if (candidate / ".git").exists() and remote_for(candidate, repo, forge):
532
+ return candidate
533
+ return None