@jesdi/skills 0.0.102 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jesdi/skills",
3
- "version": "0.0.102",
3
+ "version": "0.0.103",
4
4
  "description": "jesdi's agent skills (content package consumed by @jesdi/skills-cli)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,9 +17,10 @@ stderr.
17
17
  |---|---|
18
18
  | `python3 pr_exam.py validate --request <request.json> <exam.json>` | Checks a generated exam against its request; prints its summary. |
19
19
  | `python3 pr_exam.py public <exam.json>` | Prints the exam the page may show: no key, concepts or answers. |
20
- | `python3 pr_exam.py score --exam <exam.json> --answers <answers.json> --grades <grades.json>` | Scores an attempt and names what was missed. |
20
+ | `python3 pr_exam.py score --exam <exam.json> --answers <answers.json> --grades <grades.json> [--flags <flags.json>]` | Scores an attempt and names what was missed. `--flags` holds `{"bypassed": [id], "assisted": [id, ...]}`: one bypassed question leaves the score; both are reported as `help`. |
21
21
  | `python3 pr_exam.py learned --records <dir> --today <YYYY-MM-DD>` | Lists concepts known, due or wrong. |
22
- | `python3 pr_exam.py record --records <dir> --exam <exam.json> --result <result.json> --today <YYYY-MM-DD>` | Writes learning records for a scored attempt. |
22
+ | `python3 pr_exam.py record --records <dir> --exam <exam.json> --result <result.json> --today <YYYY-MM-DD>` | Writes learning records for a scored attempt: `demonstrated`, `assisted` (a full point with help, always `due`) or `misconception`. An older `pr_exam.py` refuses an `assisted` record, so never roll the host pin back past this version. |
23
+ | `python3 pr_exam.py context --exam <exam.json> --diff <diff> --body <body> --turn <turn.json>` | Prints the prompt for one tip or chat turn: the section below for its kind, the diff, the body, then the turn. |
23
24
  | `python3 pr_exam.py config [<.pr-exam.json>]` | Reads and validates the repo's exam config. |
24
25
  | `python3 pr_exam.py setup [--check] <owner/repo>` | Run by the operator: makes `exam` a required check of the default branch. `--check` only reports whether it is one. |
25
26
 
@@ -126,6 +127,25 @@ nothing else from generation. No key, no explanation, no earlier attempt.
126
127
  `choice` questions are never graded by the session, and you do not score the attempt: the host runs
127
128
  `pr_exam.py score`, which marks them from the key and refuses a grade for one.
128
129
 
130
+ ## Tips
131
+
132
+ A tip helps a reader who is stuck on one question. You get the question, its key, the draft
133
+ and the earlier tips. Climb one rung per tip number:
134
+
135
+ 1. Where to look: point at a file or hunk, nothing more.
136
+ 2. The missing idea: name what the draft leaves out.
137
+ 3. One step away: bring the reader next to the answer, never onto it.
138
+
139
+ React to the draft. Never state the answer, never quote the key. On a `choice` question never
140
+ quote, name or rule out an option. Do not repeat an earlier tip. Reply in two sentences at most.
141
+
142
+ ## Chat
143
+
144
+ The chat answers freely, the key included: explain, compare, and say whether the draft is
145
+ right. After a submit, use the submitted answer, its points and its feedback to explain the
146
+ result. Ground every claim in the diff and the PR body, and say so when they do not settle it.
147
+ Be brief.
148
+
129
149
  ## Never
130
150
 
131
151
  Never apply a bypass label. Never post an `exam` status. The host decides both.
@@ -15,6 +15,9 @@ with the prompt the host uses (agent-ops `dispatcher/exam_runner.py`). One live
15
15
  `passed.diff`) → `exam.json`, 2 questions on concepts no earlier exam covered.
16
16
  - `delta-nothing-new/`: `delta`, after a pass: the push only rewords a docstring and renames a
17
17
  variable → an empty `exam.json`.
18
+ - `tip-choice/`, `tip-text/`, `chat-answer/`: three live turns on the twelve-concept exam (a tip on a
19
+ `choice` question, tip 1 on a `text` question, a `question` chat turn "what is the answer?"). Each has
20
+ `turn.json`, `prompt.md` (what `context` prints for it) and `reply.md` (`claude -p --tools ''` on the prompt).
18
21
 
19
22
  The requests are written as the host writes them, with paths made relative. Every generation run
20
23
  finished on `validate` exit 0. `test_skill_fixtures.py` checks the outputs again.
