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/study.py ADDED
@@ -0,0 +1,327 @@
1
+ """The study log: an append-only record of how well you understand each PR.
2
+
3
+ Everything that shows understanding (or the lack of it) is appended here: your prediction before
4
+ reading (or that you skipped it), whether you asked for a briefing, quiz questions and your answers (each
5
+ tagged with whether a hint or a briefing came first), the assistant's assessments with code evidence, your
6
+ teach-back, your "what I missed" reflections, pinned notes, and findings. Entries are never edited or
7
+ deleted, so the log is an honest trail.
8
+
9
+ ``by`` says what kind of author wrote an entry: ``you``, ``model`` (the Socratic assistant, on whichever model
10
+ runtime is configured), or ``rules`` (the assistant that needs no model). Only an author that read the code
11
+ writes verdicts; the rules assistant never does. What the model writes also carries ``model`` (the model the
12
+ runtime reported using) and ``runtime`` (which runtime carried the conversation), because a verdict's weight
13
+ depends on who reached it and the same assistant may be talking to GitHub Copilot, Claude, or a deployment
14
+ of yours. Both come from the entry, never from the current configuration, so changing runtimes never relabels
15
+ an old grade. Older logs say ``by: copilot``, the assistant's former name; ``load`` reads it as ``model`` rather
16
+ than rewriting the file, and leaves the runtime unrecorded, since those entries never said which it was.
17
+
18
+ The log lives in the repo's data directory (``study/pr-<n>.jsonl``), and its evidence is rendered as the last
19
+ section of the brief, so a terminal deep review reads the same evidence the dashboard shows.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import datetime as dt
25
+ import json
26
+ import threading
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from readthrough.config import Config
31
+ from readthrough.files import locked
32
+ from readthrough.limits import MAX_STUDY_TEXT
33
+
34
+ MARKER = "<!-- readthrough:study-log -->"
35
+ VERDICTS = ("correct", "partial", "incorrect")
36
+ SEVERITIES = ("blocker", "major", "minor", "question")
37
+ RESERVED = frozenset({"id", "ts", "kind", "by"})
38
+
39
+ MODEL = "model" # the Socratic assistant, whichever model runtime carries it
40
+ RULES = "rules" # the assistant that needs no model and never grades
41
+ ASSISTANTS = (MODEL, RULES)
42
+ LEGACY_MODEL_BY = "copilot" # the model assistant's former name in the log, after its first engine
43
+ AIDS = ("hint", "brief") # what can come before an answer and inform it
44
+ TOOL = "readthrough" # the engine itself, which only ever records that an assistant failed to answer
45
+
46
+ # kind -> (who may write it, required fields)
47
+ KINDS: dict[str, tuple[set[str], tuple[str, ...]]] = {
48
+ "prediction": ({"you"}, ("text",)),
49
+ "teachback": ({"you"}, ("text",)),
50
+ "answer": ({"you"}, ("qid", "text")),
51
+ "reflection": ({"you"}, ("text",)), # "what I missed", after an answer or a teach-back
52
+ "chat": ({"you", *ASSISTANTS}, ("role", "text")),
53
+ "note": ({"you", *ASSISTANTS}, ("text",)),
54
+ "finding": ({"you", MODEL}, ("severity", "summary")),
55
+ "question": (set(ASSISTANTS), ("question",)),
56
+ "assessment": ({MODEL}, ("qid", "verdict", "feedback")),
57
+ "teachback_assessment": ({MODEL}, ("verdict", "feedback")),
58
+ # A turn that ended in an error, so a request with no reply is never read as one you abandoned.
59
+ "failure": ({TOOL}, ("assistant", "text")),
60
+ }
61
+
62
+ _lock = threading.Lock()
63
+
64
+
65
+ def log_path(cfg: Config, number: int) -> Path:
66
+ return cfg.study_dir / f"pr-{number}.jsonl"
67
+
68
+
69
+ def load(cfg: Config, number: int) -> list[dict[str, Any]]:
70
+ path = log_path(cfg, number)
71
+ if not path.exists():
72
+ return []
73
+ entries = []
74
+ for line in path.read_text(encoding="utf-8").splitlines():
75
+ if line.strip():
76
+ try:
77
+ entries.append(_current(json.loads(line)))
78
+ except ValueError:
79
+ continue # a torn final line from a crash; skip it rather than lose the log
80
+ return entries
81
+
82
+
83
+ def _current(entry: dict[str, Any]) -> dict[str, Any]:
84
+ """An entry as this version names things. The model assistant used to write as ``copilot``; that was its
85
+ name, not a record of the runtime (the same name was written through other runtimes for a while), so the
86
+ author is renamed and the runtime is left unrecorded rather than guessed."""
87
+ if entry.get("by") == LEGACY_MODEL_BY:
88
+ entry["by"] = MODEL
89
+ if entry.get("kind") == "failure" and entry.get("assistant") == LEGACY_MODEL_BY:
90
+ entry["assistant"] = MODEL
91
+ return entry
92
+
93
+
94
+ def append(cfg: Config, number: int, kind: str, *, by: str, **fields: Any) -> dict[str, Any]:
95
+ """Validate and append one entry. Returns the stored entry (with its id)."""
96
+ if kind not in KINDS:
97
+ raise ValueError(f"unknown entry kind {kind!r}")
98
+ writers, required = KINDS[kind]
99
+ if by not in writers:
100
+ raise ValueError(f"{by} can't write {kind} entries")
101
+ missing = [f for f in required if not str(fields.get(f, "")).strip()]
102
+ if missing:
103
+ raise ValueError(f"{kind} needs {', '.join(missing)}")
104
+ # The log sets these; a writer (a model's tool call included) can't name them, or the record would lie.
105
+ reserved = RESERVED & set(fields)
106
+ if reserved:
107
+ raise ValueError(f"{', '.join(sorted(reserved))} are set by the log, not the writer")
108
+ for key, value in fields.items():
109
+ if isinstance(value, list):
110
+ if not all(isinstance(v, str) for v in value):
111
+ raise ValueError(f"{key} must be a list of strings")
112
+ fields[key] = [v[:MAX_STUDY_TEXT] for v in value]
113
+ elif value is not None and not isinstance(value, (str, int, float, bool)):
114
+ raise ValueError(f"{key} must be a string, a number, true or false, or a list of strings")
115
+ elif isinstance(value, str) and len(value) > MAX_STUDY_TEXT:
116
+ fields[key] = value[:MAX_STUDY_TEXT]
117
+ if fields.get("line") is not None:
118
+ try:
119
+ fields["line"] = int(fields["line"])
120
+ except (TypeError, ValueError):
121
+ raise ValueError("line must be a number") from None
122
+ if kind in ("assessment", "teachback_assessment") and fields["verdict"] not in VERDICTS:
123
+ raise ValueError(f"verdict must be one of {', '.join(VERDICTS)}")
124
+ if kind == "finding" and fields["severity"] not in SEVERITIES:
125
+ raise ValueError(f"severity must be one of {', '.join(SEVERITIES)}")
126
+
127
+ # Ids and question numbers come from what's already in the file, so reading and appending must be one step
128
+ # for every writer: this process's threads (the lock) and other processes, such as a review agent's
129
+ # terminal recording a finding while the server's assistant writes (the file lock).
130
+ path = log_path(cfg, number)
131
+ path.parent.mkdir(parents=True, exist_ok=True)
132
+ with _lock, locked(path):
133
+ entries = load(cfg, number)
134
+ if (
135
+ kind in ("answer", "assessment", "reflection")
136
+ and fields.get("qid") is not None
137
+ and not any(e["kind"] == "question" and e.get("qid") == fields["qid"] for e in entries)
138
+ ):
139
+ raise ValueError(f"no question {fields['qid']}")
140
+ if kind == "answer":
141
+ fields["aided"] = aids_before(entries, fields["qid"])
142
+ if kind == "question":
143
+ fields["qid"] = f"Q{sum(e['kind'] == 'question' for e in entries) + 1}"
144
+ entry = {
145
+ "id": len(entries) + 1,
146
+ "ts": dt.datetime.now(dt.UTC).isoformat(timespec="seconds"),
147
+ "kind": kind,
148
+ "by": by,
149
+ **fields,
150
+ }
151
+ with path.open("a", encoding="utf-8") as handle:
152
+ handle.write(json.dumps(entry) + "\n")
153
+ return entry
154
+
155
+
156
+ def aids_before(entries: list[dict[str, Any]], qid: str) -> list[str]:
157
+ """What the learner had seen before answering ``qid``: a hint for it, or a briefing. Computed from the
158
+ log, never asserted by anyone, so "worked out unaided" is something a reader can check."""
159
+ aids = []
160
+ if any(e["kind"] == "chat" and e.get("action") == "hint" and e.get("qid") == qid for e in entries):
161
+ aids.append("hint")
162
+ if any(e["kind"] == "chat" and e.get("action") == "brief" for e in entries):
163
+ aids.append("brief")
164
+ return aids
165
+
166
+
167
+ def summarize(entries: list[dict[str, Any]]) -> dict[str, Any]:
168
+ questions = {e["qid"]: e for e in entries if e["kind"] == "question"}
169
+ latest_assessment: dict[str, str] = {}
170
+ for e in entries:
171
+ if e["kind"] == "assessment":
172
+ latest_assessment[e["qid"]] = e["verdict"]
173
+ answers = {e["qid"]: e for e in entries if e["kind"] == "answer" and e["qid"] in questions}
174
+ counts = {v: sum(1 for x in latest_assessment.values() if x == v) for v in VERDICTS}
175
+ assessed = sum(counts.values())
176
+ teachbacks = [e for e in entries if e["kind"] == "teachback_assessment"]
177
+ return {
178
+ "questions": len(questions),
179
+ "answered": len(answers),
180
+ "unaided": sum(1 for a in answers.values() if not a.get("aided")),
181
+ "after_hint": sum(1 for a in answers.values() if "hint" in (a.get("aided") or [])),
182
+ "after_brief": sum(1 for a in answers.values() if "brief" in (a.get("aided") or [])),
183
+ "assessed": assessed,
184
+ **counts,
185
+ "score": round((counts["correct"] + 0.5 * counts["partial"]) / assessed, 2) if assessed else None,
186
+ "predictions": sum(e["kind"] == "prediction" and not e.get("skipped") for e in entries),
187
+ "prediction_skipped": any(e["kind"] == "prediction" and e.get("skipped") for e in entries),
188
+ "briefed": any(e["kind"] == "chat" and e.get("action") == "brief" for e in entries),
189
+ "teachback": teachbacks[-1]["verdict"] if teachbacks else None,
190
+ "teachbacks": sum(e["kind"] == "teachback" for e in entries),
191
+ "reflections": sum(e["kind"] == "reflection" for e in entries),
192
+ "findings": sum(e["kind"] == "finding" for e in entries),
193
+ "notes": sum(e["kind"] == "note" for e in entries),
194
+ }
195
+
196
+
197
+ def graders(entries: list[dict[str, Any]]) -> str:
198
+ """Who graded, as precisely as the log knows: the models named on the verdicts and the runtime that carried
199
+ them, else "a model" whose name wasn't recorded. Always from the entries, never from the current
200
+ configuration: a verdict's weight depends on who reached it, and switching runtimes must not relabel it.
201
+ """
202
+ verdicts = [e for e in entries if e["kind"] in ("assessment", "teachback_assessment")]
203
+ if not verdicts:
204
+ return "nobody"
205
+ models = sorted({e["model"] for e in verdicts if e.get("model")})
206
+ runtimes = sorted({e["runtime"] for e in verdicts if e.get("runtime")})
207
+ who = ", ".join(models) if models else "a model not named in the log"
208
+ via = f" via {', '.join(runtimes)}" if runtimes else ""
209
+ return who + via
210
+
211
+
212
+ def _handoff(entries: list[dict[str, Any]]) -> str:
213
+ """One line for whoever picks this up next (a deep review): where understanding is solid and where it isn't."""
214
+ focus = {e["qid"]: e.get("focus") or "" for e in entries if e["kind"] == "question"}
215
+ verdict = {e["qid"]: e["verdict"] for e in entries if e["kind"] == "assessment"}
216
+ answered = {e["qid"] for e in entries if e["kind"] == "answer"}
217
+
218
+ def names(qids: list[str]) -> str:
219
+ return ", ".join(f"{q} ({focus[q]})" if focus.get(q) else q for q in qids)
220
+
221
+ right = [q for q, v in verdict.items() if v == "correct"]
222
+ shaky = [q for q, v in verdict.items() if v != "correct"]
223
+ open_ = [q for q in focus if q not in answered]
224
+ parts = []
225
+ if right:
226
+ parts.append(f"solid on {names(right)}")
227
+ if shaky:
228
+ parts.append(f"revisit {names(shaky)}")
229
+ if open_:
230
+ parts.append(f"unanswered {names(open_)}")
231
+ teach = [e for e in entries if e["kind"] == "teachback_assessment"]
232
+ if teach and teach[-1].get("gaps"):
233
+ parts.append("teach-back gaps: " + "; ".join(teach[-1]["gaps"]))
234
+ return "; ".join(parts) + "." if parts else ""
235
+
236
+
237
+ def _quote(text: str) -> str:
238
+ return "\n".join("> " + line for line in text.strip().splitlines())
239
+
240
+
241
+ def render_appendix(entries: list[dict[str, Any]]) -> str:
242
+ """Markdown for the end of the brief. Unanswered questions don't show their expected points."""
243
+ if not entries:
244
+ return ""
245
+ s = summarize(entries)
246
+ out = [MARKER, "", "## 9. Study log (evidence of understanding)", ""]
247
+ if s["assessed"]:
248
+ score = f"{s['correct']} correct, {s['partial']} partial, {s['incorrect']} incorrect of {s['assessed']} assessed by {graders(entries)}"
249
+ elif s["answered"]:
250
+ aided = s["answered"] - s["unaided"]
251
+ score = f"{s['answered']} answered, not graded" + (f" ({aided} after a hint or briefing)" if aided else "")
252
+ else:
253
+ score = "no answers yet"
254
+ teach = s["teachback"] or ("written, not graded" if s["teachbacks"] else "not yet")
255
+ out.append(f"Quiz: {score}. Predictions: {s['predictions']}. Teach-back: {teach}. Findings: {s['findings']}.\n")
256
+ handoff = _handoff(entries)
257
+ if handoff:
258
+ out.append(f"**Handoff:** {handoff}\n")
259
+ if s["briefed"]:
260
+ first_brief = next(e["id"] for e in entries if e["kind"] == "chat" and e.get("action") == "brief")
261
+ first_quiz = next((e["id"] for e in entries if e["kind"] == "answer"), None)
262
+ when = (
263
+ "before answering any quiz question"
264
+ if first_quiz is None or first_brief < first_quiz
265
+ else "after starting the quiz"
266
+ )
267
+ out.append(f"Asked for a briefing {when}, so treat later answers as informed by it.\n")
268
+
269
+ def section(title: str, kinds: tuple[str, ...]) -> list[dict[str, Any]]:
270
+ picked = [e for e in entries if e["kind"] in kinds]
271
+ if picked:
272
+ if out[-1] != "":
273
+ out.append("")
274
+ out.append(f"### {title}\n")
275
+ return picked
276
+
277
+ out.extend(
278
+ f"- {e['ts'][:16].replace('T', ' ')}: " + ("_skipped_" if e.get("skipped") else e["text"].strip())
279
+ for e in section("Predictions (before reading)", ("prediction",))
280
+ )
281
+ answers = {e["qid"]: e for e in entries if e["kind"] == "answer"}
282
+ assessments = {e["qid"]: e for e in entries if e["kind"] == "assessment"}
283
+ reflections: dict[str | None, list[dict[str, Any]]] = {}
284
+ for e in entries:
285
+ if e["kind"] == "reflection":
286
+ reflections.setdefault(e.get("qid"), []).append(e)
287
+ for q in section("Quiz", ("question",)):
288
+ out.append(
289
+ f"**{q['qid']}.** {q['question'].strip()}"
290
+ + (f" _(refs: {', '.join(q.get('refs') or [])})_" if q.get("refs") else "")
291
+ + (f" _(asked by {q['by']})_" if q["by"] != MODEL else "")
292
+ )
293
+ if q["qid"] in answers:
294
+ a = answers[q["qid"]]
295
+ aided = ", ".join(f"after a {x}" for x in a.get("aided") or [])
296
+ out.append(_quote(a["text"]) + (f"\n\n_({aided})_" if aided else ""))
297
+ if q["qid"] in assessments:
298
+ a = assessments[q["qid"]]
299
+ evidence = f" Evidence: {', '.join(a.get('evidence') or [])}." if a.get("evidence") else ""
300
+ out.append(f"\n**{a['verdict'].capitalize()}.** {a['feedback'].strip()}{evidence}")
301
+ out.extend(f"\n_What I missed:_ {r['text'].strip()}" for r in reflections.get(q["qid"], []))
302
+ out.append("")
303
+ for e in section("Teach-back", ("teachback", "teachback_assessment")):
304
+ out.append(
305
+ _quote(e["text"])
306
+ if e["kind"] == "teachback"
307
+ else f"**{e['verdict'].capitalize()}.** {e['feedback'].strip()}"
308
+ )
309
+ out.append("")
310
+ out.extend(f"_What I missed:_ {r['text'].strip()}\n" for r in reflections.get(None, []))
311
+ for e in section("Findings", ("finding",)):
312
+ where = f"`{e['path']}:{e.get('line') or '?'}` " if e.get("path") else ""
313
+ out.append(f"- [{e['severity']}] {where}{e['summary'].strip()} _({e['by']})_")
314
+ for e in section("Pinned notes", ("note",)):
315
+ who = "pinned from the conversation" if e.get("pinned") else e["by"]
316
+ out.append(f"- {e['text'].strip()} _({who}{', ' + e['section'] if e.get('section') else ''})_")
317
+ return "\n".join(out).rstrip() + "\n"
318
+
319
+
320
+ def refresh_brief(cfg: Config, number: int) -> None:
321
+ """Rewrite the study section at the end of the brief after the log changes."""
322
+ path = cfg.briefs_dir / f"pr-{number}.md"
323
+ if not path.exists():
324
+ return
325
+ base = path.read_text(encoding="utf-8").split(MARKER, 1)[0].rstrip() + "\n"
326
+ appendix = render_appendix(load(cfg, number))
327
+ path.write_text(base + ("\n" + appendix if appendix else ""), encoding="utf-8")
readthrough/system.py ADDED
@@ -0,0 +1,205 @@
1
+ """OS integration: the ``readthrough://`` URL handler and the daily refresh task.
2
+
3
+ Windows is implemented directly (HKCU registry and Task Scheduler, no admin rights needed). On other
4
+ platforms the functions explain what to set up by hand.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import subprocess
10
+ import sys
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from readthrough.review import URL_SCHEME
15
+
16
+ if sys.platform == "win32":
17
+ import winreg
18
+
19
+ TASK_NAME = "readthrough"
20
+ SERVER_TASK_NAME = "readthrough-server"
21
+ PROTOCOL_KEY = rf"Software\Classes\{URL_SCHEME}"
22
+
23
+ _DAYS = {"daily": None, "weekdays": "Monday,Tuesday,Wednesday,Thursday,Friday"}
24
+
25
+
26
+ def windowless_python() -> Path:
27
+ """pythonw.exe from the same environment, so background launches don't flash a console."""
28
+ exe = Path(sys.executable)
29
+ if sys.platform == "win32":
30
+ candidate = exe.with_name("pythonw.exe")
31
+ if candidate.exists():
32
+ return candidate
33
+ return exe
34
+
35
+
36
+ def handler_command() -> str:
37
+ return f'"{windowless_python()}" -m readthrough handle-url "%1"'
38
+
39
+
40
+ def _not_windows(what: str, manual: str) -> NotImplementedError:
41
+ """The error for an installer that's automated on Windows only. Callers ``raise`` it inside a platform check."""
42
+ return NotImplementedError(f"{what} is automated on Windows only. On this platform:\n{manual}")
43
+
44
+
45
+ # ---------------------------------------------------------------- URL protocol
46
+
47
+
48
+ def install_protocol() -> str:
49
+ if sys.platform != "win32":
50
+ raise _not_windows(
51
+ "Registering the readthrough:// handler",
52
+ " macOS: wrap `readthrough handle-url` in an app bundle with CFBundleURLSchemes = readthrough.\n"
53
+ " Linux: add a .desktop file with MimeType=x-scheme-handler/readthrough and run\n"
54
+ " `xdg-mime default readthrough.desktop x-scheme-handler/readthrough`.",
55
+ )
56
+ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, PROTOCOL_KEY) as key:
57
+ winreg.SetValueEx(key, None, 0, winreg.REG_SZ, "URL:Readthrough")
58
+ winreg.SetValueEx(key, "URL Protocol", 0, winreg.REG_SZ, "")
59
+ with winreg.CreateKey(winreg.HKEY_CURRENT_USER, PROTOCOL_KEY + r"\shell\open\command") as key:
60
+ winreg.SetValueEx(key, None, 0, winreg.REG_SZ, handler_command())
61
+ return handler_command()
62
+
63
+
64
+ def registered_protocol_command() -> str | None:
65
+ if sys.platform != "win32":
66
+ return None
67
+ try:
68
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, PROTOCOL_KEY + r"\shell\open\command") as key:
69
+ return str(winreg.QueryValueEx(key, "")[0]) # "" is the key's default value
70
+ except OSError:
71
+ return None
72
+
73
+
74
+ def uninstall_protocol() -> bool:
75
+ if sys.platform != "win32" or registered_protocol_command() is None:
76
+ return False
77
+ for sub in (r"\shell\open\command", r"\shell\open", r"\shell", ""):
78
+ winreg.DeleteKey(winreg.HKEY_CURRENT_USER, PROTOCOL_KEY + sub)
79
+ return True
80
+
81
+
82
+ # ---------------------------------------------------------------- scheduled refresh
83
+
84
+
85
+ @dataclass
86
+ class ScheduleStatus:
87
+ installed: bool
88
+ state: str = ""
89
+ next_run: str = ""
90
+ last_run: str = ""
91
+ last_result: str = ""
92
+
93
+
94
+ def _powershell(script: str) -> subprocess.CompletedProcess[str]:
95
+ # PowerShell writes its console code page by default; ask for UTF-8 so task names round-trip.
96
+ script = "[Console]::OutputEncoding = [Text.Encoding]::UTF8\n" + script
97
+ return subprocess.run(
98
+ ["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
99
+ capture_output=True,
100
+ text=True,
101
+ encoding="utf-8",
102
+ errors="replace",
103
+ creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0,
104
+ check=False,
105
+ )
106
+
107
+
108
+ def _ps_quote(text: str) -> str:
109
+ return "'" + text.replace("'", "''") + "'"
110
+
111
+
112
+ def install_schedule(*, at: str, days: str, open_mode: str, home: Path | None = None) -> str:
113
+ cron_days = "1-5" if days == "weekdays" else "*"
114
+ hour, minute = at.split(":")
115
+ if sys.platform != "win32":
116
+ raise _not_windows(
117
+ "The daily refresh",
118
+ f" Add this line with `crontab -e`:\n {int(minute)} {int(hour)} * * {cron_days} readthrough build --all --open {open_mode}",
119
+ )
120
+ trigger = f"New-ScheduledTaskTrigger -Daily -At {_ps_quote(at)}"
121
+ if _DAYS[days]:
122
+ trigger = f"New-ScheduledTaskTrigger -Weekly -DaysOfWeek {_DAYS[days]} -At {_ps_quote(at)}"
123
+ settings = "-ExecutionTimeLimit (New-TimeSpan -Minutes 30)"
124
+ return _register_task(
125
+ TASK_NAME,
126
+ _module_args(home, f"build --all --open {open_mode}"),
127
+ trigger,
128
+ settings,
129
+ "Refresh every readthrough repo and open the dashboard when something needs you",
130
+ )
131
+
132
+
133
+ def install_server_task(*, home: Path | None = None) -> str:
134
+ """Run `readthrough serve` at logon, restart it if it dies, and start it now."""
135
+ if sys.platform != "win32":
136
+ raise _not_windows(
137
+ "Starting the live server at logon",
138
+ " Run `readthrough serve` from a launchd agent (macOS) or a systemd user service (Linux).",
139
+ )
140
+ trigger = "New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name)"
141
+ settings = "-ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew"
142
+ command = _register_task(
143
+ SERVER_TASK_NAME, _module_args(home, "serve"), trigger, settings, "Live Readthrough dashboard"
144
+ )
145
+ _powershell(f"Start-ScheduledTask -TaskName {_ps_quote(SERVER_TASK_NAME)}")
146
+ return command
147
+
148
+
149
+ def _module_args(home: Path | None, command: str) -> str:
150
+ args = "-m readthrough"
151
+ if home is not None:
152
+ args += f' --home "{home}"'
153
+ return f"{args} {command}"
154
+
155
+
156
+ def _register_task(name: str, args: str, trigger: str, settings: str, description: str) -> str:
157
+ script = f"""
158
+ $ErrorActionPreference = 'Stop'
159
+ $action = New-ScheduledTaskAction -Execute {_ps_quote(str(windowless_python()))} -Argument {_ps_quote(args)}
160
+ $trigger = {trigger}
161
+ $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries {settings}
162
+ Register-ScheduledTask -TaskName {_ps_quote(name)} -Action $action -Trigger $trigger -Settings $settings -Description {_ps_quote(description)} -Force | Out-Null
163
+ """
164
+ result = _powershell(script)
165
+ if result.returncode != 0:
166
+ raise RuntimeError(f"Register-ScheduledTask failed: {result.stderr.strip()}")
167
+ return f"{windowless_python()} {args}"
168
+
169
+
170
+ def schedule_status(name: str = TASK_NAME) -> ScheduleStatus:
171
+ if sys.platform != "win32":
172
+ return ScheduleStatus(installed=False)
173
+ script = f"""
174
+ $t = Get-ScheduledTask -TaskName {_ps_quote(name)} -ErrorAction SilentlyContinue
175
+ if (-not $t) {{ exit 3 }}
176
+ $i = $t | Get-ScheduledTaskInfo
177
+ "$($t.State)|$($i.NextRunTime)|$($i.LastRunTime)|$($i.LastTaskResult)"
178
+ """
179
+ result = _powershell(script)
180
+ if result.returncode != 0:
181
+ return ScheduleStatus(installed=False)
182
+ state, next_run, last_run, last_result = [*result.stdout.strip().split("|"), "", "", "", ""][:4]
183
+ return ScheduleStatus(True, state, next_run, last_run, last_result)
184
+
185
+
186
+ def run_schedule_now() -> None:
187
+ result = _powershell(f"Start-ScheduledTask -TaskName {_ps_quote(TASK_NAME)}")
188
+ if result.returncode != 0:
189
+ raise RuntimeError(result.stderr.strip() or "Start-ScheduledTask failed")
190
+
191
+
192
+ def uninstall_schedule(name: str = TASK_NAME) -> bool:
193
+ if not schedule_status(name).installed:
194
+ return False
195
+ _powershell(f"Stop-ScheduledTask -TaskName {_ps_quote(name)}")
196
+ result = _powershell(f"Unregister-ScheduledTask -TaskName {_ps_quote(name)} -Confirm:$false")
197
+ return result.returncode == 0
198
+
199
+
200
+ def message_box(title: str, text: str) -> None:
201
+ """Show errors from windowless launches, which otherwise fail silently."""
202
+ if sys.platform == "win32":
203
+ import ctypes
204
+
205
+ ctypes.windll.user32.MessageBoxW(None, text, title, 0x10)