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.
- readthrough/__init__.py +8 -0
- readthrough/__main__.py +3 -0
- readthrough/agents.py +344 -0
- readthrough/analyze.py +537 -0
- readthrough/assets/SKILL.md +86 -0
- readthrough/assets/defaults.toml +143 -0
- readthrough/assets/profile-reference.md +133 -0
- readthrough/assets/vendor/README.md +22 -0
- readthrough/assets/vendor/cose-base.js +3214 -0
- readthrough/assets/vendor/cytoscape-fcose.js +1549 -0
- readthrough/assets/vendor/cytoscape.min.js +31 -0
- readthrough/assets/vendor/layout-base.js +5230 -0
- readthrough/assets/vendor/licenses/cose-base-LICENSE +21 -0
- readthrough/assets/vendor/licenses/cytoscape-LICENSE +19 -0
- readthrough/assets/vendor/licenses/cytoscape-fcose-LICENSE +19 -0
- readthrough/assets/vendor/licenses/dompurify-LICENSE +202 -0
- readthrough/assets/vendor/licenses/layout-base-LICENSE +21 -0
- readthrough/assets/vendor/licenses/lucide-LICENSE +15 -0
- readthrough/assets/vendor/licenses/marked-LICENSE +44 -0
- readthrough/assets/vendor/lucide-icons.js +36 -0
- readthrough/assets/vendor/marked.umd.js +82 -0
- readthrough/assets/vendor/purify.min.js +7 -0
- readthrough/assets/web/dashboard.css +202 -0
- readthrough/assets/web/dashboard.html +48 -0
- readthrough/assets/web/dashboard.js +937 -0
- readthrough/assets/web/setup.css +57 -0
- readthrough/assets/web/setup.html +28 -0
- readthrough/assets/web/setup.js +342 -0
- readthrough/assets/web/theme.css +36 -0
- readthrough/assistants.py +699 -0
- readthrough/brief.py +145 -0
- readthrough/build.py +616 -0
- readthrough/ci.py +107 -0
- readthrough/cli.py +958 -0
- readthrough/config.py +533 -0
- readthrough/contract.py +394 -0
- readthrough/engine.py +230 -0
- readthrough/faults.py +92 -0
- readthrough/files.py +110 -0
- readthrough/forges/__init__.py +614 -0
- readthrough/forges/azure_devops.py +658 -0
- readthrough/forges/forgejo.py +300 -0
- readthrough/forges/github.py +487 -0
- readthrough/forges/gitlab.py +335 -0
- readthrough/ledger.py +61 -0
- readthrough/limits.py +26 -0
- readthrough/logs.py +169 -0
- readthrough/membership.py +76 -0
- readthrough/model.py +177 -0
- readthrough/onboard.py +551 -0
- readthrough/onboard_model.py +319 -0
- readthrough/process.py +169 -0
- readthrough/profile.py +699 -0
- readthrough/py.typed +0 -0
- readthrough/registry.py +157 -0
- readthrough/review.py +394 -0
- readthrough/rules.py +111 -0
- readthrough/runtimes/__init__.py +297 -0
- readthrough/runtimes/anthropic.py +278 -0
- readthrough/runtimes/copilot.py +313 -0
- readthrough/runtimes/openai.py +307 -0
- readthrough/serve.py +817 -0
- readthrough/study.py +327 -0
- readthrough/system.py +205 -0
- readthrough/terminals.py +168 -0
- readthrough/tuning.py +266 -0
- readthrough/usage.py +169 -0
- readthrough/web_setup.py +635 -0
- readthrough-0.4.0.dist-info/METADATA +123 -0
- readthrough-0.4.0.dist-info/RECORD +73 -0
- readthrough-0.4.0.dist-info/WHEEL +4 -0
- readthrough-0.4.0.dist-info/entry_points.txt +2 -0
- readthrough-0.4.0.dist-info/licenses/LICENSE +21 -0
readthrough/contract.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"""The contract between the server and the page: what crosses the boundary, and the rules it crosses under.
|
|
2
|
+
|
|
3
|
+
Three things cross it, all declared here so that changing one is a deliberate edit that tests check from both
|
|
4
|
+
sides (``tests/test_contract.py``: a real build has exactly these shapes, and the page reads nothing but them):
|
|
5
|
+
|
|
6
|
+
1. **The payload** (``data.json``, ``build.DATA_SCHEMA``). ``Payload`` is the whole file; the page gets it
|
|
7
|
+
inlined at render and again from ``GET /api/data`` after a ``data`` event. ``PullRequestItem`` is one PR.
|
|
8
|
+
2. **Server-Sent Events** on ``GET /api/events`` (``EVENTS``). They are notifications, not state: each carries
|
|
9
|
+
enough to patch the page in place, but the page's truth is always what a GET returns, and after any gap it
|
|
10
|
+
re-fetches rather than reasoning about what it missed (see "Gaps" below).
|
|
11
|
+
3. **The study API** (``StudyState``, ``StudyEvent``): the per-PR study log and the assistant's turn.
|
|
12
|
+
|
|
13
|
+
Rules:
|
|
14
|
+
|
|
15
|
+
* Adding a field is compatible within a schema; the page ignores what it doesn't know. Removing or renaming
|
|
16
|
+
one, or changing what it means, bumps ``DATA_SCHEMA``: the server refuses to serve a newer file and
|
|
17
|
+
rebuilds (``serve.Dashboard.load``), and a page from an older server run reloads itself on ``hello``.
|
|
18
|
+
* The page may add fields of its own to a PR item (``CLIENT_PR_FIELDS``: its view of the ledger); the server
|
|
19
|
+
never writes those names.
|
|
20
|
+
* Study log entries have ids that are unique per PR and strictly increase in the file, so the page
|
|
21
|
+
de-duplicates by id and an event delivered twice is harmless. Only one assistant turn runs per PR at a
|
|
22
|
+
time; a second request is refused with 409 and the page shows the reason.
|
|
23
|
+
* Gaps. An ``EventSource`` reconnects by itself, but events sent meanwhile are gone; a client that can't keep
|
|
24
|
+
up overflows its queue. Either way the page is told, or notices, and re-fetches everything it holds:
|
|
25
|
+
``hello`` with a different ``instance`` means the server restarted (new CSRF token: reload the page);
|
|
26
|
+
``resync`` means the server dropped events for this client; a reconnect after an error reloads too.
|
|
27
|
+
* Errors are JSON ``{"error": message}`` with the HTTP status that says why (400 bad request, 403 wrong host,
|
|
28
|
+
origin, or token, 404 unknown PR or route, 409 busy, 413 too large, 500 with an error id). The page shows
|
|
29
|
+
the message as it is.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from typing import Any, TypedDict
|
|
35
|
+
|
|
36
|
+
# ---------------------------------------------------------------- the payload
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class FileRow(TypedDict):
|
|
40
|
+
path: str
|
|
41
|
+
add: int
|
|
42
|
+
del_: int # JSON key ``del``; see FIELD_NAMES
|
|
43
|
+
type: str # ADDED | MODIFIED | DELETED | RENAMED | COPIED | CHANGED
|
|
44
|
+
comp: str # the component the path belongs to (``other`` when unmapped)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Flag(TypedDict):
|
|
48
|
+
id: str # a rule id (see ``Payload.rules``)
|
|
49
|
+
kind: str # risk | blocker | convention | responsibility | correctness | info | author | you
|
|
50
|
+
msg: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Smell(TypedDict):
|
|
54
|
+
id: str
|
|
55
|
+
kind: str
|
|
56
|
+
path: str
|
|
57
|
+
line: int
|
|
58
|
+
msg: str
|
|
59
|
+
code: str # the offending line, clipped
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class FailingCheck(TypedDict):
|
|
63
|
+
name: str
|
|
64
|
+
url: str | None
|
|
65
|
+
required: bool
|
|
66
|
+
on_main: bool # also failing on the base branch: not this PR's fault
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class CiChecks(TypedDict, total=False):
|
|
70
|
+
state: str # ci.STATES: passing | failing | failing-optional | failing-main | not-run | pending | none | unknown
|
|
71
|
+
failing: list[FailingCheck]
|
|
72
|
+
pending: int
|
|
73
|
+
cancelled: int
|
|
74
|
+
passed: int
|
|
75
|
+
total: int
|
|
76
|
+
required_missing: list[str]
|
|
77
|
+
required_known: bool
|
|
78
|
+
reason: str # only when state is unknown: why the forge couldn't say
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Thread(TypedDict):
|
|
82
|
+
path: str | None
|
|
83
|
+
line: int | None
|
|
84
|
+
outdated: bool
|
|
85
|
+
author: str
|
|
86
|
+
body: str
|
|
87
|
+
body_html: str # third-party HTML: the page runs it through DOMPurify
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Review(TypedDict):
|
|
91
|
+
author: str
|
|
92
|
+
state: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Issue(TypedDict):
|
|
96
|
+
number: int
|
|
97
|
+
title: str
|
|
98
|
+
url: str
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class SessionInfo(TypedDict):
|
|
102
|
+
"""``agents.SessionInfo.payload()``: the PR's primary review session."""
|
|
103
|
+
|
|
104
|
+
id: str
|
|
105
|
+
exists: bool
|
|
106
|
+
updated: int | None
|
|
107
|
+
active: bool | None # None: the agent leaves no trace of whether the session is open
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AgentSession(SessionInfo):
|
|
111
|
+
"""Every session linked to the PR, the primary first (``review.pr_sessions``)."""
|
|
112
|
+
|
|
113
|
+
where: str # "VS Code" | "terminal" | the client name | "other"
|
|
114
|
+
name: str
|
|
115
|
+
agent: str # the agent's registry name
|
|
116
|
+
agent_label: str
|
|
117
|
+
editor_url: str | None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class StudySummary(TypedDict):
|
|
121
|
+
"""``study.summarize``: the log's counts, shown next to the PR and at the top of the Study tab."""
|
|
122
|
+
|
|
123
|
+
questions: int
|
|
124
|
+
answered: int
|
|
125
|
+
unaided: int
|
|
126
|
+
after_hint: int
|
|
127
|
+
after_brief: int
|
|
128
|
+
assessed: int
|
|
129
|
+
correct: int
|
|
130
|
+
partial: int
|
|
131
|
+
incorrect: int
|
|
132
|
+
score: float | None
|
|
133
|
+
predictions: int
|
|
134
|
+
prediction_skipped: bool
|
|
135
|
+
briefed: bool
|
|
136
|
+
teachback: str | None
|
|
137
|
+
teachbacks: int
|
|
138
|
+
reflections: int
|
|
139
|
+
findings: int
|
|
140
|
+
notes: int
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class PullRequestItem(TypedDict):
|
|
144
|
+
"""One analysed PR (``analyze.analyze``, plus what the build adds: sessions and the study summary)."""
|
|
145
|
+
|
|
146
|
+
number: int
|
|
147
|
+
title: str
|
|
148
|
+
url: str
|
|
149
|
+
author: str
|
|
150
|
+
author_kind: str
|
|
151
|
+
author_group: str # internal | external | bot | you
|
|
152
|
+
author_association: str
|
|
153
|
+
body: str
|
|
154
|
+
body_html: str
|
|
155
|
+
draft: bool
|
|
156
|
+
created: str
|
|
157
|
+
updated: str
|
|
158
|
+
age_days: float
|
|
159
|
+
idle_days: float
|
|
160
|
+
additions: int
|
|
161
|
+
deletions: int
|
|
162
|
+
changed_files: int
|
|
163
|
+
head: str
|
|
164
|
+
base: str
|
|
165
|
+
review_decision: str
|
|
166
|
+
mergeable: str
|
|
167
|
+
ci_state: str
|
|
168
|
+
ci_checks: CiChecks
|
|
169
|
+
labels: list[str]
|
|
170
|
+
requested: list[str]
|
|
171
|
+
reviews: list[Review]
|
|
172
|
+
comments: int
|
|
173
|
+
issues: list[Issue]
|
|
174
|
+
files: list[FileRow]
|
|
175
|
+
by_comp: dict[str, int]
|
|
176
|
+
primary: str
|
|
177
|
+
layers: list[str]
|
|
178
|
+
rules: list[str] # names of the instruction files that apply
|
|
179
|
+
flags: list[Flag]
|
|
180
|
+
smells: list[Smell]
|
|
181
|
+
unresolved: list[Thread]
|
|
182
|
+
lane: str # mine | draft | blocked | waiting | approved | ready
|
|
183
|
+
minutes: int
|
|
184
|
+
priority: float
|
|
185
|
+
related: list[int]
|
|
186
|
+
session: SessionInfo
|
|
187
|
+
sessions: list[AgentSession]
|
|
188
|
+
study: StudySummary
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
CLIENT_PR_FIELDS = frozenset({"status", "note", "understood", "reviewed"})
|
|
192
|
+
"""What the page adds to a PR item from the ledger (``loadProgress``). Never written by the server."""
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class Component(TypedDict):
|
|
196
|
+
id: str
|
|
197
|
+
label: str
|
|
198
|
+
layer: str
|
|
199
|
+
contract: dict[str, Any] # ``profile.Contract`` as a dict, or {} when the component has none
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class ProfileView(TypedDict):
|
|
203
|
+
repo: str
|
|
204
|
+
title: str
|
|
205
|
+
layers: list[Any]
|
|
206
|
+
author_kinds: dict[str, Any]
|
|
207
|
+
contracts_source: str | None
|
|
208
|
+
overlap_non_source: list[str]
|
|
209
|
+
drafted_by: str | None
|
|
210
|
+
origin: str
|
|
211
|
+
onboarded: str | None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class Instruction(TypedDict):
|
|
215
|
+
name: str
|
|
216
|
+
patterns: list[str]
|
|
217
|
+
url: str
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class Overlap(TypedDict):
|
|
221
|
+
a: int
|
|
222
|
+
b: int
|
|
223
|
+
files: list[str]
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
class PlanSession(TypedDict):
|
|
227
|
+
component: str
|
|
228
|
+
label: str
|
|
229
|
+
prs: list[int]
|
|
230
|
+
minutes: int
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class News(TypedDict):
|
|
234
|
+
since: str | None
|
|
235
|
+
opened: list[int]
|
|
236
|
+
closed: list[dict[str, Any]] # {number, title}
|
|
237
|
+
needs_you: list[int]
|
|
238
|
+
changed_after_review: list[int]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class Drift(TypedDict):
|
|
242
|
+
coverage: float
|
|
243
|
+
unmapped: list[Any] # (path, count) pairs
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class BuildWarning(TypedDict):
|
|
247
|
+
code: str
|
|
248
|
+
message: str
|
|
249
|
+
details: list[str]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class Freshness(TypedDict):
|
|
253
|
+
stale_live_hours: float
|
|
254
|
+
stale_snapshot_hours: float
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class Links(TypedDict):
|
|
258
|
+
protocol: bool
|
|
259
|
+
briefs_dir: str
|
|
260
|
+
clone_uri: str | None
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
class ForgeView(TypedDict):
|
|
264
|
+
name: str
|
|
265
|
+
label: str
|
|
266
|
+
pr_noun: str
|
|
267
|
+
url: str
|
|
268
|
+
files_tab: str
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class Payload(TypedDict):
|
|
272
|
+
"""``data.json``: everything the page shows. ``prs`` is the only part a build can't do without."""
|
|
273
|
+
|
|
274
|
+
schema: int
|
|
275
|
+
version: str
|
|
276
|
+
repo: str
|
|
277
|
+
slug: str
|
|
278
|
+
forge: ForgeView
|
|
279
|
+
viewer: str
|
|
280
|
+
generated: str
|
|
281
|
+
profile: ProfileView
|
|
282
|
+
rules: dict[str, dict[str, str]] # rule id -> {source, how}
|
|
283
|
+
components: list[Component]
|
|
284
|
+
instructions: list[Instruction]
|
|
285
|
+
prs: list[PullRequestItem]
|
|
286
|
+
overlaps: list[Overlap]
|
|
287
|
+
sessions: list[PlanSession]
|
|
288
|
+
ledger: dict[str, Any] # PR number (as a string) -> ledger entry
|
|
289
|
+
news: News
|
|
290
|
+
drift: Drift | None
|
|
291
|
+
draft: bool
|
|
292
|
+
warnings: list[BuildWarning]
|
|
293
|
+
stats: dict[str, Any]
|
|
294
|
+
freshness: Freshness
|
|
295
|
+
links: Links
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
# ---------------------------------------------------------------- the page's own settings
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class Live(TypedDict):
|
|
302
|
+
"""Inlined as ``LIVE`` when the page is served (``null`` in a static snapshot)."""
|
|
303
|
+
|
|
304
|
+
token: str # the CSRF token every POST carries as X-Readthrough-Token
|
|
305
|
+
instance: str # changes when the server restarts; a page that sees another one on ``hello`` reloads
|
|
306
|
+
base: str # the repo's URL prefix, /r/<slug>
|
|
307
|
+
repos: list[dict[str, str]] # {slug, name} for the switcher
|
|
308
|
+
refresh_minutes: int
|
|
309
|
+
status: dict[str, Any] # the dashboard's status, as the ``status`` event carries it
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
CLIENT_LIVE_FIELDS = frozenset({"disconnected"})
|
|
313
|
+
"""What the page adds to ``LIVE`` itself: whether its event stream is down right now."""
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# ---------------------------------------------------------------- events
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
EVENTS = frozenset({"hello", "status", "data", "ledger", "sessions", "study", "resync"})
|
|
320
|
+
"""Server-Sent Event names on /api/events.
|
|
321
|
+
|
|
322
|
+
hello {instance} first, on every (re)connection
|
|
323
|
+
status the dashboard's status building, error, last_build, next_build, warnings, ...
|
|
324
|
+
data {generated} a build finished: fetch /api/data
|
|
325
|
+
ledger the whole ledger a status or note changed
|
|
326
|
+
sessions {number: {session, sessions}} only the PRs whose agent sessions changed
|
|
327
|
+
study a StudyEvent the Study tab's stream
|
|
328
|
+
resync {reason} this client missed events (its queue overflowed): fetch everything again
|
|
329
|
+
"""
|
|
330
|
+
|
|
331
|
+
STUDY_EVENT_TYPES = frozenset({"start", "delta", "tool", "entry", "usage", "done", "error", "reload"})
|
|
332
|
+
"""``StudyEvent.type``. The engine sends start, then any number of delta and tool, entries as they are written,
|
|
333
|
+
usage per model call, and done or error; reload says the log changed outside the dashboard (a terminal appended)."""
|
|
334
|
+
|
|
335
|
+
STUDY_EVENTS_THE_PAGE_MAY_IGNORE = frozenset({"usage"})
|
|
336
|
+
"""Informational: the page needn't react (usage goes to the ledger, which doctor sums)."""
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class StudyEvent(TypedDict, total=False):
|
|
340
|
+
pr: int
|
|
341
|
+
type: str # one of STUDY_EVENT_TYPES
|
|
342
|
+
action: str # start: what the learner asked for
|
|
343
|
+
assistant: str # start: which assistant answers
|
|
344
|
+
text: str # delta: the next piece of the reply
|
|
345
|
+
name: str # tool: the tool the model is calling
|
|
346
|
+
entry: dict[str, Any] # entry: the log entry (a question's expected points withheld until answered)
|
|
347
|
+
summary: dict[str, Any] # entry, reload: the log's StudySummary afterwards
|
|
348
|
+
message: str # error: why the turn failed (also logged as a failure entry)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
# ---------------------------------------------------------------- the study API
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class EngineInfo(TypedDict):
|
|
355
|
+
"""``engine.StudyEngine.engine_info`` plus ``busy``: what answers in the Study tab."""
|
|
356
|
+
|
|
357
|
+
name: str # the assistant: model | rules
|
|
358
|
+
available: bool
|
|
359
|
+
reason: str
|
|
360
|
+
runtime: str | None # the model runtime, when the assistant runs on one
|
|
361
|
+
model: str | None # the model configured for it, when the runtime names one up front
|
|
362
|
+
describe: str # the runtime's own description
|
|
363
|
+
busy: bool # a turn is running for this PR
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class StudyState(TypedDict):
|
|
367
|
+
"""``GET /api/study/<n>``."""
|
|
368
|
+
|
|
369
|
+
entries: list[dict[str, Any]] # study log entries, public form (``engine.public_entries``)
|
|
370
|
+
summary: dict[str, Any] # StudySummary
|
|
371
|
+
engine: EngineInfo
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
STUDY_ADD_KINDS = frozenset({"prediction", "teachback", "note", "reflection", "finding"})
|
|
375
|
+
"""``POST /api/study/<n>`` body ``kind``: what the learner writes without asking the assistant anything.
|
|
376
|
+
``note`` with ``pinned`` keeps a message in the brief; ``prediction`` with ``skipped`` records skipping it."""
|
|
377
|
+
|
|
378
|
+
STUDY_ASK_ACTIONS = frozenset({"chat", "quiz", "brief", "answer", "teachback", "hint"})
|
|
379
|
+
"""``POST /api/study/<n>/ask`` body ``action`` (``engine.ACTIONS``); ``text`` and ``qid`` as the action needs."""
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# ---------------------------------------------------------------- helpers for the tests
|
|
383
|
+
|
|
384
|
+
FIELD_NAMES = {"del_": "del"} # TypedDict keys that can't be spelled as the JSON key
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def fields(record: type) -> frozenset[str]:
|
|
388
|
+
"""The JSON keys a TypedDict declares."""
|
|
389
|
+
return frozenset(FIELD_NAMES.get(k, k) for k in record.__annotations__)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def required_fields(record: type) -> frozenset[str]:
|
|
393
|
+
required: frozenset[str] = getattr(record, "__required_keys__", frozenset())
|
|
394
|
+
return frozenset(FIELD_NAMES.get(k, k) for k in required)
|
readthrough/engine.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""The study engine: the learner's side of the Study tab, and the loop the assistant runs on.
|
|
2
|
+
|
|
3
|
+
The engine records what the learner did (an answer, a teach-back, a request for a hint), marks the PR
|
|
4
|
+
busy, and hands the turn to the configured assistant (``assistants.py``). Whatever the assistant appends
|
|
5
|
+
is broadcast to open pages as it happens. The engine itself never writes on the assistant's behalf, so
|
|
6
|
+
``by`` in the log is always truthful; the one entry it writes in its own name records a turn that failed.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import logging
|
|
13
|
+
import threading
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from readthrough import assistants, process, runtimes, study
|
|
18
|
+
from readthrough.config import Config
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
Broadcast = Callable[[str, Any], None]
|
|
23
|
+
ACTIONS = ("chat", "quiz", "brief", "answer", "teachback", "hint")
|
|
24
|
+
BUILT_FROM = (
|
|
25
|
+
"assistant",
|
|
26
|
+
"assistant_options",
|
|
27
|
+
"runtime",
|
|
28
|
+
"runtime_options",
|
|
29
|
+
) # the Config fields an assistant is made from
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Busy(RuntimeError):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class StudyEngine:
|
|
37
|
+
"""Owns an asyncio loop on a background thread; the HTTP server calls ``submit`` from its threads."""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
cfg: Config,
|
|
42
|
+
broadcast: Broadcast,
|
|
43
|
+
pr_info: Callable[[int], dict[str, Any] | None],
|
|
44
|
+
components: Callable[[], list[dict[str, Any]]] | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
self.cfg = cfg
|
|
47
|
+
self.broadcast = broadcast
|
|
48
|
+
self.pr_info = pr_info
|
|
49
|
+
self._components = components or (list)
|
|
50
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
51
|
+
self._busy: set[int] = set()
|
|
52
|
+
self._busy_lock = threading.Lock()
|
|
53
|
+
self._assistant: assistants.Assistant | None = None
|
|
54
|
+
self._retired: list[assistants.Assistant] = [] # replaced while a turn was running; stopped once it isn't
|
|
55
|
+
|
|
56
|
+
# ---- the assistant
|
|
57
|
+
|
|
58
|
+
def reconfigure(self, cfg: Config) -> None:
|
|
59
|
+
"""Take a fresh Config for the same repo: config.toml changed under the server (a clone added after the
|
|
60
|
+
first study turn failed for want of one, say). An assistant reads the clone, model, and tuning through
|
|
61
|
+
``harness.cfg`` on every turn, so it stays unless what it was built from changed; then it's replaced,
|
|
62
|
+
and the old one is stopped once no turn is using it."""
|
|
63
|
+
old, self.cfg = self.cfg, cfg
|
|
64
|
+
with self._busy_lock:
|
|
65
|
+
assistant = self._assistant
|
|
66
|
+
if assistant is None or all(getattr(old, f) == getattr(cfg, f) for f in BUILT_FROM):
|
|
67
|
+
return
|
|
68
|
+
self._assistant = None
|
|
69
|
+
self._retired.append(assistant)
|
|
70
|
+
retiring = self._retiring()
|
|
71
|
+
for stale in retiring:
|
|
72
|
+
asyncio.run_coroutine_threadsafe(stale.stop(), self._ensure_loop())
|
|
73
|
+
|
|
74
|
+
def _retiring(self) -> list[assistants.Assistant]:
|
|
75
|
+
"""Under the busy lock: the replaced assistants that can be stopped now that no turn is running."""
|
|
76
|
+
if self._busy:
|
|
77
|
+
return []
|
|
78
|
+
retiring, self._retired = self._retired, []
|
|
79
|
+
return retiring
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def resolved(self) -> assistants.Resolved:
|
|
83
|
+
"""Which assistant is in use and whether it can run, for the page and `doctor`."""
|
|
84
|
+
return assistants.resolve(
|
|
85
|
+
self.cfg.assistant, runtime=self.cfg.runtime, runtime_options=self.cfg.runtime_options
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def assistant(self) -> assistants.Assistant:
|
|
90
|
+
if self._assistant is None:
|
|
91
|
+
self._assistant = assistants.make(
|
|
92
|
+
self, self.cfg.assistant, self.cfg.assistant_options,
|
|
93
|
+
runtime=self.cfg.runtime, runtime_options=self.cfg.runtime_options,
|
|
94
|
+
) # fmt: skip
|
|
95
|
+
return self._assistant
|
|
96
|
+
|
|
97
|
+
def engine_info(self) -> dict[str, Any]:
|
|
98
|
+
"""What answers in the Study tab, for the page: the assistant, whether it can run, and when it runs on a
|
|
99
|
+
model runtime, which one, the model configured for it (if any), and the runtime's own description."""
|
|
100
|
+
resolved = self.resolved
|
|
101
|
+
info: dict[str, Any] = {
|
|
102
|
+
"name": resolved.name, "available": resolved.available, "reason": resolved.reason,
|
|
103
|
+
"runtime": resolved.runtime, "model": None, "describe": "",
|
|
104
|
+
} # fmt: skip
|
|
105
|
+
if resolved.runtime and resolved.available:
|
|
106
|
+
engine = runtimes.make(resolved.runtime, self.cfg.runtime_options)
|
|
107
|
+
info.update(model=self.cfg.study_model or engine.model, describe=engine.describe())
|
|
108
|
+
return info
|
|
109
|
+
|
|
110
|
+
def components(self) -> list[dict[str, Any]]:
|
|
111
|
+
return self._components()
|
|
112
|
+
|
|
113
|
+
# ---- lifecycle
|
|
114
|
+
|
|
115
|
+
def _ensure_loop(self) -> asyncio.AbstractEventLoop:
|
|
116
|
+
if self._loop is None:
|
|
117
|
+
self._loop = asyncio.new_event_loop()
|
|
118
|
+
threading.Thread(target=self._loop.run_forever, daemon=True, name="study-engine").start()
|
|
119
|
+
return self._loop
|
|
120
|
+
|
|
121
|
+
def stop(self) -> None:
|
|
122
|
+
if self._loop is None:
|
|
123
|
+
return
|
|
124
|
+
for assistant in [*self._retired, *([self._assistant] if self._assistant else [])]:
|
|
125
|
+
try:
|
|
126
|
+
asyncio.run_coroutine_threadsafe(assistant.stop(), self._loop).result(timeout=15)
|
|
127
|
+
except Exception:
|
|
128
|
+
log.exception("Study engine shutdown failed")
|
|
129
|
+
self._retired.clear()
|
|
130
|
+
self._loop.call_soon_threadsafe(self._loop.stop)
|
|
131
|
+
|
|
132
|
+
def busy(self, number: int) -> bool:
|
|
133
|
+
return number in self._busy
|
|
134
|
+
|
|
135
|
+
# ---- public entry point
|
|
136
|
+
|
|
137
|
+
def submit(self, number: int, action: str, text: str = "", qid: str | None = None) -> None:
|
|
138
|
+
"""Record what the learner did, then start the assistant's turn about it. Returns immediately."""
|
|
139
|
+
resolved = self.resolved
|
|
140
|
+
if not resolved.available:
|
|
141
|
+
raise RuntimeError(resolved.reason)
|
|
142
|
+
if action not in ACTIONS:
|
|
143
|
+
raise ValueError(f"action must be one of {', '.join(ACTIONS)}")
|
|
144
|
+
if self.pr_info(number) is None:
|
|
145
|
+
raise ValueError(f"#{number} isn't an open PR in the current data")
|
|
146
|
+
# Handler threads call this concurrently (a double-click, two tabs), so claiming the PR must be atomic.
|
|
147
|
+
with self._busy_lock:
|
|
148
|
+
if number in self._busy:
|
|
149
|
+
raise Busy(f"The assistant is still working on #{number}")
|
|
150
|
+
prompt = self._record_and_prompt(number, action, text.strip(), qid)
|
|
151
|
+
self._busy.add(number)
|
|
152
|
+
self.broadcast("study", {"pr": number, "type": "start", "action": action, "assistant": resolved.name})
|
|
153
|
+
turn = assistants.Turn(number, action, text.strip(), qid, prompt)
|
|
154
|
+
asyncio.run_coroutine_threadsafe(self._turn(turn), self._ensure_loop())
|
|
155
|
+
|
|
156
|
+
def _record_and_prompt(self, number: int, action: str, text: str, qid: str | None) -> str:
|
|
157
|
+
if action == "answer":
|
|
158
|
+
if not qid or not text:
|
|
159
|
+
raise ValueError("an answer needs the question id and your answer")
|
|
160
|
+
self.append(number, "answer", by="you", qid=qid, text=text) # study.append tags it with any aids
|
|
161
|
+
return f"My answer to {qid}:\n\n{text}\n\nAssess it with assess_answer."
|
|
162
|
+
if action == "teachback":
|
|
163
|
+
if not text:
|
|
164
|
+
raise ValueError("write your teach-back first")
|
|
165
|
+
self.append(number, "teachback", by="you", text=text)
|
|
166
|
+
return (
|
|
167
|
+
"Here is my teach-back of the whole PR, as if I were briefing a teammate:\n\n"
|
|
168
|
+
f"{text}\n\nAssess it with assess_teachback: name the specific gaps or misunderstandings."
|
|
169
|
+
)
|
|
170
|
+
if action == "quiz":
|
|
171
|
+
self.append(number, "chat", by="you", role="user", text=text or "Quiz me.")
|
|
172
|
+
return (text + "\n\n" if text else "") + "Ask me the next quiz question."
|
|
173
|
+
if action == "brief":
|
|
174
|
+
self.append(number, "chat", by="you", role="user", text="Brief me.", action="brief")
|
|
175
|
+
return (
|
|
176
|
+
"Brief me on this PR before I dig in: what it changes and why, then the things most worth "
|
|
177
|
+
"paying attention to as a reviewer, each with path:line. No quiz question this turn."
|
|
178
|
+
)
|
|
179
|
+
if action == "hint":
|
|
180
|
+
text = f"Hint for {qid}" if qid else "Hint, please."
|
|
181
|
+
self.append(number, "chat", by="you", role="user", text=text, action="hint", qid=qid)
|
|
182
|
+
return f"Give me a hint for {qid}, without the answer." if qid else "Give me a hint, without the answer."
|
|
183
|
+
if not text:
|
|
184
|
+
raise ValueError("type a message first")
|
|
185
|
+
self.append(number, "chat", by="you", role="user", text=text)
|
|
186
|
+
return text
|
|
187
|
+
|
|
188
|
+
def append(self, number: int, kind: str, *, by: str, **fields: Any) -> dict[str, Any]:
|
|
189
|
+
"""Append to the log, refresh the brief, and tell open pages. Assistants write through here too."""
|
|
190
|
+
entry = study.append(self.cfg, number, kind, by=by, **fields)
|
|
191
|
+
study.refresh_brief(self.cfg, number)
|
|
192
|
+
entries = study.load(self.cfg, number)
|
|
193
|
+
self.broadcast(
|
|
194
|
+
"study",
|
|
195
|
+
{"pr": number, "type": "entry", "entry": public_entry(entry, entries), "summary": study.summarize(entries)},
|
|
196
|
+
)
|
|
197
|
+
return entry
|
|
198
|
+
|
|
199
|
+
async def _turn(self, turn: assistants.Turn) -> None:
|
|
200
|
+
try:
|
|
201
|
+
assistant = self.assistant
|
|
202
|
+
await assistant.turn(turn)
|
|
203
|
+
self.broadcast("study", {"pr": turn.number, "type": "done"})
|
|
204
|
+
except Exception as exc:
|
|
205
|
+
log.exception("Study turn for #%d failed", turn.number)
|
|
206
|
+
message = process.redact(str(exc))[:500]
|
|
207
|
+
# Logged as well as broadcast: the request above it would otherwise read as one that was ignored.
|
|
208
|
+
# Named by runtime, never by model: a model that never answered reached nothing.
|
|
209
|
+
resolved = self.resolved
|
|
210
|
+
runtime = {"runtime": resolved.runtime} if resolved.runtime else {}
|
|
211
|
+
self.append(turn.number, "failure", by=study.TOOL, assistant=resolved.name, text=message, **runtime)
|
|
212
|
+
self.broadcast("study", {"pr": turn.number, "type": "error", "message": message})
|
|
213
|
+
finally:
|
|
214
|
+
with self._busy_lock:
|
|
215
|
+
self._busy.discard(turn.number)
|
|
216
|
+
retiring = self._retiring()
|
|
217
|
+
for stale in retiring:
|
|
218
|
+
await stale.stop()
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def public_entry(entry: dict[str, Any], entries: list[dict[str, Any]]) -> dict[str, Any]:
|
|
222
|
+
"""Hide a question's expected points until the learner has answered it."""
|
|
223
|
+
if entry["kind"] != "question":
|
|
224
|
+
return entry
|
|
225
|
+
answered = any(e["kind"] == "answer" and e.get("qid") == entry["qid"] for e in entries)
|
|
226
|
+
return entry if answered else {k: v for k, v in entry.items() if k != "expected_points"}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def public_entries(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
230
|
+
return [public_entry(e, entries) for e in entries]
|