@@ -0,0 +1,92 @@
1
+ The chat answers freely, the key included: explain, compare, and say whether the draft is
2
+ right. After a submit, use the submitted answer, its points and its feedback to explain the
3
+ result. Ground every claim in the diff and the PR body, and say so when they do not settle it.
4
+ Be brief.
5
+
6
+ Diff:
7
+ diff --git a/lease.py b/lease.py
8
+ new file mode 100644
9
+ --- /dev/null
10
+ +++ b/lease.py
11
+ @@ -0,0 +1,61 @@
12
+ +import time
13
+ +
14
+ +
15
+ +class LeaseLost(Exception):
16
+ + """The caller no longer owns the lease it tried to write under."""
17
+ +
18
+ +
19
+ +class LeaseStore:
20
+ + """Single-writer lease over a key-value store.
21
+ +
22
+ + Two workers can both believe they lead after a pause (GC, network). A
23
+ + fencing token lets the store reject the older leader's late writes.
24
+ + """
25
+ +
26
+ + def __init__(self, backend, ttl=30, clock=time.monotonic):
27
+ + self.backend = backend
28
+ + self.ttl = ttl
29
+ + self.clock = clock
30
+ +
31
+ + def acquire(self, name, owner):
32
+ + now = self.clock()
33
+ + held = self.backend.get(name)
34
+ + if held and held["expires"] > now and held["owner"] != owner:
35
+ + return None
36
+ + token = (held["token"] + 1) if held else 1
37
+ + self.backend.put(name, {"owner": owner, "token": token, "expires": now + self.ttl})
38
+ + return token
39
+ +
40
+ + def renew(self, name, owner, token):
41
+ + held = self.backend.get(name)
42
+ + if not held or held["owner"] != owner or held["token"] != token:
43
+ + raise LeaseLost(name)
44
+ + held["expires"] = self.clock() + self.ttl
45
+ + self.backend.put(name, held)
46
+ +
47
+ + def write(self, name, token, key, value):
48
+ + held = self.backend.get(name)
49
+ + if not held or held["token"] != token:
50
+ + raise LeaseLost(name)
51
+ + self.backend.put(key, value)
52
+ +
53
+ + def release(self, name, owner, token):
54
+ + held = self.backend.get(name)
55
+ + if held and held["owner"] == owner and held["token"] == token:
56
+ + held["expires"] = 0
57
+ + self.backend.put(name, held)
58
+ +
59
+ +
60
+ +def run_leader(store, name, owner, work, interval=10):
61
+ + token = store.acquire(name, owner)
62
+ + if token is None:
63
+ + return False
64
+ + try:
65
+ + while work(token):
66
+ + store.renew(name, owner, token)
67
+ + time.sleep(interval)
68
+ + except LeaseLost:
69
+ + return False
70
+ + finally:
71
+ + store.release(name, owner, token)
72
+ + return True
73
+
74
+
75
+ PR body:
76
+ Adds a lease so that only one worker runs the nightly sync at a time. Before this, two workers sometimes ran it at once and overwrote each other's results.
77
+
78
+ Why: a worker that stalls past its TTL must not keep writing after another worker took over, so every write carries a fencing token and the store refuses a stale one.
79
+
80
+ ```merge-risk v1
81
+ risk: medium
82
+ rollback: revert; leases expire after the TTL
83
+ blast-radius: the nightly sync only
84
+ ```
85
+
86
+
87
+ Question: {"id": "q3", "concept": "fencing-token", "type": "choice", "prompt": "What makes a write under an old fencing token fail?", "options": ["The token encodes the owner's process identifier", "Every new acquisition increments the stored token", "Each token carries its own signed expiry"]}
88
+ Key: {"explanation": "acquire stores the previous token plus one, so the newest holder always has the highest token and any older token no longer matches.", "hunk": "+ token = (held[\"token\"] + 1) if held else 1", "answer": 1}
89
+
90
+ Draft:
91
+
92
+ Message: what is the answer?
@@ -0,0 +1,7 @@
1
+ The answer is **"Every new acquisition increments the stored token."**
2
+
3
+ - **Why that's right:** `acquire` stores `held["token"] + 1`, so each new holder gets a higher token than the last. `write` then checks `held["token"] != token` and raises `LeaseLost`. An older leader's token no longer matches the stored one, so its late write is refused. This is the behaviour the PR body describes: "the store refuses a stale one."
4
+ - **Why not the owner's process identifier:** the token is a plain integer counter. `write` never looks at the owner at all.
5
+ - **Why not a signed expiry:** the expiry is stored in the lease record, not in the token, and nothing is signed. `write` doesn't check expiry either. It only compares tokens.
6
+
7
+ One caveat from the diff: `write` checks for an exact match, not "is this the highest token." It works here only because the stored token only ever goes up.
@@ -0,0 +1 @@
1
+ {"kind":"question","question":"q3","draft":"","thread":[],"message":"what is the answer?"}
@@ -0,0 +1,97 @@
1
+ A tip helps a reader who is stuck on one question. You get the question, its key, the draft
2
+ and the earlier tips. Climb one rung per tip number:
3
+
4
+ 1. Where to look: point at a file or hunk, nothing more.
5
+ 2. The missing idea: name what the draft leaves out.
6
+ 3. One step away: bring the reader next to the answer, never onto it.
7
+
8
+ React to the draft. Never state the answer, never quote the key. On a `choice` question never
9
+ quote, name or rule out an option. Do not repeat an earlier tip. Reply in two sentences at most.
10
+
11
+ Diff:
12
+ diff --git a/lease.py b/lease.py
13
+ new file mode 100644
14
+ --- /dev/null
15
+ +++ b/lease.py
16
+ @@ -0,0 +1,61 @@
17
+ +import time
18
+ +
19
+ +
20
+ +class LeaseLost(Exception):
21
+ + """The caller no longer owns the lease it tried to write under."""
22
+ +
23
+ +
24
+ +class LeaseStore:
25
+ + """Single-writer lease over a key-value store.
26
+ +
27
+ + Two workers can both believe they lead after a pause (GC, network). A
28
+ + fencing token lets the store reject the older leader's late writes.
29
+ + """
30
+ +
31
+ + def __init__(self, backend, ttl=30, clock=time.monotonic):
32
+ + self.backend = backend
33
+ + self.ttl = ttl
34
+ + self.clock = clock
35
+ +
36
+ + def acquire(self, name, owner):
37
+ + now = self.clock()
38
+ + held = self.backend.get(name)
39
+ + if held and held["expires"] > now and held["owner"] != owner:
40
+ + return None
41
+ + token = (held["token"] + 1) if held else 1
42
+ + self.backend.put(name, {"owner": owner, "token": token, "expires": now + self.ttl})
43
+ + return token
44
+ +
45
+ + def renew(self, name, owner, token):
46
+ + held = self.backend.get(name)
47
+ + if not held or held["owner"] != owner or held["token"] != token:
48
+ + raise LeaseLost(name)
49
+ + held["expires"] = self.clock() + self.ttl
50
+ + self.backend.put(name, held)
51
+ +
52
+ + def write(self, name, token, key, value):
53
+ + held = self.backend.get(name)
54
+ + if not held or held["token"] != token:
55
+ + raise LeaseLost(name)
56
+ + self.backend.put(key, value)
57
+ +
58
+ + def release(self, name, owner, token):
59
+ + held = self.backend.get(name)
60
+ + if held and held["owner"] == owner and held["token"] == token:
61
+ + held["expires"] = 0
62
+ + self.backend.put(name, held)
63
+ +
64
+ +
65
+ +def run_leader(store, name, owner, work, interval=10):
66
+ + token = store.acquire(name, owner)
67
+ + if token is None:
68
+ + return False
69
+ + try:
70
+ + while work(token):
71
+ + store.renew(name, owner, token)
72
+ + time.sleep(interval)
73
+ + except LeaseLost:
74
+ + return False
75
+ + finally:
76
+ + store.release(name, owner, token)
77
+ + return True
78
+
79
+
80
+ PR body:
81
+ Adds a lease so that only one worker runs the nightly sync at a time. Before this, two workers sometimes ran it at once and overwrote each other's results.
82
+
83
+ Why: a worker that stalls past its TTL must not keep writing after another worker took over, so every write carries a fencing token and the store refuses a stale one.
84
+
85
+ ```merge-risk v1
86
+ risk: medium
87
+ rollback: revert; leases expire after the TTL
88
+ blast-radius: the nightly sync only
89
+ ```
90
+
91
+
92
+ Question: {"id": "q3", "concept": "fencing-token", "type": "choice", "prompt": "What makes a write under an old fencing token fail?", "options": ["The token encodes the owner's process identifier", "Every new acquisition increments the stored token", "Each token carries its own signed expiry"]}
93
+ Key: {"explanation": "acquire stores the previous token plus one, so the newest holder always has the highest token and any older token no longer matches.", "hunk": "+ token = (held[\"token\"] + 1) if held else 1", "answer": 1}
94
+
95
+ Draft:
96
+
97
+ Tip number: 1
@@ -0,0 +1 @@
1
+ Your draft is empty, so start with `acquire` in lease.py and read the line that works out which token to store. Then compare it with the check at the top of `write`.
@@ -0,0 +1 @@
1
+ {"kind":"tip","question":"q3","tip":1,"draft":"","tips":[]}
@@ -0,0 +1,97 @@
1
+ A tip helps a reader who is stuck on one question. You get the question, its key, the draft
2
+ and the earlier tips. Climb one rung per tip number:
3
+
4
+ 1. Where to look: point at a file or hunk, nothing more.
5
+ 2. The missing idea: name what the draft leaves out.
6
+ 3. One step away: bring the reader next to the answer, never onto it.
7
+
8
+ React to the draft. Never state the answer, never quote the key. On a `choice` question never
9
+ quote, name or rule out an option. Do not repeat an earlier tip. Reply in two sentences at most.
10
+
11
+ Diff:
12
+ diff --git a/lease.py b/lease.py
13
+ new file mode 100644
14
+ --- /dev/null
15
+ +++ b/lease.py
16
+ @@ -0,0 +1,61 @@
17
+ +import time
18
+ +
19
+ +
20
+ +class LeaseLost(Exception):
21
+ + """The caller no longer owns the lease it tried to write under."""
22
+ +
23
+ +
24
+ +class LeaseStore:
25
+ + """Single-writer lease over a key-value store.
26
+ +
27
+ + Two workers can both believe they lead after a pause (GC, network). A
28
+ + fencing token lets the store reject the older leader's late writes.
29
+ + """
30
+ +
31
+ + def __init__(self, backend, ttl=30, clock=time.monotonic):
32
+ + self.backend = backend
33
+ + self.ttl = ttl
34
+ + self.clock = clock
35
+ +
36
+ + def acquire(self, name, owner):
37
+ + now = self.clock()
38
+ + held = self.backend.get(name)
39
+ + if held and held["expires"] > now and held["owner"] != owner:
40
+ + return None
41
+ + token = (held["token"] + 1) if held else 1
42
+ + self.backend.put(name, {"owner": owner, "token": token, "expires": now + self.ttl})
43
+ + return token
44
+ +
45
+ + def renew(self, name, owner, token):
46
+ + held = self.backend.get(name)
47
+ + if not held or held["owner"] != owner or held["token"] != token:
48
+ + raise LeaseLost(name)
49
+ + held["expires"] = self.clock() + self.ttl
50
+ + self.backend.put(name, held)
51
+ +
52
+ + def write(self, name, token, key, value):
53
+ + held = self.backend.get(name)
54
+ + if not held or held["token"] != token:
55
+ + raise LeaseLost(name)
56
+ + self.backend.put(key, value)
57
+ +
58
+ + def release(self, name, owner, token):
59
+ + held = self.backend.get(name)
60
+ + if held and held["owner"] == owner and held["token"] == token:
61
+ + held["expires"] = 0
62
+ + self.backend.put(name, held)
63
+ +
64
+ +
65
+ +def run_leader(store, name, owner, work, interval=10):
66
+ + token = store.acquire(name, owner)
67
+ + if token is None:
68
+ + return False
69
+ + try:
70
+ + while work(token):
71
+ + store.renew(name, owner, token)
72
+ + time.sleep(interval)
73
+ + except LeaseLost:
74
+ + return False
75
+ + finally:
76
+ + store.release(name, owner, token)
77
+ + return True
78
+
79
+
80
+ PR body:
81
+ Adds a lease so that only one worker runs the nightly sync at a time. Before this, two workers sometimes ran it at once and overwrote each other's results.
82
+
83
+ Why: a worker that stalls past its TTL must not keep writing after another worker took over, so every write carries a fencing token and the store refuses a stale one.
84
+
85
+ ```merge-risk v1
86
+ risk: medium
87
+ rollback: revert; leases expire after the TTL
88
+ blast-radius: the nightly sync only
89
+ ```
90
+
91
+
92
+ Question: {"id": "q2", "concept": "stale-leader-writes", "type": "text", "prompt": "A worker holding the lease pauses longer than its TTL, and another worker takes over. Why is the lease alone not enough here, and what stops the first worker's late writes?"}
93
+ Key: {"explanation": "After a pause (GC, network) both workers can believe they lead. Every write carries the fencing token from acquire, and write raises LeaseLost when the stored token differs, so the stale leader's late writes are refused.", "hunk": "+ def write(self, name, token, key, value):\n+ held = self.backend.get(name)\n+ if not held or held[\"token\"] != token:\n+ raise LeaseLost(name)", "rubric": {"pass": "Says the paused worker still believes it leads, and that each write carries a fencing token the store compares with the current one, refusing the stale token.", "partial": "Mentions the fencing token or the stale leader, but not how the store uses the token to refuse the late write."}}
94
+
95
+ Draft:
96
+
97
+ Tip number: 1
@@ -0,0 +1 @@
1
+ Your answer is still empty, so start in `lease.py` with the `write` method and the first lines it runs before it touches the backend. Then look back at what `acquire` returns to the caller.
@@ -0,0 +1 @@
1
+ {"kind":"tip","question":"q2","tip":1,"draft":"","tips":[]}
@@ -362,7 +362,7 @@ def check_record(f):
362
362
  """ValueError naming what is wrong with a record's frontmatter fields."""
