From 034b4d83e194c2d96a30c1465effad86254979ca Mon Sep 17 00:00:00 2001 From: Anthony Giacalone Date: Tue, 20 Oct 2026 10:04:47 -0700 Subject: [PATCH] Emit a per-outcome GRADING_NOTE.md with every Gradescope build MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The grading note was a one-line-per-question summary, which left graders to invent the Gradescope rubric. It now lists one rubric row per possible outcome of each question (each MC choice, both T/F sides, each FIB blank plus a wrong-order row, and every item of an authored Gradescope rubric block), with its points and a form·Qn·slot key. Graders enter the rows and only pick which one applies, and reg-gradescope-stats reads the note directly, which closes the documented format gap. Graduated from the CECS 378 Su26 prototype into lectern.grading_note. A code question keyed True/False no longer loses its credit, and math in choices renders as 2^(n/2). New --grading-note-only rewrites just the note for an exam that is already printed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012VAyCxeJ3nhHwBM5ABHMqN --- CHANGELOG.md | 4 +- README.md | 2 +- SKILL.md | 9 ++ docs/gradescope-workflow.md | 34 +++++- examples/cecs-378-demo/README.md | 10 +- lectern/exam_build.py | 13 +++ lectern/exam_pack.py | 92 +++++---------- lectern/grading_note.py | 190 +++++++++++++++++++++++++++++++ tests/test_exam_pack.py | 116 ++++++++++++++++--- 9 files changed, 378 insertions(+), 92 deletions(-) create mode 100644 lectern/grading_note.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 239bef2..1d42c6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to lectern are documented here. ## [Unreleased] ### Added +- **`reg-exam-build` writes a per-outcome `GRADING_NOTE.md` for every Gradescope build.** The note was a one-line-per-question summary table, which left the grader to invent the Gradescope rubric. It is now the ISA work order: every question gets one rubric row per possible outcome (each MC choice, both T/F sides, each FIB blank plus a wrong-order row, and every item of an authored `Gradescope rubric` block on written questions), with the points that row carries and a stable `form·Qn·slot` key. Graders enter the rows verbatim and only choose which one applies, so points land the same way whoever grades, and `reg-gradescope-stats` reads the note directly. Graduated from the CECS 378 Su26 prototype (`build_grading_note.py`) into `lectern.grading_note`, with two fixes on the way: a code question keyed True/False no longer loses its credit to a trailing brace, and math in choices renders as `2^(n/2)` rather than `2^{n/2`. `% order: any` before a multi-blank fill drops the wrong-order row. New **`--grading-note-only`** rewrites just the note for an exam that is already printed. - **`reg-guardcheck`: the student's half of the guard-file check.** The instructor-side check reads git history from outside the student's control and is the record; this is the notice the *student* sees, in the CI run they already look at. `stamp` records a template's expected digests to `grading/guard.sha256` (`sha256sum`-format, so `sha256sum -c` verifies it with no tooling); `check` runs as one step in the lab's own `autograde.yml` and reports what changed. ==It notifies, it never grades==: no points, no pass/fail, and it always exits 0 (`--strict` opts out) because failing a student's build over a file that does not affect their program is a bad way to open a conversation. It never invents a `result.json` either, since a result file conjured from nothing reads downstream as a zero-point run; it only records a `notices` array in one that already exists. The message is deliberately unaccusing: what changed, that it does not affect the assignment or the grade, that the instructor sees it in the history, and the `git checkout` line that restores it, plus a GitHub Actions run annotation. Stdlib-only, so a template vendors the single file as `grading/guardcheck.py` and the runner's bare `python3` runs it. Workflow snippet at `lectern/references/guardcheck.workflow.yml`. ==A student controls their own workflow, so this is a courtesy and not evidence==: the sweep is what counts. - **Guard-file integrity: grading checks for repos that modify `AGENTS.md`.** Every lab template ships `AGENTS.md`, the high-authority AI-assistant surface, and the doctrine has always been that a student may delete it because doing so is a visible act in the git history. Nothing actually looked. The new `lectern.triage_guardfile` module compares each declared **guard file** at the grading commit against its baseline and reports `intact`, `modified`, `deleted` or `absent`, with the commits that touched it and a copy-pasteable reproduce command. Wired into all three surfaces: `reg-triage sweep` (a `guard` column in `results.csv`, a Guard column and a *Guard files* roll-up in `TRIAGE.md`), `reg-triage report` (section **A.6 Guard-file integrity**), and `reg-lab-recon` (a `guard` column in `cohort.csv`, a *Guard files* section in `FACTS.md`). Both manifests take `guard_files:`, defaulting to `["AGENTS.md"]`; an entry may be `{path, sha256}` to compare against the file **as distributed**, which is the only way to catch an edit made inside a squashed initial commit. Otherwise the baseline is the file's first appearance in that repo, and a file born modified reads as intact. ==It is a Part A fact and never a score==: `guardfile_forensics` does not register in `SIGNALS`, awards no points, and cannot move a bucket, because there are innocuous reasons to touch these files and the engine's standing rule is that no adverse finding is automated. Report schema bumped to v2; the signal set is unchanged. - **`reg-admin-form` — campus administrative forms, filled from the vault.** Admin forms are haphazard: no dropdowns, and they still want exact course numbers, class numbers, rooms, meeting times and a coverage plan — facts the vault already holds and that are miserable to retype from memory on a sick morning. A YAML **form profile** declares one form's fields and where each value comes from (`instructor.*` from an `identity.yaml`, `leave.*`, `term.*`, `absence.*`, `classes.*`, `literal:`, or `prompt`); the engine resolves them and writes a paste-per-box `FORM.md`, a routing `EMAIL.md`, and a machine `record.yaml`. The deterministic core is the new **`class_calendar`** module: it parses both `meets` dialects (`"TuTh 11:00-12:15"` and `"TuTh 11:00 AM–12:15 PM"`, any Unicode dash, bare `T` = Tuesday, and a trailing meridiem that carries back so `3:30-4:45 PM` is not an 03:30 class), expands each section across the requested dates, and subtracts term boundaries plus the term-spec's new optional **`no-instruction`** closures — so a Thanksgiving absence doesn't bill classes that were never going to meet. Each affected meeting is annotated with the topic its syllabus *Week of* table scheduled. Leave types carry `omit:` / `defaults:` / `guidance:`, so the **personal holiday omits *justification* on purpose** — it is contractual time off, and an empty "Reason" box invites volunteering one. Ships the **CSULB Notice of Absence** profile (SSO chiclet → DocuSign) with the chair/coordinator/associate-dean routing pinned. Adding a form is a profile, not code. Fields carry an optional **`section:`** and render grouped under it in profile order — a paste-per-box product is only useful in the form's own box order, so the Notice of Absence profile mirrors DocuSign's two screens (the PowerForm signer-information gate, then the absence form) and records **Associate Dean before Department Coordinator**, as the screen actually orders them. Fields with **`choices:`** render as a tick-list with the right box marked (a checkbox is ticked, not pasted); an out-of-range value and a section split across the profile are both rejected as authoring bugs. The shipped Notice of Absence profile is **verified against a completed DocuSign envelope** — it is a *class-delivery* form under CFA CBA Art. 24.6, not a timekeeping one, so it asks for class numbers + catalog titles (new `classes.numbers-titles` source, fed by an optional `title:` on each term-spec section), a delivery-change checkbox, a reason checkbox, and the arrangements for students — no employee ID, hours, or department. Leave types map onto the form's own reason vocabulary via `defaults:`, and the profile records that DocuSign marks the free-text `Other:` box required even when a named reason is ticked. Slash command **`/timeoff`**; `reg-admin-form init` seeds the vault, `list` shows forms + leave types, `render` does the work. A fourth product, the **Obsidian record note** (`-
.md`), carries Dataview-queryable frontmatter (`type: absence-record`, dates, hours, contact-hours, sections-affected, `status: draft`) so a semester note can list the term's absences on its own; `status` flips to `submitted` by hand, since nothing the tool can observe proves DocuSign went through. @@ -23,9 +24,6 @@ All notable changes to lectern are documented here. - **True/False exam questions now use stacked `(a) True / (b) False` choices** — the house standard documented in `references/reference_exam.tex` and `docs/design/exam-tex-format.md`. The previous inline `\textsc{T~/~F.}` form listed no answer options on their own lines, so Gradescope's region detection could not find them. The `\textsc{T~/~F.}` label and inline `Answer:` reveal are retained, so questions stay typed `tf` and `parse_outline_from_tex` still emits `True`/`False` in `_outline.csv` — no code change, purely an authoring-convention fix. - **Refreshed the `examples/cecs-378-demo` worked example** to cover the current command surface. The demo exam gains a stacked-T/F section and a `gradescope: region` build (emitting `gradescope/` + `GRADING_NOTE.md`), and the README adds runnable stages for `reg-syllabus` (stamp + build), `reg-qbank` (validate + emit), `reg-exam-readinglist` (Lectern→Scriptorium seam), and `reg-gradescope-stats` (item analysis), plus a documented "requires live infrastructure" section for the Classroom / ISA-publish / triage / term-finalize verbs. -### Known gaps -- **`reg-exam-build` GRADING_NOTE.md ≠ `reg-gradescope-stats` input format.** The build emits a summary-table grading note (`| Q | Name | Pts | Type | Answer | Rubric |`); `reg-gradescope-stats` parses the richer per-question form (`#### ·Q · … · ` + `| Pts | Key | Rubric item |`). The demo's gradescope-stats stage uses a hand-authored stats-compatible note; bridging the two is a tracked follow-up. - ### Security - **Vendored `slugify`, dropped the `vaultkit` dependency** — the name `vaultkit` on PyPI is an unrelated third-party SDK, so depending on it was a dependency-confusion risk. The one helper used (`slugify`) is now inlined in `lectern/_text.py`, making the public distribution self-contained with no private/ambiguous dependency. diff --git a/README.md b/README.md index def06a0..b3dd1bc 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ This is a deliberate design principle, not an accident. Proprietary LMS gradeboo **Grade-appeal reproducibility:** a build is fully deterministic. Given the same manifest, `.tex` sources, roster, and `assign_seed`, re-running `reg-exam-build` regenerates byte-identical content. This means a disputed paper can always be reproduced from archived sources — even weeks after the exam. See [docs/design/exam-tex-format.md](docs/design/exam-tex-format.md) for the full appeals runbook. -**Gradescope products:** set `gradescope: region` or `gradescope: bubble` in the manifest to emit a `gradescope/` directory with per-form template PDFs, answer-key PDFs, and outline CSVs ready for Gradescope import. See [docs/gradescope-workflow.md](docs/gradescope-workflow.md). +**Gradescope products:** set `gradescope: region` or `gradescope: bubble` in the manifest to emit a `gradescope/` directory with per-form template PDFs, answer-key PDFs, and outline CSVs ready for Gradescope import, plus a per-outcome `GRADING_NOTE.md`: every question's Gradescope rubric items with their points, for graders to enter and apply. `--grading-note-only` refreshes just the note. See [docs/gradescope-workflow.md](docs/gradescope-workflow.md). ### Term lifecycle diff --git a/SKILL.md b/SKILL.md index 186758a..b1897ea 100644 --- a/SKILL.md +++ b/SKILL.md @@ -417,6 +417,15 @@ Produced only when `gradescope:` is `region` or `bubble`. **region** → per-for versions) + outline; plus `gradescope_roster.csv` (Email column blank — see README caveat; prefer LMS/LTI sync). Full details in README `### Gradescope products`. +Every Gradescope build also writes **`GRADING_NOTE.md`** next to the manifest: the +ISA work order, with **one rubric row per possible outcome** of every question +(each MC choice, both T/F sides, each FIB blank + a wrong-order row, every item of +an authored `Gradescope rubric` block on written questions), its points, and a +`form·Qn·slot` key that `reg-gradescope-stats` joins back to the evaluations +export. Graders enter the rows verbatim and only pick which applies. For an exam +already printed, `reg-exam-build exam.build.yaml --grading-note-only` rewrites just +the note. + > **How to grade the result in Gradescope** — step-by-step (region/bubble setup, A/B > Version Sets, roster, the per-student-serial identity/appeals integration): > `notes/gradescope-exam-workflow.md`. diff --git a/docs/gradescope-workflow.md b/docs/gradescope-workflow.md index 3586699..77414a7 100644 --- a/docs/gradescope-workflow.md +++ b/docs/gradescope-workflow.md @@ -34,10 +34,11 @@ Set `gradescope: region` or `gradescope: bubble` in `exam.build.yaml`, then run `print_layout: per-form` for the legacy per-form `_combined.pdf` stacks.)* - **`gradescope/`** — the import products covered in this document. - **`GRADING_NOTE.md`** — the grading note (next to the manifest). One Markdown - file per exam: exam identity, the Gradescope setup steps, and a per-form - answer-key + rubric table. Gradescope imports no key or rubric, so this is the - human crib a grader works from — and it is self-contained enough to hand to a - TA/ISA who did not author the exam. See §1a. + file per exam: exam identity, the Gradescope setup steps, and for every + question **one rubric row per possible outcome**, with its points. Gradescope + imports no key or rubric, so this is the work order a grader enters and then + grades from. It is self-contained enough to hand to a TA/ISA who did not + author the exam. See §1a. ### 1a. The grading note (`GRADING_NOTE.md`) @@ -54,7 +55,30 @@ comments authored directly above each question's `\item` in the exam `.tex`: question number). `% rubric:` is required on `fib` and `code` questions and optional on `mc`/`tf` (which default to "correct choice = full points, else 0"). The note collects all forms, so an A/B exam yields one note with a `## Form A` and -`## Form B` section, each a `Q · Name · Pts · Type · Answer · Rubric` table. +`## Form B` section. + +**Every outcome gets a row.** Each question is a `#### ·Q · name · pts · +TYPE` heading over a `| Pts | Key | Rubric item |` table. The grader enters every +row into Gradescope as a rubric item and then only decides which one applies, so a +grader who did not write the question applies points the same way, and a student +can see that every alternative was considered. + +| Type | Rows | +|---|---| +| `mc` | one per choice, `(a)`…; only the `\correctchoice` carries `+N` | +| `tf` | `True` and `False`; the keyed side carries `+N` | +| `fib` | one per blank (`+N` each when the points divide evenly, else `·` and the *Scoring* caption rules), plus an `order` row for multi-blank fills unless `% order: any` precedes the question | +| `code` / written | the question's authored **Gradescope rubric** block, item for item, with its category as a `[Group]` tag (see `docs/design/exam-tex-format.md`); a code question whose answer is True/False gets the two T/F rows | + +Every question also ends with a `none` row (*No answer / multiple marks*) unless +its authored rubric has its own catch-all. Credit is carried by the points: `+N` +rows credit, `0` rows do not and exist for feedback and statistics. Each row's +`form·Qn·slot` key is what `reg-gradescope-stats` joins to Gradescope's *Export +Evaluations* columns for per-distractor item analysis. + +To refresh the note after editing an exam that is already printed, run +`reg-exam-build exam.build.yaml --grading-note-only`. It reads the form sources +and rewrites only `GRADING_NOTE.md`; no PDFs are rebuilt. ### Region target (fixed-template, rubric grading) — the standard diff --git a/examples/cecs-378-demo/README.md b/examples/cecs-378-demo/README.md index 63123c3..6221068 100644 --- a/examples/cecs-378-demo/README.md +++ b/examples/cecs-378-demo/README.md @@ -441,12 +441,10 @@ reg-gradescope-stats \ counts, and flags **dead** distractors (chosen by nobody) and possible **miskeys** (a distractor chosen more than the key). -> **Known format gap.** `reg-exam-build` emits a *summary-table* `GRADING_NOTE.md` -> (`| Q | Name | Pts | Type | Answer | Rubric |`), but `reg-gradescope-stats` -> consumes the richer *per-question* form (`#### ·Q · · · ` -> with `| Pts | Key | Rubric item |` tables). They do not yet match, so this stage -> uses a hand-authored stats-compatible note at `gradescope-stats/GRADING_NOTE.md`. -> Bridging the two formats is a tracked follow-up. +> **Note format.** `reg-exam-build` now emits the per-outcome `GRADING_NOTE.md` +> that `reg-gradescope-stats` reads, so the build's own note can be passed with +> `--grading-note`. This stage keeps its hand-authored note at +> `gradescope-stats/GRADING_NOTE.md` so the sample evaluation CSVs stay matched to it. --- diff --git a/lectern/exam_build.py b/lectern/exam_build.py index 080ba43..c1e072e 100644 --- a/lectern/exam_build.py +++ b/lectern/exam_build.py @@ -376,6 +376,11 @@ def _build_parser() -> argparse.ArgumentParser: default=None, help="(with --roster) write register CSV here (default: _serials.csv next to source)", ) + p.add_argument( + "--grading-note-only", + action="store_true", + help="(with a .yaml manifest) rewrite only GRADING_NOTE.md; no PDFs are rebuilt", + ) return p @@ -389,6 +394,10 @@ def main(argv: list[str] | None = None) -> int: parser.error("--roster/--combined/--register are not valid with a .yaml manifest " "(configure them in the manifest instead)") manifest = exam_pack.load_manifest(args.source) + if args.grading_note_only: + note = exam_pack.write_grading_note(manifest, args.source.parent) + print(f" + {note.name} (per-outcome rubric, {len(manifest.forms)} form(s))") + return 0 result = exam_pack.run(manifest, args.source.parent) print(f" forms: {', '.join(result.forms)}") print(f" + build/ ({result.student_pdf_count} student PDF(s))") @@ -403,8 +412,12 @@ def main(argv: list[str] | None = None) -> int: print(f" + {shown}") if result.gradescope_dir: print(f" + gradescope/ ({manifest.gradescope})") + if result.grading_note: + print(f" + {result.grading_note.name} (per-outcome rubric)") return 0 + if args.grading_note_only: + parser.error("--grading-note-only requires a .yaml manifest") if args.combined and args.roster is None: parser.error("--combined requires --roster") if args.register is not None and args.roster is None: diff --git a/lectern/exam_pack.py b/lectern/exam_pack.py index 46d3f27..e896098 100644 --- a/lectern/exam_pack.py +++ b/lectern/exam_pack.py @@ -14,12 +14,13 @@ import shutil import subprocess import sys -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path import yaml from lectern.exam_serial import canonical_name from lectern.exam_build import ExamBuildConfig, build_variant, build_roster, _concat_pdfs +from lectern import grading_note _VALID_ASSIGN = {"alternating", "seeded-random", "every-form"} _VALID_GRADESCOPE = {"region", "bubble", "none"} @@ -60,6 +61,7 @@ class OutlineRow: answer: str name: str = "" rubric: str = "" + block: str = field(default="", repr=False, compare=False) # raw .tex, for the grading note @dataclass @@ -239,7 +241,7 @@ def parse_outline_from_tex(tex_content: str) -> list[OutlineRow]: ) rubric = f"Correct = {answer} ({int(m_pts.group(1))} pts, all-or-nothing)." rows.append(OutlineRow(q_num=q, points=int(m_pts.group(1)), type=qtype, - answer=answer, name=name, rubric=rubric)) + answer=answer, name=name, rubric=rubric, block=block)) return rows @@ -326,64 +328,26 @@ def _pdf_page_count(pdf_path: Path) -> int: return 0 -def _course_tag(course: str) -> str: - return course.strip().lower().replace(" ", "-") +def emit_grading_note(manifest, per_form_outline, per_form_pages, exam_root, + per_form_orders=None) -> Path: + """Write the per-outcome GRADING_NOTE.md (see lectern.grading_note).""" + return grading_note.emit(manifest, per_form_outline, per_form_pages, exam_root, + per_form_orders) -def _grading_note_table(rows) -> str: - head = "| Q | Name | Pts | Type | Answer | Rubric |\n| -: | --- | -: | --- | --- | --- |" - body = "\n".join( - f"| {r.q_num} | {r.name} | {r.points} | {r.type} | {r.answer} | " - f"{r.rubric.replace(chr(10), ' ')} |" - for r in rows - ) - return head + "\n" + body - - -def emit_grading_note(manifest, per_form_outline, per_form_pages, exam_root) -> Path: - exam_root = Path(exam_root) - out = exam_root / "GRADING_NOTE.md" - forms = [f.id for f in manifest.forms] - total_pts = sum(r.points for r in next(iter(per_form_outline.values()))) - nq = sum(len(v) for v in per_form_outline.values()) - pages = per_form_pages.get(forms[0], 0) - tag = _course_tag(manifest.course) - - fm = ( - "---\n" - f"type: grading-note\n" - f"tags: [teaching, {tag}, exam, gradescope, answer-key, internal]\n" - "visibility: private\n" - "icon: LiClipboardCheck\n" - "iconColor: var(--color-red)\n" - "---\n" - ) - parts = [ - fm, - f"# {manifest.exam} — Gradescope Grading Note ({manifest.course} {manifest.term})\n", - "> [!warning] Internal — answer key\n" - "> Grader/ISA only. Never student-facing. Serials/register are grader " - "infra (see [[project_exam_serial_internal_only]]).\n", - f"{total_pts} pts · {nq} questions · {len(forms)} forms · {pages}/exam\n", - "## Gradescope setup\n" - "1. Two assignments — one per form — linked as a **Version Set**.\n" - "2. Upload `gradescope/_template.pdf` (the BLANK form) as each template.\n" - "3. Build the outline: one region per question, points from the table.\n" - "4. Enter the key in-UI (Gradescope imports nothing); keep " - "`gradescope/_answer_key.pdf` open.\n" - f"5. Upload each form's scanned stack to its own version; length = {pages} pages.\n", - ] - for fid in forms: - parts.append(f"## Form {fid}\n" + _grading_note_table(per_form_outline[fid]) + "\n") - # verify dir is always build/ — register.csv's output_pdf carries the - # .parts/ prefix in single layout, so it resolves relative to build/. - parts.append( - "## Appeals\n" - "Each paper's footer `Serial · ID` resolves to one student + form via " - "`reg-exam-verify --register build/register.csv --dir build/`.\n" - ) - out.write_text("\n".join(parts), encoding="utf-8") - return out +def write_grading_note(manifest, workdir: Path) -> Path: + """Regenerate only GRADING_NOTE.md from the form sources (no LaTeX run). + + Page counts come from the existing blank ``build/.pdf``; 0 if absent. + """ + workdir = Path(workdir) + outlines, pages, orders = {}, {}, {} + for form in manifest.forms: + tex = form.source.read_text() + outlines[form.id] = parse_outline_from_tex(tex) + orders[form.id] = grading_note.parse_orders(tex) + pages[form.id] = _pdf_page_count(workdir / "build" / f"{form.id}.pdf") + return emit_grading_note(manifest, outlines, pages, workdir, orders) def _read_names(roster_path: Path) -> list[str]: @@ -509,15 +473,18 @@ def _print_key(row): w.writerows(register_rows) gs_dir = None - grading_note = None + grading_note_path = None if manifest.gradescope != "none": gs_dir = workdir / "gradescope" gs_dir.mkdir(parents=True, exist_ok=True) per_form_outline = {} per_form_pages = {} + per_form_orders = {} for form in manifest.forms: - outline = parse_outline_from_tex(form.source.read_text()) + tex = form.source.read_text() + outline = parse_outline_from_tex(tex) per_form_outline[form.id] = outline + per_form_orders[form.id] = grading_note.parse_orders(tex) per_form_pages[form.id] = _pdf_page_count(blank_pdfs[form.id]) if manifest.gradescope == "region": emit_region_products(form.id, blank_pdfs[form.id], key_pdfs[form.id], outline, gs_dir) @@ -525,11 +492,12 @@ def _print_key(row): emit_bubble_products(form.id, outline, gs_dir) if manifest.roster is not None: emit_gradescope_roster(manifest.roster, gs_dir) - grading_note = emit_grading_note(manifest, per_form_outline, per_form_pages, workdir) + grading_note_path = emit_grading_note(manifest, per_form_outline, per_form_pages, workdir, + per_form_orders) return PackResult( forms=[f.id for f in manifest.forms], build_dir=build_dir, gradescope_dir=gs_dir, register_csv=register_csv, - student_pdf_count=student_pdf_count, grading_note=grading_note, + student_pdf_count=student_pdf_count, grading_note=grading_note_path, combined_pdf=combined_pdf, ) diff --git a/lectern/grading_note.py b/lectern/grading_note.py new file mode 100644 index 0000000..7f629a0 --- /dev/null +++ b/lectern/grading_note.py @@ -0,0 +1,190 @@ +"""Per-outcome GRADING_NOTE.md: the ISA work order for Gradescope. + +One rubric row per possible outcome of each question: every MC choice, both +True/False sides, each FIB blank, and each authored rubric item on written +questions. Credit is carried by the points (``+N`` credited, ``0`` not), so a +grader who did not write the exam only decides which row applies. Every row +has a stable ``form·Qn·slot`` key that ``reg-gradescope-stats`` joins back to +Gradescope's *Export Evaluations* columns for per-distractor statistics. + +Graduated from the Su26 prototype (``exam1_su26/build_grading_note.py``) so +that every ``reg-exam-build`` emits it. +""" +from __future__ import annotations + +import re +from pathlib import Path + +LETTERS = "abcdefgh" +_CHOICE_RE = re.compile(r"\\(correct|wrong)choice\{(.+?)\}\s*$", re.M) +_ORDER_RE = re.compile(r"^\s*%\s*order:\s*(.+?)\s*$") +_QSTART_RE = re.compile(r"\\item\b.*?\\textit\{\(\d+\s*pts?\)\}") +# Authored "Gradescope rubric" block (see docs/design/exam-tex-format.md): +# \item \textbf{+1}~ \textit{(category)} +_GS_ITEM_RE = re.compile(r"^\s*\\item\s*\\textbf\{\+(\d+)\}~(.+?)\s*$", re.M) +_CAT_RE = re.compile(r"\\textit\{\((.+?)\)\}") + + +def sanitize(s: str) -> str: + """LaTeX fragment -> plain text fit for a Gradescope rubric item.""" + s = s.replace("``", "“").replace("''", "”") + s = s.replace(r"\oplus", "⊕").replace(r"\bmod", " mod ") + s = s.replace(r"\_", "_").replace(r"\&", "&").replace(r"\%", "%").replace(r"\#", "#") + s = s.replace("~", " ").replace("---", "—").replace("--", "–") + s = re.sub(r"\$(.+?)\$", r"\1", s) + s = s.replace("$", "") + # exponents/subscripts: 2^{n} -> 2^n, 2^{2n} -> 2^(2n) + s = re.sub(r"([\^_])\{([^{}]+)\}", + lambda m: m.group(1) + (m.group(2) if len(m.group(2)) == 1 else f"({m.group(2)})"), s) + for _ in range(3): # unwrap nested \cmd{...} + s = re.sub(r"\\[a-zA-Z]+\*?\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + s = s.replace("{", "").replace("}", "") + return re.sub(r"\s+", " ", s).strip() + + +def _strip_comments(block: str) -> str: + return "\n".join(l for l in block.splitlines() if not re.match(r"^\s*%", l)) + + +def parse_orders(tex_content: str) -> dict[int, str]: + """1-based question number -> ``% order:`` value (default ``strict``).""" + body = tex_content.split("\\begin{document}", 1)[-1] + out: dict[int, str] = {} + q, pending = 0, "strict" + for line in body.splitlines(): + m = _ORDER_RE.match(line) + if m: + pending = m.group(1).strip().lower() + continue + if _QSTART_RE.search(line) and not line.lstrip().startswith("%"): + q += 1 + out[q] = pending + pending = "strict" + return out + + +def _authored_items(block: str) -> list[tuple[str, str]]: + """(pts, text) rows from an authored ``Gradescope rubric`` itemize, if any.""" + b = _strip_comments(block) + if "Gradescope rubric" not in b: + return [] + body = b.split("Gradescope rubric", 1)[1].split("\\end{itemize}", 1)[0] + rows = [] + for pts, rest in _GS_ITEM_RE.findall(body): + cats = _CAT_RE.findall(rest) + text = sanitize(_CAT_RE.split(rest)[0] if cats else rest) + if cats: + text += " [" + "; ".join(sanitize(c) for c in cats) + "]" + rows.append((f"+{pts}" if pts != "0" else "0", text)) + return rows + + +def outcome_rows(form: str, row, order: str = "strict") -> list[tuple[str, str, str]]: + """(pts, key, item text) for every outcome of one question.""" + n, pts, t = row.q_num, row.points, row.type + key = lambda slot: f"{form}·Q{n}·{slot}" + block = getattr(row, "block", "") or "" + + authored = _authored_items(block) + if authored: + return [(p, key(f"r{j}"), txt) for j, (p, txt) in enumerate(authored, 1)] + + rows: list[tuple[str, str, str]] = [] + answer = (row.answer or "").strip() + tf_answer = re.match(r"[A-Za-z]+", answer) + tf_answer = tf_answer.group(0).lower() if tf_answer else "" + + if t == "mc": + for idx, (kind, text) in enumerate(_CHOICE_RE.findall(_strip_comments(block))): + c = LETTERS[idx] + rows.append((f"+{pts}" if kind == "correct" else "0", key(c), f"({c}) {sanitize(text)}")) + if not rows and answer: # choices not marked up: credit the keyed letter only + rows.append((f"+{pts}", key(answer.lower()), f"({answer.lower()})")) + elif t == "tf" or (t == "code" and tf_answer in ("true", "false")): + for side in ("true", "false"): + slot = side[0].upper() if t == "tf" else side + rows.append((f"+{pts}" if side == tf_answer else "0", key(slot), side.capitalize())) + elif t == "fib" or t == "code": + seg = [sanitize(s) for s in answer.split(";") if s.strip()] + blanks = [re.split(r"\.\s|\(", s)[0].strip() for s in seg] or ["(see Scoring)"] + per = pts / len(blanks) + even = abs(per - round(per)) < 1e-9 + for j, b in enumerate(blanks, 1): + rows.append((f"+{int(round(per))}" if even else "·", key(f"b{j}"), + f"blank {j} = “{b}”" + ("" if even else " (see Scoring)"))) + if len(blanks) >= 2 and order != "any": + rows.append(("0", key("order"), "Incorrect order / wrong mapping (right values, wrong blanks)")) + rows.append(("0", key("none"), "No answer / multiple marks")) + return rows + + +def _course_tag(course: str) -> str: + return course.strip().lower().replace(" ", "-") + + +def render(manifest, per_form_outline, per_form_pages, per_form_orders=None) -> str: + forms = [f.id for f in manifest.forms] + per_form_orders = per_form_orders or {} + first = per_form_outline[forms[0]] + total_pts = sum(r.points for r in first) + nq = len(first) + pages = per_form_pages.get(forms[0], 0) + multi = len(forms) > 1 + + shape = f"{len(forms)} forms ({'/'.join(forms)})" if multi else f"single form {forms[0]}" + H = [ + "---", "type: grading-note", + f"tags: [teaching, {_course_tag(manifest.course)}, exam, gradescope, answer-key, internal]", + "visibility: private", "icon: LiClipboardCheck", "iconColor: var(--color-red)", + "---", "", + f"# {manifest.exam} — Gradescope Grading Note ({manifest.course} {manifest.term})", "", + "> [!warning] Internal — ISA work order", + "> Grader/ISA only, never student-facing. Enter each question's rubric items " + "into Gradescope **verbatim**. Grade by matching: your only decision per paper " + "is *which item applies*. Keys (`form·Qn·slot`) round-trip to per-distractor " + "statistics, so keep them intact. Serials/register are grader infra (see " + "[[project_exam_serial_internal_only]]).", "", + f"{total_pts} pts · {nq} questions · {shape} · {pages} pages/exam", "", + "## Gradescope setup", + ("1. One assignment per form, linked as a **Version Set**." if multi + else "1. One assignment: *Exam / Quiz*, fixed template."), + "2. Upload `gradescope/_template.pdf` (the BLANK form) as the template.", + "3. Per question: draw the region, then add **one rubric item per row** " + "(`Pts` + item text). Credit is the `+N` rows; `0` rows are no-credit " + "(apply them for feedback and statistics). A `[Group]` tag names the " + "criterion a written-answer item belongs to.", + (f"4. Upload each form's scanned stack to its own version; length = {pages} pages." + if multi else f"4. Upload the scanned stack; length = {pages} pages."), "", + "> [!note] Written-answer scoring", + "> `fib`/`code` questions carry a **Scoring** caption, which is the " + "authoritative rule. Where blanks don't divide evenly the per-blank rows are " + "reference only (marked `·`). When two credited items share a group, only " + "one counts.", "", + ] + for f in forms: + H.append(f"## Form {f}") + H.append("") + orders = per_form_orders.get(f, {}) + for r in per_form_outline[f]: + H.append(f"#### {f}·Q{r.q_num} · {r.name} · {r.points} pts · {r.type.upper()}") + if r.type in ("fib", "code") and r.rubric: + H.append(f"*Scoring:* {sanitize(r.rubric)}") + H.append("") # blank line before the table, or Obsidian won't render it + H += ["| Pts | Key | Rubric item (paste into Gradescope) |", "| --: | --- | --- |"] + for p, k, txt in outcome_rows(f, r, orders.get(r.q_num, "strict")): + H.append(f"| {p} | `{k}` | {txt.replace('|', '/')} |") + H.append("") + H += [ + "## Appeals", + "Each paper's footer `Serial · ID` resolves to one student + form via " + "`reg-exam-verify --register build/register.csv --dir build/`.", "", + ] + return "\n".join(H) + + +def emit(manifest, per_form_outline, per_form_pages, exam_root, per_form_orders=None) -> Path: + out = Path(exam_root) / "GRADING_NOTE.md" + out.write_text(render(manifest, per_form_outline, per_form_pages, per_form_orders), + encoding="utf-8") + return out diff --git a/tests/test_exam_pack.py b/tests/test_exam_pack.py index 376e292..40f8b04 100644 --- a/tests/test_exam_pack.py +++ b/tests/test_exam_pack.py @@ -233,29 +233,96 @@ def test_emit_gradescope_roster_columns(tmp_path): assert rows[0]["Email"] == "" # email not carried — left blank +MC_BLOCK = r"""\textit{(2 pts)} Which property? + \begin{enumerate}[label=(\alph*)] + \item \wrongchoice{Confidentiality} + \item \correctchoice{Availability} + \item \wrongchoice{Integrity \texttt{x}} + \end{enumerate} +""" + +CODE_BLOCK = r"""\textit{(3 pts)} Explain. + \ifanswers \par\smallskip \textbf{Gradescope rubric} \textit{(additive, 3 pts):} + \begin{itemize}[noitemsep] + \item \textbf{+1}~Names deadlock \textit{(Outcome)} + \item \textbf{+0}~Calls it ``starvation'' \textit{(Outcome)} + \item \textbf{+2}~Global lock order \textit{(Fix)} \textit{(only one counts)} + \item \textbf{+0}~Blank / off-topic \textit{(catchall)} + \end{itemize} + \fi +""" + + +def _note(tmp_path, a, b=None, orders=None): + forms = [FormSpec("A", tmp_path / "A.tex")] + ([FormSpec("B", tmp_path / "B.tex")] if b else []) + man = ExamManifest(course="CECS 378", term="su26", exam="Exam 1", forms=forms, + gradescope="region", points=4) + outlines = {"A": a, **({"B": b} if b else {})} + return emit_grading_note(man, outlines, {"A": 4, "B": 4}, tmp_path, orders).read_text() + + def test_emit_grading_note_structure(tmp_path): a = [ - OutlineRow(1, 2, "mc", "a", "CIA — confidentiality", "Correct = a (2 pts)."), + OutlineRow(1, 2, "mc", "b", "CIA — availability", "", block=MC_BLOCK), OutlineRow(2, 2, "fib", "confusion; diffusion", "FIB — Shannon", "1 pt/blank."), ] - b = [OutlineRow(1, 2, "mc", "c", "CIA — availability", "Correct = c (2 pts).")] - man = ExamManifest(course="CECS 378", term="su26", exam="Exam 1", - forms=[FormSpec("A", tmp_path / "A.tex"), - FormSpec("B", tmp_path / "B.tex")], - gradescope="region", points=4) - note = emit_grading_note( - man, {"A": a, "B": b}, {"A": 4, "B": 4}, tmp_path - ) - assert note == tmp_path / "GRADING_NOTE.md" - text = note.read_text() + b = [OutlineRow(1, 2, "mc", "c", "CIA — availability", "")] + text = _note(tmp_path, a, b) assert "type: grading-note" in text assert "tags: [teaching, cecs-378, exam, gradescope, answer-key, internal]" in text assert "## Form A" in text and "## Form B" in text - assert "CIA — confidentiality" in text - assert "confusion; diffusion" in text # FIB full answer in table - assert "4 pts · 3 questions · 2 forms · 4/exam" in text - assert "length = 4 pages" in text + assert "4 pts · 2 questions · 2 forms (A/B) · 4 pages/exam" in text + assert "Version Set" in text and "length = 4 pages" in text assert "[!warning] Internal" in text + # every MC choice is a row; only the keyed one carries credit + assert "#### A·Q1 · CIA — availability · 2 pts · MC" in text + assert "| 0 | `A·Q1·a` | (a) Confidentiality |" in text + assert "| +2 | `A·Q1·b` | (b) Availability |" in text + assert "| 0 | `A·Q1·c` | (c) Integrity x |" in text + assert "| 0 | `A·Q1·none` | No answer / multiple marks |" in text + # FIB: one credited row per blank, plus the strict-order row + assert "*Scoring:* 1 pt/blank." in text + assert "| +1 | `A·Q2·b1` | blank 1 = “confusion” |" in text + assert "| +1 | `A·Q2·b2` | blank 2 = “diffusion” |" in text + assert "`A·Q2·order`" in text + + +def test_grading_note_single_form_and_order_any(tmp_path): + a = [OutlineRow(1, 2, "fib", "56; 128", "FIB — key sizes", "1 pt/blank.")] + text = _note(tmp_path, a, orders={"A": {1: "any"}}) + assert "single form A" in text and "Version Set" not in text + assert "`A·Q1·order`" not in text + + +def test_grading_note_tf_and_code_true_false(tmp_path): + a = [OutlineRow(1, 1, "tf", "False", "T/F", ""), + OutlineRow(2, 2, "code", "False", "Code T/F", "2 pts, all-or-nothing.")] + text = _note(tmp_path, a) + assert "| 0 | `A·Q1·T` | True |" in text and "| +1 | `A·Q1·F` | False |" in text + assert "| +2 | `A·Q2·false` | False |" in text and "| 0 | `A·Q2·true` | True |" in text + + +def test_grading_note_uses_authored_gradescope_rubric(tmp_path): + a = [OutlineRow(1, 3, "code", "deadlock", "Code — lock order", "3 pts additive.", + block=CODE_BLOCK)] + text = _note(tmp_path, a) + assert "| +1 | `A·Q1·r1` | Names deadlock [Outcome] |" in text + assert "| 0 | `A·Q1·r2` | Calls it “starvation” [Outcome] |" in text + assert "| +2 | `A·Q1·r3` | Global lock order [Fix; only one counts] |" in text + assert "| 0 | `A·Q1·r4` | Blank / off-topic [catchall] |" in text + assert "`A·Q1·none`" not in text # the authored catchall replaces it + assert "\\" not in text + + +def test_grading_note_round_trips_through_stats_parser(tmp_path): + from lectern.gradescope_stats import parse_grading_note + a = [OutlineRow(1, 2, "mc", "b", "CIA — availability", "", block=MC_BLOCK), + OutlineRow(2, 3, "code", "deadlock", "Code — lock order", "3 pts.", block=CODE_BLOCK)] + _note(tmp_path, a) + parsed = parse_grading_note(tmp_path / "GRADING_NOTE.md") + assert parsed["A"][1]["pts"] == 2 and parsed["A"][1]["type"] == "MC" + assert [k for _, k, _ in parsed["A"][1]["items"]] == ["A·Q1·a", "A·Q1·b", "A·Q1·c", "A·Q1·none"] + assert len(parsed["A"][2]["items"]) == 4 def test_emit_region_products_copies_and_outlines(tmp_path): @@ -505,3 +572,22 @@ def test_cli_relative_manifest_path(tmp_path, monkeypatch): rc = main(["exam.build.yaml"]) # relative path assert rc == 0 assert (tmp_path / "build" / "register.csv").exists() + + +def test_grading_note_only_cli_writes_note_without_pdfs(tmp_path): + from lectern.exam_build import main as build_main + shutil.copytree(FIX, tmp_path / "fix") + fixd = tmp_path / "fix" + assert build_main([str(fixd / "manifest_ab.yaml"), "--grading-note-only"]) == 0 + text = (fixd / "GRADING_NOTE.md").read_text() + assert "## Form A" in text and "## Form B" in text + assert "| Pts | Key | Rubric item (paste into Gradescope) |" in text + assert not (fixd / "build").exists() + + +def test_grading_note_sanitize_math(): + from lectern.grading_note import sanitize + assert sanitize(r"$2^{n}$") == "2^n" + assert sanitize(r"$2^{2n}$") == "2^(2n)" + assert sanitize(r"$2^{n/2}$") == "2^(n/2)" + assert sanitize(r"\texttt{fork()} returns ``0''") == "fork() returns “0”"