@jesdi/skills 0.0.101 → 0.0.103
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.
- package/package.json +1 -1
- package/skills/babysit-pr/SKILL.md +9 -2
- package/skills/babysit-pr/babysit.py +98 -36
- package/skills/babysit-pr/exam.py +156 -0
- package/skills/babysit-pr/fixtures/exam_host.py +47 -0
- package/skills/babysit-pr/fixtures/gh +107 -11
- package/skills/babysit-pr/test_babysit.py +8 -2
- package/skills/babysit-pr/test_e2e_setup.py +1 -1
- package/skills/babysit-pr/test_exam_merge_gate.py +189 -0
- package/skills/babysit-pr/test_exam_request.py +337 -0
- package/skills/babysit-pr/test_exam_required_check.py +145 -0
- package/skills/babysit-pr/test_exam_wait.py +353 -0
- package/skills/babysit-pr/test_merge_and_handoff.py +12 -6
- package/skills/babysit-pr/test_trusted_merge_risk.py +2 -2
- package/skills/pr-exam/SKILL.md +151 -0
- package/skills/pr-exam/fixtures/README.md +23 -0
- package/skills/pr-exam/fixtures/chat-answer/prompt.md +92 -0
- package/skills/pr-exam/fixtures/chat-answer/reply.md +7 -0
- package/skills/pr-exam/fixtures/chat-answer/turn.json +1 -0
- package/skills/pr-exam/fixtures/delta-new-concept/body.md +9 -0
- package/skills/pr-exam/fixtures/delta-new-concept/diff.patch +82 -0
- package/skills/pr-exam/fixtures/delta-new-concept/exam.json +46 -0
- package/skills/pr-exam/fixtures/delta-new-concept/passed.diff +66 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0001-single-sync-leader.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0002-stale-leader-writes.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0003-fencing-token.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0004-lease-expiry.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0005-injected-monotonic-clock.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0006-leader-lifecycle.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0007-lease-rollback.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/records/0008-sync-blast-radius.md +10 -0
- package/skills/pr-exam/fixtures/delta-new-concept/request.json +43 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/body.md +9 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/diff.patch +66 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/exam.json +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/passed.diff +66 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0001-single-sync-leader.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0002-stale-leader-writes.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0003-fencing-token.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0004-lease-expiry.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0005-injected-monotonic-clock.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0006-leader-lifecycle.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0007-lease-rollback.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/records/0008-sync-blast-radius.md +10 -0
- package/skills/pr-exam/fixtures/delta-nothing-new/request.json +43 -0
- package/skills/pr-exam/fixtures/followup/body.md +9 -0
- package/skills/pr-exam/fixtures/followup/diff.patch +66 -0
- package/skills/pr-exam/fixtures/followup/exam.json +61 -0
- package/skills/pr-exam/fixtures/followup/records/0001-single-sync-leader.md +10 -0
- package/skills/pr-exam/fixtures/followup/records/0002-stale-leader-writes.md +10 -0
- package/skills/pr-exam/fixtures/followup/records/0003-fencing-token.md +10 -0
- package/skills/pr-exam/fixtures/followup/records/0004-lease-expiry.md +10 -0
- package/skills/pr-exam/fixtures/followup/records/0005-injected-monotonic-clock.md +10 -0
- package/skills/pr-exam/fixtures/followup/records/0006-lease-rollback.md +10 -0
- package/skills/pr-exam/fixtures/followup/records/0007-sync-blast-radius.md +10 -0
- package/skills/pr-exam/fixtures/followup/request.json +41 -0
- package/skills/pr-exam/fixtures/grading/answers.json +5 -0
- package/skills/pr-exam/fixtures/grading/attempt.json +10 -0
- package/skills/pr-exam/fixtures/grading/grades.json +14 -0
- package/skills/pr-exam/fixtures/grading/questions.json +26 -0
- package/skills/pr-exam/fixtures/grading/request.json +10 -0
- package/skills/pr-exam/fixtures/tip-choice/prompt.md +97 -0
- package/skills/pr-exam/fixtures/tip-choice/reply.md +1 -0
- package/skills/pr-exam/fixtures/tip-choice/turn.json +1 -0
- package/skills/pr-exam/fixtures/tip-text/prompt.md +97 -0
- package/skills/pr-exam/fixtures/tip-text/reply.md +1 -0
- package/skills/pr-exam/fixtures/tip-text/turn.json +1 -0
- package/skills/pr-exam/fixtures/twelve-concepts/body.md +9 -0
- package/skills/pr-exam/fixtures/twelve-concepts/diff.patch +66 -0
- package/skills/pr-exam/fixtures/twelve-concepts/exam.json +195 -0
- package/skills/pr-exam/fixtures/twelve-concepts/request.json +15 -0
- package/skills/pr-exam/fixtures/typo-readme/body.md +1 -0
- package/skills/pr-exam/fixtures/typo-readme/diff.patch +7 -0
- package/skills/pr-exam/fixtures/typo-readme/exam.json +30 -0
- package/skills/pr-exam/fixtures/typo-readme/request.json +15 -0
- package/skills/pr-exam/pr_exam.py +887 -0
- package/skills/pr-exam/test_config.py +83 -0
- package/skills/pr-exam/test_context.py +174 -0
- package/skills/pr-exam/test_exam_format.py +252 -0
- package/skills/pr-exam/test_flag_shapes.py +18 -0
- package/skills/pr-exam/test_followup_delta.py +90 -0
- package/skills/pr-exam/test_learning_records.py +355 -0
- package/skills/pr-exam/test_record_publication.py +45 -0
- package/skills/pr-exam/test_scoring.py +287 -0
- package/skills/pr-exam/test_served_shapes.py +38 -0
- package/skills/pr-exam/test_setup.py +349 -0
- package/skills/pr-exam/test_skill_fixtures.py +136 -0
- package/skills/pr-exam/test_turn_shapes.py +34 -0
- package/skills-manifest.json +9 -3
|
@@ -0,0 +1,887 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""pr_exam: every deterministic rule of a PR exam, one subcommand each (see `main`).
|
|
3
|
+
|
|
4
|
+
Each command reads files and prints JSON, or exits non-zero with every error on stderr."""
|
|
5
|
+
import argparse
|
|
6
|
+
import datetime
|
|
7
|
+
import fcntl
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import urllib.request
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
KINDS = ["why", "concept", "architecture", "risk", "behaviour"] # highest priority first
|
|
17
|
+
QUESTION_FIELDS = {"id", "concept", "type", "prompt", "options"}
|
|
18
|
+
MAX_QUESTIONS = 8
|
|
19
|
+
SLUG = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def is_slug(v):
|
|
23
|
+
return isinstance(v, str) and bool(SLUG.fullmatch(v))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def nonempty(v):
|
|
27
|
+
return isinstance(v, str) and bool(v.strip())
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def broken(rules):
|
|
31
|
+
"""The message of every (is_broken, message) rule that is broken, in order."""
|
|
32
|
+
return [message for is_broken, message in rules if is_broken]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def rule_of(table, name):
|
|
36
|
+
"""table[name]; None for a name the table does not hold, whatever its JSON type."""
|
|
37
|
+
return table.get(name) if isinstance(name, str) else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def options_ok(options):
|
|
41
|
+
return isinstance(options, list) and all(nonempty(o) for o in options)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def is_object_list(v):
|
|
45
|
+
return isinstance(v, list) and all(isinstance(q, dict) for q in v)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def shape_errors(q):
|
|
49
|
+
"""Served fields must be plain strings, so nothing private can hide inside them."""
|
|
50
|
+
qid = q.get("id")
|
|
51
|
+
return broken((
|
|
52
|
+
(not nonempty(qid), f"question {qid!r}: id must be a non-empty string"),
|
|
53
|
+
(not nonempty(q.get("prompt")), f"question {qid}: prompt must be a non-empty string"),
|
|
54
|
+
(rule_of(QUESTION_TYPES, q.get("type")) is None, f"question {qid}: type must be choice or text"),
|
|
55
|
+
("options" in q and not options_ok(q["options"]), f"question {qid}: options must be non-empty strings"),
|
|
56
|
+
))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def questions_shape_errors(questions):
|
|
60
|
+
if not is_object_list(questions):
|
|
61
|
+
return ["questions must be a list of objects"]
|
|
62
|
+
return [e for q in questions for e in shape_errors(q)]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def served_errors(exam):
|
|
66
|
+
"""Every field `public` copies must have its plain shape, so no answer can ride inside one."""
|
|
67
|
+
if not isinstance(exam, dict):
|
|
68
|
+
return ["exam must be a JSON object"]
|
|
69
|
+
version = exam.get("version")
|
|
70
|
+
return broken((
|
|
71
|
+
(type(version) is not int or version != 1, "version must be 1"),
|
|
72
|
+
*((not nonempty(exam.get(f)), f"{f} must be a non-empty string") for f in ("repo", "head_sha")),
|
|
73
|
+
(type(exam.get("pr")) is not int, "pr must be an integer"),
|
|
74
|
+
)) + questions_shape_errors(exam.get("questions"))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def request_errors(exam, request):
|
|
78
|
+
"""The exam answers the request it was generated for."""
|
|
79
|
+
mode = exam.get("mode")
|
|
80
|
+
return broken((
|
|
81
|
+
(rule_of(MODE_RULES, mode) is None, "mode must be first, followup or delta"),
|
|
82
|
+
("mode" in request and mode != request["mode"],
|
|
83
|
+
f"mode {mode!r} differs from the request's {request.get('mode')!r}"),
|
|
84
|
+
*((exam.get(f) != request.get(f), f"{f} differs from the request's") for f in ("repo", "pr", "head_sha")),
|
|
85
|
+
))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def concept_errors(concepts):
|
|
89
|
+
"""Each concept: a slug id, a known kind, listed once."""
|
|
90
|
+
errors, seen = [], set()
|
|
91
|
+
for c in concepts:
|
|
92
|
+
cid = c.get("id")
|
|
93
|
+
errors += broken((
|
|
94
|
+
(not is_slug(cid), f"concept {cid!r}: id must be a slug (lowercase letters, digits, single hyphens)"),
|
|
95
|
+
(c.get("kind") not in KINDS, f"concept {cid}: kind must be one of {KINDS}"),
|
|
96
|
+
(cid in seen, f"concept {cid}: listed twice"),
|
|
97
|
+
))
|
|
98
|
+
seen.add(cid)
|
|
99
|
+
return errors
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def count_errors(mode, n):
|
|
103
|
+
"""Every exam asks at least its mode's minimum, and at most MAX_QUESTIONS."""
|
|
104
|
+
low, _ = rule_of(MODE_RULES, mode) or (1, None)
|
|
105
|
+
return [] if low <= n <= MAX_QUESTIONS else [f"question count {n} is outside the allowed range"]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def choice_options(q):
|
|
109
|
+
"""A choice question's options when they are a list of two or more, else None."""
|
|
110
|
+
options = q.get("options")
|
|
111
|
+
return options if isinstance(options, list) and len(options) >= 2 else None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def choice_options_errors(q):
|
|
115
|
+
qid, options = q.get("id"), choice_options(q)
|
|
116
|
+
if options is None:
|
|
117
|
+
return [f"question {qid}: choice needs a list of options"]
|
|
118
|
+
return broken((
|
|
119
|
+
(len({len(str(o).split()) for o in options}) > 1, f"question {qid}: options differ in word count"),
|
|
120
|
+
(len(set(map(str, options))) != len(options), f"question {qid}: options contain duplicates"),
|
|
121
|
+
))
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def text_options_errors(q):
|
|
125
|
+
return [f"question {q.get('id')}: text question must not have options"] if "options" in q else []
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def is_index(a, options):
|
|
129
|
+
return isinstance(a, int) and not isinstance(a, bool) and options is not None and 0 <= a < len(options)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def choice_key_errors(q, entry):
|
|
133
|
+
qid = q.get("id")
|
|
134
|
+
return broken((
|
|
135
|
+
(not is_index(entry.get("answer"), choice_options(q)), f"key {qid}: answer is not an index into options"),
|
|
136
|
+
("rubric" in entry, f"key {qid}: choice question must not have a rubric"),
|
|
137
|
+
))
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def text_key_errors(q, entry):
|
|
141
|
+
qid, rubric = q.get("id"), entry.get("rubric")
|
|
142
|
+
rubric = rubric if isinstance(rubric, dict) else {}
|
|
143
|
+
return broken((
|
|
144
|
+
*((not nonempty(rubric.get(part)), f"key {qid}: rubric.{part} must be non-empty")
|
|
145
|
+
for part in ("pass", "partial")),
|
|
146
|
+
("answer" in entry, f"key {qid}: text question must not have an answer"),
|
|
147
|
+
))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# Per question type: the rule of its options, and the rule of its key entry. A choice has distinct
|
|
151
|
+
# options of one word count, an answer index and no rubric; a text has no options, a rubric and no answer.
|
|
152
|
+
QUESTION_TYPES = {"choice": (choice_options_errors, choice_key_errors),
|
|
153
|
+
"text": (text_options_errors, text_key_errors)}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def type_rules(q):
|
|
157
|
+
"""(options rule, key rule) of the question's type; a type that is none of them has no rule to break."""
|
|
158
|
+
return rule_of(QUESTION_TYPES, q.get("type")) or (lambda q: [], lambda q, entry: [])
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def key_errors(q, key, diff):
|
|
162
|
+
"""The question's key entry explains it with a hunk of the diff."""
|
|
163
|
+
qid = q.get("id")
|
|
164
|
+
entry = key.get(qid)
|
|
165
|
+
if not isinstance(entry, dict):
|
|
166
|
+
return [f"key {qid}: entry must be an object"] if qid in key else []
|
|
167
|
+
hunk = entry.get("hunk")
|
|
168
|
+
return broken((
|
|
169
|
+
*((not nonempty(entry.get(f)), f"key {qid}: {f} must be non-empty") for f in ("explanation", "hunk")),
|
|
170
|
+
(nonempty(hunk) and hunk not in diff, f"key {qid}: hunk is not in the diff"),
|
|
171
|
+
)) + type_rules(q)[1](q, entry)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def question_errors(q, kinds, key, diff):
|
|
175
|
+
qid, extra = q.get("id"), set(q) - QUESTION_FIELDS
|
|
176
|
+
return broken((
|
|
177
|
+
(bool(extra), f"question {qid}: unexpected field(s) {sorted(extra)}"),
|
|
178
|
+
(q.get("concept") not in kinds, f"question {qid}: concept {q.get('concept')!r} is not a listed concept"),
|
|
179
|
+
)) + type_rules(q)[0](q) + key_errors(q, key, diff)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def learned_errors(q, learned):
|
|
183
|
+
"""A concept learned as skip is not asked; one learned as due is asked as choice only."""
|
|
184
|
+
concept = q.get("concept")
|
|
185
|
+
state = learned.get(concept)
|
|
186
|
+
return broken((
|
|
187
|
+
(state == "skip", f"concept {concept}: learned as skip, so it may not be asked"),
|
|
188
|
+
(state == "due" and q.get("type") != "choice", f"concept {concept}: learned as due, so it may not be asked as text"),
|
|
189
|
+
))
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def question_list_errors(questions, kinds, key, diff, learned):
|
|
193
|
+
"""Per question, in order: its concept asked once, its own rules and key, its learned state."""
|
|
194
|
+
errors, seen = [], set()
|
|
195
|
+
for q in questions:
|
|
196
|
+
if q.get("concept") in seen:
|
|
197
|
+
errors.append(f"concept {q.get('concept')}: asked by more than one question")
|
|
198
|
+
seen.add(q.get("concept"))
|
|
199
|
+
errors += question_errors(q, kinds, key, diff) + learned_errors(q, learned)
|
|
200
|
+
return errors
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def duplicate_id_errors(qids):
|
|
204
|
+
return [f"question {qid}: id used more than once" for qid in {i for i in qids if qids.count(i) > 1}]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def key_match_errors(qids, key):
|
|
208
|
+
"""One key entry per question, none for anything else."""
|
|
209
|
+
return ([f"key: no entry for question {qid}" for qid in qids if qid not in key]
|
|
210
|
+
+ [f"key: entry {qid} matches no question" for qid in key if qid not in qids])
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def misconception_errors(learned, asked, kinds, n):
|
|
214
|
+
"""With room left, a recorded misconception that is not a listed concept is asked."""
|
|
215
|
+
if n >= MAX_QUESTIONS:
|
|
216
|
+
return []
|
|
217
|
+
covered = asked | set(kinds)
|
|
218
|
+
return [f"concept {cid}: recorded misconception is not asked"
|
|
219
|
+
for cid, state in learned.items() if state == "misconception" and cid not in covered]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
RANK = {k: i for i, k in enumerate(KINDS)}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def lowest_asked_rank(kinds, asked):
|
|
226
|
+
return max((RANK[kinds[c]] for c in asked if kinds.get(c) in RANK), default=-1)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def unasked(kinds, asked, learned):
|
|
230
|
+
"""[(id, kind)] of listed concepts of a known kind that no question asks, other than those learned as skip."""
|
|
231
|
+
return [(cid, kind) for cid, kind in kinds.items()
|
|
232
|
+
if not (cid in asked or kind not in RANK or learned.get(cid) == "skip")]
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def unasked_errors(kinds, asked, learned, n):
|
|
236
|
+
"""With room left every listed concept is asked; when full, none dropped outranks one asked."""
|
|
237
|
+
lowest = lowest_asked_rank(kinds, asked)
|
|
238
|
+
missing = unasked(kinds, asked, learned)
|
|
239
|
+
if n < MAX_QUESTIONS:
|
|
240
|
+
return [f"concept {cid}: not asked, but only {n} of {MAX_QUESTIONS} questions used" for cid, _ in missing]
|
|
241
|
+
return [f"concept {cid}: dropped while a lower-priority concept is asked" for cid, kind in missing
|
|
242
|
+
if lowest > RANK[kind]]
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def coverage_errors(questions, kinds, learned):
|
|
246
|
+
"""Which concepts the exam must ask: recorded misconceptions, then listed concepts by priority."""
|
|
247
|
+
n, asked = len(questions), {q.get("concept") for q in questions}
|
|
248
|
+
return misconception_errors(learned, asked, kinds, n) + unasked_errors(kinds, asked, learned, n)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def asks_why_as_text(questions, kinds):
|
|
252
|
+
return any(q.get("type") == "text" and kinds.get(q.get("concept")) == "why" for q in questions)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def first_errors(questions, kinds, request):
|
|
256
|
+
"""A first exam mixes choice and text, and asks a why concept as text."""
|
|
257
|
+
n = len(questions)
|
|
258
|
+
types = {q.get("type") for q in questions if rule_of(QUESTION_TYPES, q.get("type"))}
|
|
259
|
+
return broken((
|
|
260
|
+
(n >= 2 and types != set(QUESTION_TYPES), "a first exam with 2 or more questions needs both choice and text"),
|
|
261
|
+
(n >= 3 and not asks_why_as_text(questions, kinds),
|
|
262
|
+
"a first exam with 3 or more questions needs a text question on a why concept"),
|
|
263
|
+
))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def followup_concept_errors(questions, only):
|
|
267
|
+
asked = [q.get("concept") for q in questions]
|
|
268
|
+
return ([f"concept {cid}: missed, but no followup question asks it" for cid in only if cid not in asked]
|
|
269
|
+
+ [f"concept {cid}: not in only_concepts, so a followup may not ask it" for cid in set(asked) - set(only)])
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def followup_errors(questions, kinds, request):
|
|
273
|
+
"""A followup asks exactly the missed concepts, each with a prompt not seen before."""
|
|
274
|
+
prior = request.get("prior_prompts", [])
|
|
275
|
+
return followup_concept_errors(questions, request.get("only_concepts", [])) + [
|
|
276
|
+
f"question {q.get('id')}: prompt repeats one of an earlier attempt"
|
|
277
|
+
for q in questions if q.get("prompt") in prior]
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def delta_errors(questions, kinds, request):
|
|
281
|
+
"""A delta lists only concepts no earlier exam covered."""
|
|
282
|
+
prior = request.get("prior_concepts", [])
|
|
283
|
+
return [f"concept {cid}: an earlier exam covered it, so a delta may not list it" for cid in kinds if cid in prior]
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
# Per mode: the fewest questions it may ask, and its own rule over (questions, kinds, request).
|
|
287
|
+
MODE_RULES = {"first": (1, first_errors), "followup": (1, followup_errors), "delta": (0, delta_errors)}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def mode_errors(exam, request, kinds):
|
|
291
|
+
_, rule = rule_of(MODE_RULES, exam.get("mode")) or (None, lambda *args: [])
|
|
292
|
+
return rule(exam["questions"], kinds, request)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def errors_for(exam, request, diff, learned):
|
|
296
|
+
"""Every broken rule of `exam`, one message each."""
|
|
297
|
+
errors = served_errors(exam)
|
|
298
|
+
if not isinstance(exam, dict) or not is_object_list(exam.get("questions")):
|
|
299
|
+
return errors # the rules below walk the questions
|
|
300
|
+
concepts, questions, key = exam.get("concepts", []), exam["questions"], exam.get("key", {})
|
|
301
|
+
kinds = {c.get("id"): c.get("kind") for c in concepts}
|
|
302
|
+
errors += (request_errors(exam, request) + concept_errors(concepts)
|
|
303
|
+
+ count_errors(exam.get("mode"), len(questions))
|
|
304
|
+
+ question_list_errors(questions, kinds, key, diff, learned))
|
|
305
|
+
qids = [q.get("id") for q in questions]
|
|
306
|
+
return (errors + duplicate_id_errors(qids) + key_match_errors(qids, key)
|
|
307
|
+
+ coverage_errors(questions, kinds, learned) + mode_errors(exam, request, kinds))
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def load(path):
|
|
311
|
+
return json.loads(Path(path).read_text())
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def validate(args):
|
|
315
|
+
exam, request = load(args.exam), load(args.request)
|
|
316
|
+
diff = Path(request["diff"]).read_text()
|
|
317
|
+
try:
|
|
318
|
+
learned = learned_states(request["records"], request["today"]) if request.get("records") else {}
|
|
319
|
+
except ValueError as e:
|
|
320
|
+
return fail(e)
|
|
321
|
+
errors = errors_for(exam, request, diff, learned)
|
|
322
|
+
if errors:
|
|
323
|
+
return fail("\n".join(errors))
|
|
324
|
+
print(f"valid: {len(exam['questions'])} questions, {len(exam['concepts'])} concepts")
|
|
325
|
+
return 0
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def bypass_label_errors(labels):
|
|
329
|
+
if not isinstance(labels, dict):
|
|
330
|
+
return ["bypassLabels: must be an object of label to skip or defer"]
|
|
331
|
+
return [f"bypassLabels: {k!r} has mode {m!r}, allowed values: skip, defer"
|
|
332
|
+
for k, m in labels.items() if m not in ("skip", "defer")]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def config_errors(c):
|
|
336
|
+
if not isinstance(c, dict):
|
|
337
|
+
return ["config: must be a JSON object"]
|
|
338
|
+
errors = [f"unknown key: {k}" for k in c if k not in ("enabled", "bypassLabels")]
|
|
339
|
+
if not isinstance(c.get("enabled", True), bool):
|
|
340
|
+
errors.append("enabled: must be true or false")
|
|
341
|
+
return errors + bypass_label_errors(c.get("bypassLabels", {}))
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def config(args):
|
|
345
|
+
path = Path(args.path)
|
|
346
|
+
try:
|
|
347
|
+
c = json.loads(path.read_text()) if path.exists() else {}
|
|
348
|
+
except ValueError as e:
|
|
349
|
+
return fail(f"invalid json in {path}: {e}")
|
|
350
|
+
errors = config_errors(c)
|
|
351
|
+
if errors:
|
|
352
|
+
return fail("\n".join(errors))
|
|
353
|
+
print(json.dumps({"enabled": c.get("enabled", True), "bypassLabels": c.get("bypassLabels", {})}))
|
|
354
|
+
return 0
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
FILE_RE = re.compile(r"^(\d{4,})-(.+)\.md$")
|
|
358
|
+
FIELDS = ("concept", "state", "date", "source", "status")
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def check_record(f):
|
|
362
|
+
"""ValueError naming what is wrong with a record's frontmatter fields."""
|
|
363
|
+
if any(not f.get(k) for k in FIELDS):
|
|
364
|
+
raise ValueError("missing field")
|
|
365
|
+
if f["state"] not in ("demonstrated", "assisted", "misconception"):
|
|
366
|
+
raise ValueError("state")
|
|
367
|
+
datetime.date.fromisoformat(f["date"])
|
|
368
|
+
if not re.fullmatch(r"active|superseded by LR-\d{4,}", f["status"]):
|
|
369
|
+
raise ValueError("status")
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def record_fields(path):
|
|
373
|
+
"""The frontmatter fields of one record; ValueError naming the file when it is malformed."""
|
|
374
|
+
head = path.read_text().split("---")
|
|
375
|
+
f = dict(re.findall(r"^(\w+): *(.*?) *$", head[1] if len(head) > 2 else "", re.M))
|
|
376
|
+
try:
|
|
377
|
+
check_record(f)
|
|
378
|
+
except ValueError as e:
|
|
379
|
+
raise ValueError(f"{path.name}: malformed record ({e})") from None
|
|
380
|
+
return f
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def read_records(directory):
|
|
384
|
+
"""[(number, path, fields)] for every record; ValueError naming the file when one is malformed."""
|
|
385
|
+
out = []
|
|
386
|
+
for path in sorted(Path(directory).glob("*.md")):
|
|
387
|
+
m = FILE_RE.match(path.name)
|
|
388
|
+
if m:
|
|
389
|
+
out.append((int(m.group(1)), path, record_fields(path)))
|
|
390
|
+
return sorted(out, key=lambda r: r[0]) # oldest first: when two records are active, the newest counts
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def learned_states(directory, today):
|
|
394
|
+
today = datetime.date.fromisoformat(today)
|
|
395
|
+
states = {}
|
|
396
|
+
for _, _, f in read_records(directory):
|
|
397
|
+
if f["status"] != "active":
|
|
398
|
+
continue
|
|
399
|
+
if f["state"] == "misconception":
|
|
400
|
+
states[f["concept"]] = "misconception"
|
|
401
|
+
elif f["state"] == "assisted":
|
|
402
|
+
states[f["concept"]] = "due"
|
|
403
|
+
else:
|
|
404
|
+
age = (today - datetime.date.fromisoformat(f["date"])).days
|
|
405
|
+
states[f["concept"]] = "skip" if age < 30 else "due"
|
|
406
|
+
return states
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def learned(args):
|
|
410
|
+
try:
|
|
411
|
+
print(json.dumps(learned_states(args.records, args.today)))
|
|
412
|
+
except ValueError as e:
|
|
413
|
+
return fail(e)
|
|
414
|
+
return 0
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def slug_errors(result):
|
|
418
|
+
return [f"concept {q.get('concept')!r}: not a slug, so it cannot name a record"
|
|
419
|
+
for q in result["questions"] if not is_slug(q.get("concept"))]
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def record(args):
|
|
423
|
+
exam, result = load(args.exam), load(args.result)
|
|
424
|
+
bad = slug_errors(result)
|
|
425
|
+
if bad:
|
|
426
|
+
return fail("\n".join(bad))
|
|
427
|
+
explanations = {qid: k["explanation"] for qid, k in exam["key"].items()}
|
|
428
|
+
source = f"{exam['repo']}#{exam['pr']}"
|
|
429
|
+
Path(args.records).mkdir(parents=True, exist_ok=True)
|
|
430
|
+
# exclusive lock: read, number, supersede and write are one critical section across processes
|
|
431
|
+
with open(Path(args.records) / ".lock", "w") as lock:
|
|
432
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
433
|
+
try:
|
|
434
|
+
existing = read_records(args.records)
|
|
435
|
+
except ValueError as e:
|
|
436
|
+
return fail(e)
|
|
437
|
+
return write_records(args, result, existing, explanations, source)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def publish(path, text):
|
|
441
|
+
"""Write a whole file or nothing: readers never see a partial record."""
|
|
442
|
+
tmp = path.with_name(f".{path.name}.tmp")
|
|
443
|
+
tmp.write_text(text)
|
|
444
|
+
os.replace(tmp, path)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def record_state(q):
|
|
448
|
+
"""The state a question's record takes, or None when it leaves no record (half a point)."""
|
|
449
|
+
if q.get("help") == "bypassed" or q["points"] == 0:
|
|
450
|
+
return "misconception"
|
|
451
|
+
if q["points"] == 1:
|
|
452
|
+
return "assisted" if q.get("help") == "assisted" else "demonstrated"
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def publish_record(args, q, state, n, explanation, source):
|
|
456
|
+
concept = q["concept"]
|
|
457
|
+
publish(Path(args.records) / f"{n:04d}-{concept}.md",
|
|
458
|
+
f"---\nconcept: {concept}\nstate: {state}\ndate: {args.today}\nsource: {source}\n"
|
|
459
|
+
f"status: active\n---\n# {concept}\n\n{explanation}\n")
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def supersede(existing, concept, n):
|
|
463
|
+
"""Mark the concept's active records superseded by LR-n, on disk and in `existing`."""
|
|
464
|
+
for _, path, f in existing:
|
|
465
|
+
if f["concept"] == concept and f["status"] == "active":
|
|
466
|
+
publish(path, re.sub(r"^status: *active *$", f"status: superseded by LR-{n:04d}",
|
|
467
|
+
path.read_text(), count=1, flags=re.M))
|
|
468
|
+
f["status"] = f"superseded by LR-{n:04d}"
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def write_records(args, result, existing, explanations, source):
|
|
472
|
+
n = max([r[0] for r in existing], default=0)
|
|
473
|
+
for q in result["questions"]:
|
|
474
|
+
state = record_state(q)
|
|
475
|
+
if state:
|
|
476
|
+
n += 1
|
|
477
|
+
# The successor is published before its predecessor is superseded: a failure in between
|
|
478
|
+
# leaves two active records, and the newest one counts, so no state is ever lost.
|
|
479
|
+
publish_record(args, q, state, n, explanations.get(q["id"], ""), source)
|
|
480
|
+
supersede(existing, q["concept"], n)
|
|
481
|
+
return 0
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def served(exam):
|
|
485
|
+
"""The projection the exam page may see: no concept, key, answer or rubric."""
|
|
486
|
+
out = {k: exam[k] for k in ("version", "repo", "pr", "head_sha")}
|
|
487
|
+
out["questions"] = [{k: q[k] for k in ("id", "type", "prompt", "options") if k in q} for q in exam["questions"]]
|
|
488
|
+
return out
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def public(args):
|
|
492
|
+
exam = load(args.exam)
|
|
493
|
+
errors = served_errors(exam)
|
|
494
|
+
if errors:
|
|
495
|
+
return fail("\n".join(errors))
|
|
496
|
+
print(json.dumps(served(exam)))
|
|
497
|
+
return 0
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
GRADE_POINTS = {"pass": 1, "partial": 0.5, "fail": 0}
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def grade_errors(grades, texts, bypassed=()):
|
|
504
|
+
"""Only text questions are graded, each pass, partial or fail; a bypassed question's grade is ignored."""
|
|
505
|
+
errors = []
|
|
506
|
+
for qid, g in grades.items():
|
|
507
|
+
if qid in bypassed:
|
|
508
|
+
continue
|
|
509
|
+
if qid not in texts:
|
|
510
|
+
errors.append(f"grade for {qid}: not a text question")
|
|
511
|
+
elif g.get("grade") not in GRADE_POINTS:
|
|
512
|
+
errors.append(f"question {qid}: grade {g.get('grade')!r} is not pass, partial or fail")
|
|
513
|
+
return errors
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
FLAG_KEYS = ("bypassed", "assisted")
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def question_ids(exam):
|
|
520
|
+
return {q["id"] for q in exam["questions"]}
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def flagged(flags):
|
|
524
|
+
return [qid for k in FLAG_KEYS for qid in flags.get(k, [])]
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def flag_shape_errors(flags):
|
|
528
|
+
"""flags.json is an object whose flag collections are lists of question id strings."""
|
|
529
|
+
if not isinstance(flags, dict):
|
|
530
|
+
return ["flags: must be a JSON object"]
|
|
531
|
+
return [f"flags: {k} must be a list of question ids" for k in FLAG_KEYS
|
|
532
|
+
if not (isinstance(flags.get(k, []), list) and all(isinstance(q, str) for q in flags.get(k, [])))]
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def flag_errors(exam, flags):
|
|
536
|
+
return flag_shape_errors(flags) or flag_ref_errors(exam, flags)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def flag_ref_errors(exam, flags):
|
|
540
|
+
"""Every flag key is known, every flagged id is a question, and at most one is bypassed."""
|
|
541
|
+
ids = question_ids(exam)
|
|
542
|
+
errors = [f"flags: unknown key {k!r}" for k in flags if k not in FLAG_KEYS]
|
|
543
|
+
errors += [f"flags: unknown question {qid}" for qid in flagged(flags) if qid not in ids]
|
|
544
|
+
if len(flags.get("bypassed", [])) > 1:
|
|
545
|
+
errors.append("flags: at most one question can be bypassed, got " + ", ".join(flags["bypassed"]))
|
|
546
|
+
return errors
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def answer_errors(exam, answers, grades, bypassed):
|
|
550
|
+
"""Every question not bypassed is answered and, if text, graded pass, partial or fail."""
|
|
551
|
+
texts = {q["id"] for q in exam["questions"] if q["type"] == "text"}
|
|
552
|
+
errors = []
|
|
553
|
+
for q in exam["questions"]:
|
|
554
|
+
if q["id"] not in bypassed:
|
|
555
|
+
errors += broken((
|
|
556
|
+
(q["id"] not in answers, f"question {q['id']}: unanswered"),
|
|
557
|
+
(q["id"] in texts and q["id"] not in grades, f"question {q['id']}: text question has no grade"),
|
|
558
|
+
))
|
|
559
|
+
return errors + grade_errors(grades, texts, bypassed)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def score_errors(exam, answers, grades, flags=None):
|
|
563
|
+
flags = {} if flags is None else flags
|
|
564
|
+
return flag_errors(exam, flags) or answer_errors(exam, answers, grades, flags.get("bypassed", []))
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def points(q, k, answers, grades):
|
|
568
|
+
if q["type"] == "choice":
|
|
569
|
+
return 1 if answers[q["id"]] == k["answer"] else 0
|
|
570
|
+
return GRADE_POINTS[grades[q["id"]]["grade"]]
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def question_result(q, k, answers, grades, help=None):
|
|
574
|
+
"""A question's points; below full points, also its explanation, hunk and (text) grader feedback.
|
|
575
|
+
A bypassed question has no points but carries its explanation and hunk."""
|
|
576
|
+
if help == "bypassed":
|
|
577
|
+
return {"id": q["id"], "concept": q["concept"], "help": help, "explanation": k["explanation"], "hunk": k["hunk"]}
|
|
578
|
+
r = {"id": q["id"], "concept": q["concept"], "points": points(q, k, answers, grades)}
|
|
579
|
+
if r["points"] < 1:
|
|
580
|
+
r.update(explanation=k["explanation"], hunk=k["hunk"])
|
|
581
|
+
if q["type"] == "text":
|
|
582
|
+
r["feedback"] = grades[q["id"]].get("feedback", "")
|
|
583
|
+
if help:
|
|
584
|
+
r["help"] = help
|
|
585
|
+
return r
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def passed(exam, missed, total, maximum):
|
|
589
|
+
"""At least 80% of the points, and no why concept missed."""
|
|
590
|
+
kinds = {c["id"]: c["kind"] for c in exam["concepts"]}
|
|
591
|
+
why_ok = all(kinds.get(c) != "why" for c in missed)
|
|
592
|
+
return total >= 0.8 * maximum and why_ok
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def helped(qid, flags):
|
|
596
|
+
return next((k for k in FLAG_KEYS if qid in flags.get(k, [])), None)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def tally(exam, out):
|
|
600
|
+
"""result.json from the question results; a bypassed question counts toward neither score nor max."""
|
|
601
|
+
counted = [r for r in out if r.get("help") != "bypassed"]
|
|
602
|
+
missed = [r["concept"] for r in counted if r["points"] < 1]
|
|
603
|
+
total = sum(r["points"] for r in counted)
|
|
604
|
+
return {"passed": passed(exam, missed, total, len(counted)), "score": total, "max": len(counted), "questions": out, "missed": missed}
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
def scored(exam, answers, grades, flags=None):
|
|
608
|
+
"""result.json: points per question, the missed concepts, and whether the attempt passed."""
|
|
609
|
+
flags = flags or {}
|
|
610
|
+
return tally(exam, [question_result(q, exam["key"][q["id"]], answers, grades, helped(q["id"], flags)) for q in exam["questions"]])
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def score(args):
|
|
614
|
+
exam, answers, grades = load(args.exam), load(args.answers), load(args.grades)
|
|
615
|
+
flags = load(args.flags) if args.flags else {}
|
|
616
|
+
errors = score_errors(exam, answers, grades, flags)
|
|
617
|
+
if errors:
|
|
618
|
+
return fail("\n".join(errors))
|
|
619
|
+
print(json.dumps(scored(exam, answers, grades, flags)))
|
|
620
|
+
return 0
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
UPGRADE = "Upgrade to GitHub Pro or make this repository public"
|
|
624
|
+
UNPROTECTED = "Branch not protected"
|
|
625
|
+
CHECKS_OFF = "Required status checks not enabled"
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def fail(message):
|
|
629
|
+
print(message, file=sys.stderr)
|
|
630
|
+
return 1
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def gh_api(*args, body=None):
|
|
634
|
+
"""`gh api`, with `body` sent as the JSON request body."""
|
|
635
|
+
return subprocess.run(["gh", "api", *args, *(["--input", "-"] if body is not None else [])],
|
|
636
|
+
input=None if body is None else json.dumps(body), capture_output=True, text=True)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def app_id():
|
|
640
|
+
"""The id of the host's GitHub App: the only sender whose `exam` status counts."""
|
|
641
|
+
host = os.environ.get("PR_EXAM_HOST") # babysit-pr's exam.py reads the same variable for its requests
|
|
642
|
+
if not host:
|
|
643
|
+
raise SystemExit("PR_EXAM_HOST is not set: point it at the pr-exam host")
|
|
644
|
+
try:
|
|
645
|
+
with urllib.request.urlopen(host.rstrip("/") + "/api/exam/host", timeout=30) as r:
|
|
646
|
+
v = json.load(r)["app_id"]
|
|
647
|
+
except Exception as e:
|
|
648
|
+
raise SystemExit(f"the host cannot report its GitHub App id: {e}")
|
|
649
|
+
if type(v) is not int or v <= 0: # GitHub reads -1 as "any app"
|
|
650
|
+
raise SystemExit(f"the host reported a bad App id: {v!r}")
|
|
651
|
+
return v
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def required_checks(rsc):
|
|
655
|
+
"""[{context, app_id}] of a required-status-checks answer; a check named only by context is bound to no app."""
|
|
656
|
+
return rsc.get("checks") or [{"context": c, "app_id": None} for c in rsc.get("contexts", [])]
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
def exam_bound(checks, app=None):
|
|
660
|
+
"""Whether `exam` is among the required `checks`: sent by `app`, or by anyone when no app is given."""
|
|
661
|
+
return any(c["context"] == "exam" and app in (None, c.get("app_id")) for c in checks)
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def add_exam(path, checks, app):
|
|
665
|
+
"""PATCH the required status checks and nothing else: `checks` as they are, plus `exam` from the App."""
|
|
666
|
+
kept = [{"context": c["context"], "app_id": -1 if c.get("app_id") is None else c["app_id"]}
|
|
667
|
+
for c in checks if c["context"] != "exam"] # a check bound to no app goes back as -1, "any app"
|
|
668
|
+
return gh_api("-X", "PATCH", f"{path}/required_status_checks",
|
|
669
|
+
body={"checks": kept + [{"context": "exam", "app_id": app}]})
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def enable_checks(path, app):
|
|
673
|
+
"""A protected branch whose status checks are off: the PATCH turns them on. Where GitHub answers
|
|
674
|
+
404 to it, adding the context creates the sub-resource, and the PATCH then binds `exam` to the App."""
|
|
675
|
+
patched = add_exam(path, [], app)
|
|
676
|
+
if patched.returncode == 0 or "HTTP 404" not in patched.stderr:
|
|
677
|
+
return patched
|
|
678
|
+
added = gh_api("-X", "POST", f"{path}/required_status_checks/contexts", body={"contexts": ["exam"]})
|
|
679
|
+
return added if added.returncode else add_exam(path, [], app)
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def protect(path, app):
|
|
683
|
+
"""An unprotected branch gets a protection holding only `exam`, enforced for admins too."""
|
|
684
|
+
return gh_api("-X", "PUT", path, body={
|
|
685
|
+
"required_status_checks": {"strict": False, "checks": [{"context": "exam", "app_id": app}]},
|
|
686
|
+
"enforce_admins": True, "required_pull_request_reviews": None, "restrictions": None})
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def written(write, where):
|
|
690
|
+
if write.returncode:
|
|
691
|
+
return fail(write.stderr.strip())
|
|
692
|
+
print(f"exam is now required on {where}")
|
|
693
|
+
return 0
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def require_unread(stderr, path, where, app):
|
|
697
|
+
"""The required checks could not be read: a free private repo stays agent-enforced, a branch with
|
|
698
|
+
no protection or no status checks gets them, any other error fails."""
|
|
699
|
+
if UPGRADE in stderr:
|
|
700
|
+
print(f"GitHub will not protect {where.partition('@')[0]}: the exam gate is agent-enforced only")
|
|
701
|
+
return 0
|
|
702
|
+
write = next((w for why, w in ((UNPROTECTED, protect), (CHECKS_OFF, enable_checks)) if why in stderr), None)
|
|
703
|
+
return written(write(path, app), where) if write else fail(stderr.strip())
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def require_exam(got, path, where, app):
|
|
707
|
+
"""Make `exam` from the App a required check, given the read `got` of the branch's required checks."""
|
|
708
|
+
if got.returncode:
|
|
709
|
+
return require_unread(got.stderr, path, where, app)
|
|
710
|
+
checks = required_checks(json.loads(got.stdout))
|
|
711
|
+
if exam_bound(checks, app):
|
|
712
|
+
print(f"exam is already required on {where}")
|
|
713
|
+
return 0
|
|
714
|
+
return written(add_exam(path, checks, app), where)
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
def check_required(got, branch):
|
|
718
|
+
"""`setup --check`: whether `exam` is a required check, whoever sends it. Reads only; unknown is an error."""
|
|
719
|
+
if got.returncode and not any(off in got.stderr for off in (UNPROTECTED, CHECKS_OFF)):
|
|
720
|
+
return fail(got.stderr.strip())
|
|
721
|
+
checks = [] if got.returncode else required_checks(json.loads(got.stdout))
|
|
722
|
+
print(json.dumps({"required": exam_bound(checks), "branch": branch}))
|
|
723
|
+
return 0
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def setup(args):
|
|
727
|
+
app = None if args.check else app_id()
|
|
728
|
+
info = gh_api(f"repos/{args.repo}")
|
|
729
|
+
if info.returncode:
|
|
730
|
+
return fail(info.stderr.strip())
|
|
731
|
+
branch = json.loads(info.stdout)["default_branch"]
|
|
732
|
+
path = f"repos/{args.repo}/branches/{branch}/protection"
|
|
733
|
+
got = gh_api(f"{path}/required_status_checks")
|
|
734
|
+
if args.check:
|
|
735
|
+
return check_required(got, branch)
|
|
736
|
+
return require_exam(got, path, f"{args.repo}@{branch}", app)
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
PROMPT_LIMIT = 400_000
|
|
740
|
+
TURN_KINDS = {"tip": "Tips", "question": "Chat", "general": "Chat"}
|
|
741
|
+
TURN_SHAPES = {"tip": {"question", "tip", "draft", "tips"},
|
|
742
|
+
"question": {"question", "draft", "submitted", "points", "feedback", "thread", "message"},
|
|
743
|
+
"general": {"thread", "message"}}
|
|
744
|
+
TURN_FIELDS = set().union(*TURN_SHAPES.values())
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def is_text_list(v):
|
|
748
|
+
return isinstance(v, list) and all(isinstance(x, str) for x in v)
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
def is_thread(v):
|
|
752
|
+
return isinstance(v, list) and all(isinstance(m, dict) and set(m) == {"role", "text"} and is_text_list(list(m.values())) for m in v)
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
FIELD_TYPES = {"draft": (lambda v: isinstance(v, str), "a string"), "submitted": (lambda v: isinstance(v, str), "a string"),
|
|
756
|
+
"feedback": (lambda v: isinstance(v, str), "a string"), "message": (lambda v: isinstance(v, str), "a string"),
|
|
757
|
+
"points": (lambda v: type(v) in (int, float), "a number"), "tips": (is_text_list, "a list of strings"),
|
|
758
|
+
"thread": (is_thread, "a list of {role, text} strings")}
|
|
759
|
+
|
|
760
|
+
|
|
761
|
+
def skill_section(name):
|
|
762
|
+
m = re.search(rf"^## {name}\n(.*?)(?=^## |\Z)", (Path(__file__).parent / "SKILL.md").read_text(), re.M | re.S)
|
|
763
|
+
if not m:
|
|
764
|
+
raise ValueError(f"SKILL.md has no '## {name}' section")
|
|
765
|
+
return m.group(1).strip()
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def turn_errors(turn, exam):
|
|
769
|
+
"""Each kind of turn has its own fields (TURN_SHAPES), each of its documented type (FIELD_TYPES)."""
|
|
770
|
+
if not isinstance(turn, dict) or turn.get("kind") not in TURN_SHAPES:
|
|
771
|
+
return ["turn kind: must be tip, question or general"]
|
|
772
|
+
return turn_shape_errors(turn) + target_errors(turn, exam) + tip_errors(turn) + reply_errors(turn)
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def turn_shape_errors(turn):
|
|
776
|
+
kind = turn["kind"]
|
|
777
|
+
errors = [f"turn field {f}: unknown" for f in sorted(set(turn) - TURN_FIELDS - {"kind"})]
|
|
778
|
+
errors += [f"a {f} is not allowed on a {kind} turn" for f in sorted((set(turn) & TURN_FIELDS) - TURN_SHAPES[kind])]
|
|
779
|
+
return errors + [f"{f}: must be {what}" for f, (ok, what) in FIELD_TYPES.items() if f in turn and not ok(turn[f])]
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def target_errors(turn, exam):
|
|
783
|
+
"""A tip or question turn names one of the exam's questions."""
|
|
784
|
+
q = turn.get("question")
|
|
785
|
+
return broken(((turn["kind"] != "general" and q not in question_ids(exam), f"question {q}: not in the exam"),))
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def tip_errors(turn):
|
|
789
|
+
t = turn.get("tip")
|
|
790
|
+
return broken(((turn["kind"] == "tip" and (type(t) is not int or not 1 <= t <= 3), f"tip {t}: must be in the range 1-3"),))
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def reply_errors(turn):
|
|
794
|
+
return broken((
|
|
795
|
+
(turn["kind"] != "tip" and "message" not in turn, "message: required on a chat turn"),
|
|
796
|
+
(("points" in turn or "feedback" in turn) and "submitted" not in turn, "points and feedback need a submitted answer"),
|
|
797
|
+
))
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
def key_block(exam, qid):
|
|
801
|
+
q = next(q for q in exam["questions"] if q["id"] == qid)
|
|
802
|
+
return f"Question: {json.dumps(q)}\nKey: {json.dumps(exam['key'][qid])}"
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def turn_parts(turn, exam):
|
|
806
|
+
return target_parts(turn, exam) + (tip_parts(turn) if turn["kind"] == "tip" else chat_parts(turn))
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def target_parts(turn, exam):
|
|
810
|
+
if turn["kind"] == "general":
|
|
811
|
+
return ["All questions:\n" + "\n".join(key_block(exam, q["id"]) for q in exam["questions"])]
|
|
812
|
+
parts = [key_block(exam, turn["question"])]
|
|
813
|
+
if "draft" in turn and "submitted" not in turn: # after submit, the submitted answer replaces the draft
|
|
814
|
+
parts.append(f"Draft: {turn['draft']}")
|
|
815
|
+
return parts
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def tip_parts(turn):
|
|
819
|
+
return [f"Tip number: {turn['tip']}"] + [f"Tip {i}: {t}" for i, t in enumerate(turn.get("tips", []), 1)]
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
CHAT_LABELS = (("submitted", "Submitted answer"), ("points", "Points"), ("feedback", "Feedback"))
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def chat_parts(turn):
|
|
826
|
+
parts = [f"{label}: {turn[k]}" for k, label in CHAT_LABELS if k in turn]
|
|
827
|
+
parts += [f"{m['role']}: {m['text']}" for m in turn.get("thread", [])]
|
|
828
|
+
return parts + [f"Message: {turn['message']}"]
|
|
829
|
+
|
|
830
|
+
|
|
831
|
+
def context(args):
|
|
832
|
+
exam, turn = load(args.exam), load(args.turn)
|
|
833
|
+
errors = turn_errors(turn, exam)
|
|
834
|
+
if errors:
|
|
835
|
+
return fail("\n".join(errors))
|
|
836
|
+
try:
|
|
837
|
+
rules = skill_section(TURN_KINDS[turn["kind"]])
|
|
838
|
+
except ValueError as e:
|
|
839
|
+
return fail(e)
|
|
840
|
+
prompt = "\n\n".join([rules, "Diff:\n" + Path(args.diff).read_text(), "PR body:\n" + Path(args.body).read_text(),
|
|
841
|
+
*turn_parts(turn, exam)])
|
|
842
|
+
if len(prompt) > PROMPT_LIMIT:
|
|
843
|
+
return fail(f"prompt is {len(prompt):,} characters, over the {PROMPT_LIMIT:,}-character limit")
|
|
844
|
+
print(prompt)
|
|
845
|
+
return 0
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
def main(argv=None):
|
|
849
|
+
p = argparse.ArgumentParser(prog="pr_exam")
|
|
850
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
851
|
+
v = sub.add_parser("validate")
|
|
852
|
+
v.add_argument("--request", required=True)
|
|
853
|
+
v.add_argument("exam")
|
|
854
|
+
v.set_defaults(fn=validate)
|
|
855
|
+
pub = sub.add_parser("public")
|
|
856
|
+
pub.add_argument("exam")
|
|
857
|
+
pub.set_defaults(fn=public)
|
|
858
|
+
sc = sub.add_parser("score")
|
|
859
|
+
for f in ("exam", "answers", "grades"):
|
|
860
|
+
sc.add_argument(f"--{f}", required=True)
|
|
861
|
+
sc.add_argument("--flags")
|
|
862
|
+
sc.set_defaults(fn=score)
|
|
863
|
+
ln = sub.add_parser("learned")
|
|
864
|
+
ln.add_argument("--records", required=True)
|
|
865
|
+
ln.add_argument("--today", required=True)
|
|
866
|
+
ln.set_defaults(fn=learned)
|
|
867
|
+
rc = sub.add_parser("record")
|
|
868
|
+
for f in ("records", "exam", "result", "today"):
|
|
869
|
+
rc.add_argument(f"--{f}", required=True)
|
|
870
|
+
rc.set_defaults(fn=record)
|
|
871
|
+
cf = sub.add_parser("config")
|
|
872
|
+
cf.add_argument("path", nargs="?", default=".pr-exam.json")
|
|
873
|
+
cf.set_defaults(fn=config)
|
|
874
|
+
st = sub.add_parser("setup")
|
|
875
|
+
st.add_argument("--check", action="store_true", help="only report whether `exam` is a required check")
|
|
876
|
+
st.add_argument("repo")
|
|
877
|
+
st.set_defaults(fn=setup)
|
|
878
|
+
cx = sub.add_parser("context")
|
|
879
|
+
for f in ("exam", "diff", "body", "turn"):
|
|
880
|
+
cx.add_argument(f"--{f}", required=True)
|
|
881
|
+
cx.set_defaults(fn=context)
|
|
882
|
+
args = p.parse_args(argv)
|
|
883
|
+
return args.fn(args)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
if __name__ == "__main__":
|
|
887
|
+
sys.exit(main())
|