363
363
  if any(not f.get(k) for k in FIELDS):
364
364
  raise ValueError("missing field")
365
- if f["state"] not in ("demonstrated", "misconception"):
365
+ if f["state"] not in ("demonstrated", "assisted", "misconception"):
366
366
  raise ValueError("state")
367
367
  datetime.date.fromisoformat(f["date"])
368
368
  if not re.fullmatch(r"active|superseded by LR-\d{4,}", f["status"]):
@@ -398,6 +398,8 @@ def learned_states(directory, today):
398
398
  continue
399
399
  if f["state"] == "misconception":
400
400
  states[f["concept"]] = "misconception"
401
+ elif f["state"] == "assisted":
402
+ states[f["concept"]] = "due"
401
403
  else:
402
404
  age = (today - datetime.date.fromisoformat(f["date"])).days
403
405
  states[f["concept"]] = "skip" if age < 30 else "due"
@@ -442,9 +444,16 @@ def publish(path, text):
442
444
  os.replace(tmp, path)
443
445
 
444
446
 
445
- def publish_record(args, q, n, explanation, source):
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):
446
456
  concept = q["concept"]
447
- state = "demonstrated" if q["points"] == 1 else "misconception"
448
457
  publish(Path(args.records) / f"{n:04d}-{concept}.md",
449
458
  f"---\nconcept: {concept}\nstate: {state}\ndate: {args.today}\nsource: {source}\n"
450
459
  f"status: active\n---\n# {concept}\n\n{explanation}\n")
@@ -462,11 +471,12 @@ def supersede(existing, concept, n):
462
471
  def write_records(args, result, existing, explanations, source):
463
472
  n = max([r[0] for r in existing], default=0)
464
473
  for q in result["questions"]:
465
- if q["points"] in (0, 1):
474
+ state = record_state(q)
475
+ if state:
466
476
  n += 1
467
477
  # The successor is published before its predecessor is superseded: a failure in between
468
478
  # leaves two active records, and the newest one counts, so no state is ever lost.
469
- publish_record(args, q, n, explanations.get(q["id"], ""), source)
479
+ publish_record(args, q, state, n, explanations.get(q["id"], ""), source)
470
480
  supersede(existing, q["concept"], n)
471
481
  return 0
472
482
 
@@ -490,10 +500,12 @@ def public(args):
490
500
  GRADE_POINTS = {"pass": 1, "partial": 0.5, "fail": 0}
491
501
 
492
502
 
493
- def grade_errors(grades, texts):
494
- """Only text questions are graded, each pass, partial or fail."""
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."""
495
505
  errors = []
496
506
  for qid, g in grades.items():
507
+ if qid in bypassed:
508
+ continue
497
509
  if qid not in texts:
498
510
  errors.append(f"grade for {qid}: not a text question")
499
511
  elif g.get("grade") not in GRADE_POINTS:
@@ -501,15 +513,55 @@ def grade_errors(grades, texts):
501
513
  return errors
502
514
 
503
515
 
504
- def score_errors(exam, answers, grades):
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."""
505
551
  texts = {q["id"] for q in exam["questions"] if q["type"] == "text"}
506
552
  errors = []
507
553
  for q in exam["questions"]:
508
- errors += broken((
509
- (q["id"] not in answers, f"question {q['id']}: unanswered"),
510
- (q["id"] in texts and q["id"] not in grades, f"question {q['id']}: text question has no grade"),
511
- ))
512
- return errors + grade_errors(grades, texts)
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", []))
513
565
 
514
566
 
515
567
  def points(q, k, answers, grades):
@@ -518,37 +570,53 @@ def points(q, k, answers, grades):
518
570
  return GRADE_POINTS[grades[q["id"]]["grade"]]
519
571
 
520
572
 
521
- def question_result(q, k, answers, grades):
522
- """A question's points; below full points, also its explanation, hunk and (text) grader feedback."""
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"]}
523
578
  r = {"id": q["id"], "concept": q["concept"], "points": points(q, k, answers, grades)}
524
579
  if r["points"] < 1:
525
580
  r.update(explanation=k["explanation"], hunk=k["hunk"])
526
581
  if q["type"] == "text":
527
582
  r["feedback"] = grades[q["id"]].get("feedback", "")
583
+ if help:
584
+ r["help"] = help
528
585
  return r
529
586
 
530
587
 
531
- def passed(exam, missed, total):
588
+ def passed(exam, missed, total, maximum):
532
589
  """At least 80% of the points, and no why concept missed."""
