@jesdi/skills 0.0.102 → 0.0.104

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.
@@ -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)