533
590
  kinds = {c["id"]: c["kind"] for c in exam["concepts"]}
534
591
  why_ok = all(kinds.get(c) != "why" for c in missed)
535
- return total / len(exam["questions"]) >= 0.8 and why_ok
592
+ return total >= 0.8 * maximum and why_ok
593
+
536
594
 
595
+ def helped(qid, flags):
596
+ return next((k for k in FLAG_KEYS if qid in flags.get(k, [])), None)
537
597
 
538
- def scored(exam, answers, grades):
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):
539
608
  """result.json: points per question, the missed concepts, and whether the attempt passed."""
540
- out = [question_result(q, exam["key"][q["id"]], answers, grades) for q in exam["questions"]]
541
- missed = [r["concept"] for r in out if r["points"] < 1]
542
- total = sum(r["points"] for r in out)
543
- return {"passed": passed(exam, missed, total), "score": total, "max": len(out), "questions": out, "missed": missed}
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"]])
544
611
 
545
612
 
546
613
  def score(args):
547
614
  exam, answers, grades = load(args.exam), load(args.answers), load(args.grades)
548
- errors = score_errors(exam, answers, grades)
615
+ flags = load(args.flags) if args.flags else {}
616
+ errors = score_errors(exam, answers, grades, flags)
549
617
  if errors:
550
618
  return fail("\n".join(errors))
551
- print(json.dumps(scored(exam, answers, grades)))
619
+ print(json.dumps(scored(exam, answers, grades, flags)))
552
620
  return 0
553
621
 
554
622
 
@@ -668,6 +736,115 @@ def setup(args):
668
736
  return require_exam(got, path, f"{args.repo}@{branch}", app)
669
737
 
670
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
+
671
848
  def main(argv=None):
672
849
  p = argparse.ArgumentParser(prog="pr_exam")
673
850
  sub = p.add_subparsers(dest="cmd", required=True)
@@ -681,6 +858,7 @@ def main(argv=None):
681
858
  sc = sub.add_parser("score")
682
859
  for f in ("exam", "answers", "grades"):
683
860
  sc.add_argument(f"--{f}", required=True)
861
+ sc.add_argument("--flags")
684
862
  sc.set_defaults(fn=score)
685
863
  ln = sub.add_parser("learned")
686
864
  ln.add_argument("--records", required=True)
@@ -697,6 +875,10 @@ def main(argv=None):
697
875
  st.add_argument("--check", action="store_true", help="only report whether `exam` is a required check")
698
876
  st.add_argument("repo")
699
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)
700
882
  args = p.parse_args(argv)
701
883
  return args.fn(args)
702
884
 
@@ -0,0 +1,174 @@
1
+ """Acceptance tests: `pr_exam.py context --exam --diff --body --turn`, run as a subprocess.
2
+
3
+ Spec specs/pr-exam-assist: requirements 1-4, scenarios "a tip prompt ..." to "a draft on the general chat".
4
+ turn.json shape: design.md (kind, question, tip, tips, draft, submitted, points, feedback, thread, message).
5
+ Exam: q1-q3 choice, q4-q6 text.
6
+ """
7
+ import json
8
+ import re
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ HERE = Path(__file__).parent
15
+ SCRIPT = HERE / "pr_exam.py"
16
+ DIFF = "diff --git a/src/lease.py b/src/lease.py\n+token = token + 1\n"
17
+ BODY = "PR body: make the lease token monotonic."
18
+ CONCEPTS = [("merge-lease", "concept"), ("retry-budget", "risk"), ("head-recheck", "architecture"),
19
+ ("lease-owner", "why"), ("fencing-token", "concept"), ("stale-lease", "behaviour")]
20
+
21
+
22
+ def exam():
23
+ qs, key = [], {}
24
+ for i, (slug, _) in enumerate(CONCEPTS, 1):
25
+ q = {"id": f"q{i}", "concept": slug, "type": "choice" if i <= 3 else "text", "prompt": f"Prompt-{i} about {slug}?"}
26
+ k = {"explanation": f"Explanation-{i} of {slug}.", "hunk": f"+hunk-{i} src/lease.py"}
27
+ if i <= 3:
28
+ q["options"] = [f"opt-{i}-alpha", f"opt-{i}-beta", f"opt-{i}-gamma"]
29
+ k["answer"] = 1
30
+ else:
31
+ k["rubric"] = {"pass": f"Rubric-pass-{i}.", "partial": f"Rubric-partial-{i}."}
32
+ qs.append(q)
33
+ key[q["id"]] = k
34
+ return {"version": 1, "mode": "first", "repo": "jesdi/general-skills", "pr": 240, "head_sha": "a" * 40,
35
+ "concepts": [{"id": s, "title": s, "kind": k} for s, k in CONCEPTS], "questions": qs, "key": key}
36
+
37
+
38
+ def context(tmp_path, turn, diff=DIFF, script=SCRIPT, exam_doc=None):
39
+ files = {"exam.json": json.dumps(exam_doc or exam()), "diff.patch": diff, "body.md": BODY, "turn.json": json.dumps(turn)}
40
+ for name, text in files.items():
41
+ (tmp_path / name).write_text(text)
42
+ return subprocess.run([sys.executable, str(script), "context", "--exam", str(tmp_path / "exam.json"),
43
+ "--diff", str(tmp_path / "diff.patch"), "--body", str(tmp_path / "body.md"),
44
+ "--turn", str(tmp_path / "turn.json")], capture_output=True, text=True)
45
+
46
+
47
+ def ok(r):
48
+ assert r.returncode == 0, (r.returncode, r.stdout, r.stderr)
49
+ return r.stdout
50
+
51
+
52
+ def refused(r, *words):
53
+ assert r.returncode not in (0, 2), (r.returncode, r.stdout, r.stderr) # 2 is argparse: no such command
54
+ for w in words:
55
+ assert w in r.stderr, (w, r.stderr)
56
+
57
+
58
+ def section(name):
59
+ text = (HERE / "SKILL.md").read_text()
60
+ m = re.search(rf"^## {name}\n(.*?)(?=^## |\Z)", text, re.M | re.S)
61
+ assert m, f"SKILL.md has no '## {name}' section"
62
+ return m.group(1).strip()
63
+
64
+
65
+ def has(prompt, *parts):
66
+ for p in parts:
67
+ assert p in prompt, (p, prompt)
68
+
69
+
70
+ def tail(prompt):
71
+ return prompt[prompt.index(BODY) + len(BODY):]
72
+
73
+
74
+ def tip(n, draft, tips=()):
75
+ return {"kind": "tip", "question": "q5", "tip": n, "draft": draft, "tips": list(tips)}
76
+
77
+
78
+ def test_tip_prompt_carries_rules_draft_number_and_earlier_tips(tmp_path):
79
+ p = ok(context(tmp_path, tip(2, "the token only grows", ["Look at src/lease.py, the token line."])))
80
+ q, k = exam()["questions"][4], exam()["key"]["q5"]
81
+ has(p, DIFF, BODY, q["prompt"], k["rubric"]["pass"], k["rubric"]["partial"], k["explanation"], k["hunk"],
82
+ "the token only grows", "2", "Look at src/lease.py, the token line.")
83
+ has(p, section("Tips"))
84
+
85
+
86
+ def test_tip_four_is_refused(tmp_path):
87
+ r = context(tmp_path, tip(4, ""))
88
+ refused(r, "4")
89
+ assert re.search(r"1\s*(-|–|to)\s*3", r.stderr), r.stderr
90
+
91
+
92
+ def test_unknown_question_is_refused(tmp_path):
93
+ refused(context(tmp_path, {"kind": "question", "question": "q9", "draft": "", "thread": [], "message": "hi"}), "q9")
94
+
95
+
96
+ def test_question_thread_sees_draft_key_and_thread(tmp_path):
97
+ thread = [{"role": "user", "text": "earlier question?"}, {"role": "assistant", "text": "earlier answer."}]
98
+ p = ok(context(tmp_path, {"kind": "question", "question": "q2", "draft": "option 1", "thread": thread,
99
+ "message": "is this right?"}))
100
+ q = exam()["questions"][1]
101
+ has(p, section("Chat"), DIFF, BODY, q["prompt"], *q["options"], "Explanation-2", "+hunk-2", "answer",
102
+ "option 1", "earlier question?", "earlier answer.", "is this right?")
103
+
104
+
105
+ def graded_turn(**extra):
106
+ return {"kind": "question", "question": "q5", "draft": "", "thread": [], "message": "why was I wrong?",
107
+ "submitted": "the token is random", **extra}
108
+
109
+
110
+ def test_graded_thread_sees_answer_points_and_feedback(tmp_path):
111
+ p = ok(context(tmp_path, graded_turn(points=0, feedback="misses that the token only grows")))
112
+ has(p, "the token is random", "misses that the token only grows")
113
+ assert re.search(r"(?i)points?\W{0,6}0\b|\b0\s*points?", tail(p)), tail(p)
114
+
115
+
116
+ def test_grading_thread_sees_submitted_answer_only(tmp_path):
117
+ p = ok(context(tmp_path, graded_turn()))
118
+ has(p, "the token is random")
119
+ assert "point" not in tail(p).lower() and "feedback" not in tail(p).lower(), tail(p)
120
+
121
+
122
+ def test_general_turn_sees_every_question_and_no_draft(tmp_path):
123
+ p = ok(context(tmp_path, {"kind": "general", "thread": [], "message": "what is the riskiest change?"}))
124
+ has(p, section("Chat"), DIFF, BODY, "what is the riskiest change?")
125
+ for i in range(1, 7):
126
+ has(p, f"Prompt-{i} ", f"Explanation-{i} ")
127
+ has(p, "opt-1-beta")
128
+ assert "draft" not in tail(p).lower(), tail(p)
129
+
130
+
131
+ def test_general_turn_with_draft_is_refused(tmp_path):
132
+ refused(context(tmp_path, {"kind": "general", "draft": "x", "thread": [], "message": "hi"}), "draft", "general")
133
+
134
+
135
+ def test_missing_section_is_refused_naming_heading(tmp_path):
136
+ shutil.copy(SCRIPT, tmp_path / "pr_exam.py")
137
+ (tmp_path / "SKILL.md").write_text("# pr-exam\n\n## Chat\nAnswer freely.\n")
138
+ refused(context(tmp_path, tip(1, ""), script=tmp_path / "pr_exam.py"), "Tips")
139
+
140
+
141
+ def test_turns_of_a_kind_share_their_opening(tmp_path):
142
+ a = ok(context(tmp_path, tip(1, "draft one")))
143
+ b = ok(context(tmp_path, tip(2, "another draft", ["first tip text"])))
144
+ end = a.index(BODY) + len(BODY)
145
+ assert a[:end] == b[:end]
146
+ assert a.index(section("Tips")) < a.index(DIFF) < a.index(BODY)
147
+ assert a != b
148
+
149
+
150
+ def test_oversized_prompt_is_refused_with_length_and_limit(tmp_path):
151
+ r = context(tmp_path, tip(1, ""), diff="x" * 450_000)
152
+ refused(r, "limit")
153
+ assert re.search(r"\b(450,?\d{3}|45\d,?\d{3}|4[6-9]\d,?\d{3})\b", r.stderr), r.stderr
154
+ assert re.search(r"400,?000", r.stderr), r.stderr
155
+
156
+
157
+ def test_failed_attempt_turn_uses_the_attempt_exam_not_the_followup(tmp_path):
158
+ attempt, followup = exam(), exam()
159
+ attempt["questions"][4]["prompt"] = "ATTEMPT-prompt q5"
160
+ attempt["key"]["q5"].update(explanation="ATTEMPT-explanation q5", hunk="+ATTEMPT-hunk")
161
+ attempt["key"]["q5"]["rubric"] = {"pass": "ATTEMPT-pass", "partial": "ATTEMPT-partial"}
162
+ followup["mode"] = "followup"
163
+ followup["questions"][4]["prompt"] = "FOLLOWUP-prompt q5"
164
+ followup["key"]["q5"].update(explanation="FOLLOWUP-explanation q5", hunk="+FOLLOWUP-hunk")
165
+ followup["key"]["q5"]["rubric"] = {"pass": "FOLLOWUP-pass", "partial": "FOLLOWUP-partial"}
166
+ (tmp_path / "followup.json").write_text(json.dumps(followup))
167
+ (tmp_path / "exam.followup.json").write_text(json.dumps(followup))
168
+ turn = graded_turn(points=0, feedback="ATTEMPT-feedback")
169
+ p = ok(context(tmp_path, turn, exam_doc=attempt))
170
+ has(p, "ATTEMPT-prompt q5", "ATTEMPT-explanation q5", "+ATTEMPT-hunk", "ATTEMPT-pass", "ATTEMPT-partial",
171
+ "the token is random", "ATTEMPT-feedback")
172
+ assert "FOLLOWUP" not in p, p
173
+ g = ok(context(tmp_path, {"kind": "general", "thread": [], "message": "m"}, exam_doc=attempt))
174
+ assert "FOLLOWUP" not in g and "ATTEMPT-prompt q5" in g, g
@@ -0,0 +1,18 @@
1
+ """`score --flags` refuses flag collections that are not lists of question ids (design.md, flags.json)."""
2
+ import pytest
3
+
4
+ from test_scoring import flagged
5
+
6
+
7
+ @pytest.mark.parametrize("flags, field", [
8
+ ({"bypassed": {"q4": False}}, "bypassed"),
9
+ ({"assisted": {"q2": False}}, "assisted"),
10
+ ({"assisted": None}, "assisted"),
11
+ ({"bypassed": "q6"}, "bypassed"),
12
+ ({"assisted": [2]}, "assisted"),
13
+ (["q6"], "object"),
14
+ ])
15
+ def test_malformed_flags_are_refused_without_a_result(tmp_path, flags, field):
16
+ r = flagged(tmp_path, flags, grades={"q4": "fail"})
17
+ assert r.returncode == 1, (r.returncode, r.stdout, r.stderr)
18
+ assert field in r.stderr and r.stdout == "", (r.stdout, r.stderr)
@@ -265,3 +265,91 @@ def test_validate_and_record_refuse_a_malformed_record_naming_the_file(tmp_path)
265
265
  "--result", tmp_path / "result.json", "--today", TODAY)
266
266
  assert r.returncode == 1 and "0001-merge-lease.md" in r.stderr, (r.returncode, r.stdout, r.stderr)
267
267
  assert sorted(p.name for p in records.glob("*.md")) == ["0001-merge-lease.md"]
268
+
269
+
270
+ # --- spec specs/pr-exam-assist: requirements 9-10 (assisted and bypassed records) ---
271
+ # A result question may carry help="bypassed"|"assisted"; a bypassed one has no `points`.
272
+ # `record` writes `misconception` for bypassed, `assisted` for a full point with help="assisted".
273
+ # `learned` reports an active `assisted` record as "due" at any age.
274
+ ASSIST = [("merge-lease", "concept"), ("retry-budget", "concept"), ("head-recheck", "architecture"),
275
+ ("lease-owner", "why"), ("fencing-token", "concept"), ("stale-lease", "concept")]
276
+ SKILL = Path(__file__).parent / "SKILL.md"
277
+ ASSIST_TODAY = "2026-11-24"
278
+
279
+
280
+ def record_result(tmp_path, records, questions, today=ASSIST_TODAY, kinds=None):
281
+ """questions: [(concept, points|None, help|None)]; one text question per entry."""
282
+ exam = exam_with([(c, "text", (kinds or {}).get(c, "concept")) for c, _, _ in questions])
283
+ rq = []
284
+ for i, (c, p, h) in enumerate(questions, 1):
285
+ q = {"id": f"q{i}", "concept": c}
286
+ if p is not None:
287
+ q["points"] = p
288
+ if h:
289
+ q["help"] = h
290
+ rq.append(q)
291
+ result = {"passed": True, "score": 0, "max": 0, "missed": [], "questions": rq}
292
+ (tmp_path / "rexam.json").write_text(json.dumps(exam))
293
+ (tmp_path / "result.json").write_text(json.dumps(result))
294
+ return cli("record", "--records", records, "--exam", tmp_path / "rexam.json",
295
+ "--result", tmp_path / "result.json", "--today", today)
296
+
297
+
298
+ def active(records):
299
+ out = {}
300
+ for p in sorted(records.glob("*.md")):
301
+ if field(p, "status") == "active":
302
+ out[field(p, "concept")] = (field(p, "state"), field(p, "date"))
303
+ return out
304
+
305
+
306
+ def test_each_outcome_writes_its_record(tmp_path):
307
+ records = tmp_path / "records"
308
+ r = record_result(tmp_path, records, [
309
+ ("merge-lease", 1, None), ("retry-budget", 1, "assisted"), ("head-recheck", 0, "assisted"),
310
+ ("lease-owner", None, "bypassed"), ("fencing-token", 0.5, "assisted"), ("stale-lease", 1, None)],
311
+ kinds={"lease-owner": "why"})
312
+ assert r.returncode == 0, (r.returncode, r.stdout, r.stderr)
313
+ assert active(records) == {
314
+ "merge-lease": ("demonstrated", ASSIST_TODAY), "stale-lease": ("demonstrated", ASSIST_TODAY),
315
+ "retry-budget": ("assisted", ASSIST_TODAY), "head-recheck": ("misconception", ASSIST_TODAY),
316
+ "lease-owner": ("misconception", ASSIST_TODAY)}
317
+
318
+
319
+ def test_bypassing_the_only_question_writes_a_misconception_record(tmp_path):
320
+ records = tmp_path / "records"
321
+ r = record_result(tmp_path, records, [("readme-typo", None, "bypassed")])
322
+ assert r.returncode == 0, (r.returncode, r.stdout, r.stderr)
323
+ assert active(records) == {"readme-typo": ("misconception", ASSIST_TODAY)}
324
+
325
+
326
+ def test_assisted_record_is_due_at_any_age_and_demonstrated_of_the_same_age_is_skipped(tmp_path):
327
+ assisted, demonstrated = tmp_path / "a", tmp_path / "d"
328
+ write_record(assisted, 1, "retry-budget", "assisted", "2026-11-22")
329
+ write_record(demonstrated, 1, "retry-budget", "demonstrated", "2026-11-22")
330
+ assert learned_ok(assisted, ASSIST_TODAY) == {"retry-budget": "due"}
331
+ assert learned_ok(demonstrated, ASSIST_TODAY) == {"retry-budget": "skip"}
332
+
333
+
334
+ def test_unassisted_full_point_supersedes_an_assisted_record(tmp_path):
335
+ records = tmp_path / "records"
336
+ write_record(records, 1, "retry-budget", "assisted", "2026-11-20")
337
+ r = record_result(tmp_path, records, [("retry-budget", 1, None)])
338
+ assert r.returncode == 0, (r.returncode, r.stdout, r.stderr)
339
+ assert field(records / "0001-retry-budget.md", "status") == "superseded by LR-0002"
340
+ assert active(records) == {"retry-budget": ("demonstrated", ASSIST_TODAY)}
341
+ assert learned_ok(records, ASSIST_TODAY) == {"retry-budget": "skip"}
342
+
343
+
344
+ def test_assisted_is_a_valid_state_and_any_other_state_is_still_refused(tmp_path):
345
+ records = tmp_path / "records"
346
+ write_record(records, 1, "retry-budget", "assisted", WEEK)
347
+ assert learned(records).returncode == 0, learned(records).stderr
348
+ write_record(records, 2, "merge-lease", "learned", WEEK)
349
+ r = learned(records)
350
+ assert r.returncode == 1 and "0002-merge-lease.md" in r.stderr, (r.returncode, r.stdout, r.stderr)
351
+
352
+
353
+ def test_skill_md_names_the_assisted_state_and_warns_about_older_scripts():
354
+ sentences = re.split(r"(?<=[.!?])\s+", SKILL.read_text().replace("\n", " "))
355
+ assert any("assisted" in s and "older" in s and "pr_exam.py" in s for s in sentences)
@@ -8,6 +8,8 @@ import subprocess
8
8
  import sys
9
9
  from pathlib import Path
10
10
 
11
+ import pytest
12
+
11
13
  SCRIPT = Path(__file__).parent / "pr_exam.py"
12
14
  SHA = "a" * 40
13
15
  CONCEPTS = [("c-why", "why"), ("lease-ownership", "concept"),
@@ -119,3 +121,167 @@ def test_refuse_text_question_without_grade(tmp_path):
119
121
  def test_refuse_unknown_grade(tmp_path):
120
122
  g = {"q1": {"grade": "excellent", "feedback": "f"}, "q2": {"grade": "pass", "feedback": "f"}}
121
123
  refused(score(tmp_path, grades=g), "q1", "excellent")
124
+
125
+
126
+ # --- spec specs/pr-exam-assist: requirements 5-8 (bypassed and assisted questions) ---
127
+ # Optional --flags reads {"bypassed": [qid, ...], "assisted": [qid, ...]}.
128
+ # Omitted keys mean no flags; output questions use help="bypassed" or "assisted".
129
+ # Exam: q1-q3 choice (key answer 1), q4 text on the why concept, q5 and q6 text.
130
+ ASSIST_CONCEPTS = [("merge-lease", "concept"), ("retry-budget", "concept"), ("head-recheck", "architecture"),
131
+ ("lease-owner", "why"), ("fencing-token", "concept"), ("stale-lease", "concept")]
132
+
133
+
134
+ def assist_exam(n=6):
135
+ qs, key = [], {}
136
+ for i, (slug, _) in enumerate(ASSIST_CONCEPTS[:n], 1):
137
+ t = "choice" if i <= 3 else "text"
138
+ q = {"id": f"q{i}", "concept": slug, "type": t, "prompt": f"Prompt {i}?"}
139
+ k = {"explanation": f"Explain {i}.", "hunk": f"+hunk {i}"}
140
+ if t == "choice":
141
+ q["options"] = ["alpha beta", "gamma delta", "zeta eta"]
142
+ k["answer"] = 1
143
+ else:
144
+ k["rubric"] = {"pass": "Names it.", "partial": "Mentions it."}
145
+ qs.append(q)
146
+ key[q["id"]] = k
147
+ concepts = [{"id": s, "title": s, "kind": k} for s, k in ASSIST_CONCEPTS[:n]]
148
+ if n == 1:
149
+ concepts = [{"id": "readme-typo", "title": "README typo", "kind": "behaviour"}]
150
+ qs[0].update(concept="readme-typo", prompt="Which word did the README correct?",
151
+ options=["merge lease", "retry budget", "fencing token"])
152
+ key["q1"].update(explanation="The README now spells retry budget correctly.",
153
+ hunk="-retry buget\n+retry budget")
154
+ return {"version": 1, "mode": "first", "repo": "jesdi/general-skills", "pr": 240, "head_sha": SHA,
155
+ "concepts": concepts, "questions": qs, "key": key}
156
+
157
+
158
+ def flagged(tmp_path, flags, wrong=(), grades=None, skip=(), n=6):
159
+ """Everything full points except `wrong` choice ids (answered 0) and `grades` overrides.
160
+ Questions in `skip` get neither an answer nor a grade."""
161
+ g = {"q4": "pass", "q5": "pass", "q6": "pass", **(grades or {})}
162
+ a = {f"q{i}": (0 if f"q{i}" in wrong else 1) for i in (1, 2, 3)}
163
+ a.update({"q4": "t", "q5": "t", "q6": "t"})
164
+ ans = {k: v for k, v in a.items() if k in {f"q{i}" for i in range(1, n + 1)} and k not in skip}
165
+ grs = {k: {"grade": v, "feedback": "f"} for k, v in g.items()
166
+ if k in {f"q{i}" for i in range(1, n + 1)} and k not in skip}
167
+ files = {"exam": assist_exam(n), "answers": ans, "grades": grs}
168
+ if flags is not None:
169
+ files["flags"] = flags
170
+ for name, data in files.items():
171
+ (tmp_path / f"{name}.json").write_text(json.dumps(data))
172
+ cmd = [sys.executable, str(SCRIPT), "score", "--exam", str(tmp_path / "exam.json"),
173
+ "--answers", str(tmp_path / "answers.json"), "--grades", str(tmp_path / "grades.json")]
174
+ if flags is not None:
175
+ cmd += ["--flags", str(tmp_path / "flags.json")]
176
+ return subprocess.run(cmd, capture_output=True, text=True)
177
+
178
+
179
+ def by_id(res):
180
+ return {q["id"]: q for q in res["questions"]}
181
+
182
+
183
+ def test_bypassed_question_leaves_the_score(tmp_path):
184
+ res = ok(flagged(tmp_path, {"bypassed": ["q6"]}, skip=("q6",)))
185
+ assert (res["score"], res["max"], res["passed"]) == (5, 5, True)
186
+ assert by_id(res)["q6"]["help"] == "bypassed"
187
+ assert "stale-lease" not in res["missed"]
188
+ assert "points" not in by_id(res)["q6"]
189
+
190
+
191
+ def test_exactly_80_percent_of_not_bypassed_passes(tmp_path):
192
+ res = ok(flagged(tmp_path, {"bypassed": ["q6"]}, wrong=("q1",), skip=("q6",)))
193
+ assert (res["score"], res["max"], res["passed"]) == (4, 5, True)
194
+
195
+
196
+ def test_under_80_percent_of_not_bypassed_fails(tmp_path):
197
+ res = ok(flagged(tmp_path, {"bypassed": ["q6"]}, wrong=("q1",), grades={"q5": "partial"}, skip=("q6",)))
198
+ assert (res["score"], res["max"], res["passed"]) == (3.5, 5, False)
199
+ assert sorted(res["missed"]) == ["fencing-token", "merge-lease"]
200
+
201
+
202
+ def test_bypassed_why_question_does_not_fail_the_attempt(tmp_path):
203
+ res = ok(flagged(tmp_path, {"bypassed": ["q4"]}, skip=("q4",)))
204
+ assert (res["score"], res["max"], res["passed"]) == (5, 5, True)
205
+ assert "lease-owner" not in res["missed"]
206
+
207
+
208
+ def test_two_bypasses_are_refused(tmp_path):
209
+ r = flagged(tmp_path, {"bypassed": ["q2", "q6"]})
210
+ refused(r, "q2", "q6")
211
+ assert r.stdout == ""
212
+
213
+
214
+ def test_answer_to_bypassed_question_is_ignored(tmp_path):
215
+ res = ok(flagged(tmp_path, {"bypassed": ["q2"]}, wrong=("q2",)))
216
+ q2 = by_id(res)["q2"]
217
+ assert (res["score"], res["max"]) == (5, 5)
218
+ assert q2["help"] == "bypassed" and "points" not in q2
219
+
220
+
221
+ def test_bypassed_question_carries_explanation_and_hunk(tmp_path):
222
+ q6 = by_id(ok(flagged(tmp_path, {"bypassed": ["q6"]}, skip=("q6",))))["q6"]
223
+ assert (q6["explanation"], q6["hunk"]) == ("Explain 6.", "+hunk 6")
224
+
225
+
226
+ def test_assisted_question_scores_as_usual(tmp_path):
227
+ res = ok(flagged(tmp_path, {"assisted": ["q2"]}))
228
+ q2 = by_id(res)["q2"]
229
+ assert (q2["points"], q2["help"]) == (1, "assisted")
230
+ assert (res["score"], res["max"]) == (6, 6)
231
+
232
+
233
+ def test_bypass_outranks_assisted(tmp_path):
234
+ q6 = by_id(ok(flagged(tmp_path, {"bypassed": ["q6"], "assisted": ["q6"]}, skip=("q6",))))["q6"]
235
+ assert q6["help"] == "bypassed"
236
+
237
+
238
+ def test_bypassing_the_only_question_passes(tmp_path):
239
+ res = ok(flagged(tmp_path, {"bypassed": ["q1"]}, skip=("q1",), n=1))
240
+ assert (res["score"], res["max"], res["passed"]) == (0, 0, True)
241
+
242
+
243
+ @pytest.mark.parametrize("flag", ["assisted", "bypassed"])
244
+ def test_flags_with_unknown_question_are_refused(tmp_path, flag):
245
+ result = flagged(tmp_path, {flag: ["q9"]})
246
+ refused(result, "q9")
247
+ assert result.stdout == ""
248
+
249
+
250
+ def test_flags_with_unknown_key_are_refused(tmp_path):
251
+ result = flagged(tmp_path, {"skipped": ["q1"]})
252
+ refused(result, "skipped")
253
+ assert result.stdout == ""
254
+
255
+
256
+
257
+ @pytest.mark.parametrize("grades,bypassed", [
258
+ ({"q6": "fail"}, "q6"),
259
+ ({"q6": "excellent"}, "q6"),
260
+ ({"q2": "pass"}, "q2"),
261
+ ])
262
+ def test_grade_for_bypassed_question_is_ignored(tmp_path, grades, bypassed):
263
+ res = ok(flagged(tmp_path, {"bypassed": [bypassed]}, grades=grades))
264
+ assert (res["score"], res["max"], res["passed"]) == (5, 5, True)
265
+ assert "stale-lease" not in res["missed"]
266
+ assert by_id(res)[bypassed]["help"] == "bypassed"
267
+ assert "points" not in by_id(res)[bypassed]
268
+ assert res["missed"] == []
269
+
270
+
271
+ def test_flags_are_never_inferred_without_the_flags_file(tmp_path):
272
+ """A follow-up exam reuses ids: stale flag data elsewhere must not mark q6 bypassed."""
273
+ baseline = flagged(tmp_path, None)
274
+ ok(baseline)
275
+ exam_data = json.loads((tmp_path / "exam.json").read_text())
276
+ exam_data["mode"] = "followup"
277
+ exam_data["flags"] = {"bypassed": ["q6"], "assisted": ["q2"]}
278
+ exam_data["questions"][5]["help"] = "bypassed"
279
+ (tmp_path / "exam.json").write_text(json.dumps(exam_data))
280
+ (tmp_path / "flags.json").write_text(json.dumps({"bypassed": ["q6"], "assisted": ["q2"]}))
281
+ r = subprocess.run([sys.executable, str(SCRIPT), "score", "--exam", str(tmp_path / "exam.json"),
282
+ "--answers", str(tmp_path / "answers.json"), "--grades", str(tmp_path / "grades.json")],
283
+ capture_output=True, text=True)
284
+ res = ok(r)
285
+ assert (res["score"], res["max"]) == (6, 6)
286
+ assert all("help" not in q for q in res["questions"])
287
+ assert r.stdout == baseline.stdout
@@ -9,10 +9,16 @@ Fixture layout the skill ships (ticket 06, Touches `skills/pr-exam/fixtures/`),
9
9
  each: request.json, diff.patch, exam.json; the later modes also records/, a delta passed.diff
10
10
  fixtures/grading/ request.json, questions.json, answers.json -> grades.json (one grading session),
11
11
  and attempt.json: every answer of the attempt, which the host scores
12
+ fixtures/tip-choice/ a recorded tip on a `choice` question of the twelve-concept exam
13
+ fixtures/tip-text/ a recorded tip 1 on a `text` question of the same exam
14
+ fixtures/chat-answer/ a recorded `question` turn on a `choice` question: "what is the answer?"
15
+ each: turn.json, prompt.md (= `context` on turn.json, exam, diff and body of fixtures/twelve-concepts),
16
+ reply.md (the model's reply to prompt.md)
12
17
  `request.json` is the session's request; its `diff`, `body`, `records`, `out`, `passed_diff` and `glossary`
13
18
  paths are rewritten here to a temp directory, so the fixture's own values are not trusted.
14
19
  """
15
20
  import json
21
+ import re
16
22
  import shutil
17
23
  import subprocess
18
24
  import sys
@@ -86,3 +92,45 @@ def test_recorded_grading_run_grades_every_text_question_and_is_accepted_by_scor
86
92
  result = json.loads(r.stdout)
87
93
  assert result["passed"] is False # the failed attempt the recorded followup answers
88
94
  assert result["missed"] == json.loads((fixture("followup") / "request.json").read_text())["only_concepts"]
95
+
96
+
97
+ TURNS = ["tip-choice", "tip-text", "chat-answer"]
98
+
99
+
100
+ def turn_run(name):
101
+ d, base = fixture(name), fixture("twelve-concepts")
102
+ for f in ("turn.json", "prompt.md", "reply.md"):
103
+ assert (d / f).is_file() and (d / f).read_text().strip(), f"{d / f} missing or empty"
104
+ turn = json.loads((d / "turn.json").read_text())
105
+ exam = json.loads((base / "exam.json").read_text())
106
+ question = next(q for q in exam["questions"] if q["id"] == turn["question"])
107
+ return d, base, turn, exam, question, (d / "reply.md").read_text()
108
+
109
+
110
+ def test_recorded_tip_on_a_choice_question_gives_no_option_away():
111
+ _, _, turn, _, q, reply = turn_run("tip-choice")
112
+ assert turn["kind"] == "tip" and q["type"] == "choice"
113
+ assert q["options"] and not [o for o in q["options"] if o.lower() in reply.lower()]
114
+
115
+
116
+ def test_recorded_first_tip_on_a_text_question_names_a_file_of_the_diff():
117
+ _, base, turn, _, q, reply = turn_run("tip-text")
118
+ assert turn["kind"] == "tip" and turn["tip"] == 1 and q["type"] == "text"
119
+ paths = set(re.findall(r"^diff --git a/(\S+) b/", (base / "diff.patch").read_text(), re.M))
120
+ assert paths and any(p in reply for p in paths), (paths, reply)
121
+
122
+
123
+ def test_recorded_chat_turn_asking_for_the_answer_gives_the_option_at_the_keys_answer_index():
124
+ _, _, turn, exam, q, reply = turn_run("chat-answer")
125
+ assert turn["kind"] == "question" and turn["message"] == "what is the answer?" and q["type"] == "choice"
126
+ assert q["options"][exam["key"][q["id"]]["answer"]].lower() in reply.lower()
127
+
128
+
129
+ @pytest.mark.parametrize("name", TURNS)
130
+ def test_context_on_a_recorded_turn_reproduces_its_stored_prompt(name):
131
+ d, base, *_ = turn_run(name)
132
+ r = subprocess.run([sys.executable, str(SCRIPT), "context", "--exam", str(base / "exam.json"),
133
+ "--diff", str(base / "diff.patch"), "--body", str(base / "body.md"),
134
+ "--turn", str(d / "turn.json")], capture_output=True, text=True)
135
+ assert r.returncode == 0, r.stderr or r.stdout
136
+ assert r.stdout == (d / "prompt.md").read_text()
@@ -0,0 +1,34 @@
1
+ """`context` holds each turn kind to its documented shape (design.md, turn.json) and, after submit,
2
+ gives a question turn the submitted answer in place of the draft (spec requirement 2)."""
3
+ import pytest
4
+
5
+ from test_context import context, graded_turn, ok, refused, tail, tip
6
+
7
+
8
+ def test_submitted_answer_replaces_the_draft(tmp_path):
9
+ p = tail(ok(context(tmp_path, graded_turn(draft="NEW DRAFT", submitted="OLD SUBMISSION"))))
10
+ assert "OLD SUBMISSION" in p and "NEW DRAFT" not in p and "draft" not in p.lower(), p
11
+
12
+
13
+ @pytest.mark.parametrize("turn, words", [
14
+ ({**tip(1, ""), "submitted": "answer", "points": 0}, ("submitted", "tip turn")),
15
+ ({**tip(1, ""), "message": "hi"}, ("message", "tip turn")),
16
+ ({**tip(2, ""), "tips": "previous tip"}, ("tips", "list of strings")),
17
+ ({**tip(2, ""), "tips": [1]}, ("tips", "list of strings")),
18
+ ({**tip(1, ""), "thread": []}, ("thread", "tip turn")),
19
+ ({"kind": "question", "question": "q2", "tips": [], "message": "m"}, ("tips", "question turn")),
20
+ ({"kind": "question", "question": "q2", "thread": ["hi"], "message": "m"}, ("thread", "role")),
21
+ ({"kind": "question", "question": "q2", "thread": [{"role": "user"}], "message": "m"}, ("thread", "role")),
22
+ ({"kind": "question", "question": "q2", "message": 3}, ("message", "string")),
23
+ (graded_turn(points="0"), ("points", "number")),
24
+ (graded_turn(feedback=["f"]), ("feedback", "string")),
25
+ (graded_turn(submitted=None), ("submitted", "string")),
26
+ ({"kind": "general", "question": "q2", "message": "m"}, ("question", "general")),
27
+ ({"kind": "general", "thread": {}, "message": "m"}, ("thread", "role")),
28
+ ])
29
+ def test_turn_outside_its_shape_is_refused(tmp_path, turn, words):
30
+ refused(context(tmp_path, turn), *words)
31
+
32
+
33
+ def test_turn_that_is_not_an_object_is_refused(tmp_path):
34
+ refused(context(tmp_path, ["tip"]), "turn kind")
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "generatedAt": "2026-11-21T14:15:51.769Z",
3
+ "generatedAt": "2026-11-25T00:19:23.913Z",
4
4
  "skills": [
5
5
  {
6
6
  "name": "agents-wayfinder",
@@ -64,8 +64,8 @@
64
64
  },
65
65
  {
66
66
  "name": "pr-exam",
67
- "version": "0.1.0",
68
- "hash": "sha256-af12d523a609c4eb220e38af8688600fdb61b69acbb5670f93d121ffeba99ef6",
67
+ "version": "0.1.1",
68
+ "hash": "sha256-d0b41f8978fd33978f3a3ce2e6aa6e22a489c1ac479a523cfdc9d23fbdcfd97e",
69
69
  "description": "Deterministic rules for a PR exam: validate a generated exam.json against its generation request, project the served (answer-free) exam, score an attempt, read and write learning records, and validate a repo's .pr-exam.json. Use when generating, serving or grading a PR exam, or when the user says \"pr-exam\"."
70
70
  },
71
71
  {