diff --git a/AGENTS.md b/AGENTS.md index 4a20771..6719968 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -19,6 +19,7 @@ Every skill action maps to a `reg-*` CLI command. An agent performing any Lecter | Normalize Canvas grades export | `reg-lms-grades-import` | `lms_grades` | | Normalize CSULB enrollment roster | `reg-lms-roster-import` | `lms_roster` | | Canvas API: export/push grades, roster check, post announcements, discussions, assignments, syllabus | `reg-canvas` | `canvas` (client: `canvas_api`) | +| Canvas gradebook audit; grade discussions by post count | `reg-canvas audit`, `reg-canvas discussions` | `canvas_grading` | | Pre-seed GitHub Classroom roster | `reg-classroom-roster-seed` | `classroom_seed` | | Bind student GitHub IDs to roster entries | `reg-github-bind` | `github_bind` | | Publish ISA grading artifacts to Drive | `reg-isa-publish` | `isa_publish` | @@ -44,7 +45,7 @@ releases. `reg-exam-readinglist` is installed as a standalone `~/bin` wrapper (n - All commands accept `--vault-root ` to locate vault notes. Pass it explicitly; never rely on a hard-coded default. - Prefer `--dry-run` on `reg-term-finalize` before committing; the agent should surface the preview output for review. - `reg-term-archive --check` exits 0 on a clean bundle and nonzero on drift — use the exit code as a quality gate. -- **`reg-canvas` writes are dry runs until `--apply`.** Show the dry run first. An agent never passes `--apply` to a live section (announcements notify students at once; grades are visible once posted) without the instructor's go-ahead for that specific run. Test against the sandbox course with `--course-id`. +- **`reg-canvas` writes are dry runs until `--apply`.** Show the dry run first. An agent never passes `--apply` to a live section (announcements notify students at once; grades are visible once posted) without the instructor's go-ahead for that specific run. Test against the sandbox course with `--course-id`. The same holds for `reg-canvas discussions apply`: show its dry run, and `--post` only with the go-ahead, since posting reveals every hidden grade on the assignment. - **Never read the Canvas token file** (`~/.config/lectern/canvas-token`). The client reads it; nothing else needs to. - All state lives in plain files (Markdown · CSV · YAML · LaTeX) — the agent can read and diff these directly. diff --git a/CHANGELOG.md b/CHANGELOG.md index cc862df..a85e227 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to lectern are documented here. ## [Unreleased] ### Added +- **`reg-canvas audit` and `reg-canvas discussions`: gradebook audit and discussion grading.** The first full read of the Fa26 gradebooks found no forgotten posting, but it did find three problems. Weeks 5 and 6 were ungraded in every section. 326 §03's Exam 1 was filed under Class Participation, so it counted at 10% instead of 60%. And 378's missing-submission policy was off, so non-posters were blank and left out of the current score. `audit` reports all three kinds of problem, plus hidden grades (missing-work zeros counted apart), and exits 1 when it finds something. `discussions review` grades by post count (2 or more = 5, 1 = 3) and writes a vault note listing only the posts that need a human look: one post, a post under 25 words, or 30% phrase overlap with another student. Each of those posts has a deny box. `discussions apply` reads the ticks back and sets changed scores, likes every credited post, and with `--post` posts the grades. It is a dry run until `--apply`. Posts are read to measure them, as an instructor does in SpeedGrader, and the text is reduced to metrics in memory. It is never written, printed or kept, and a test enforces that. The metrics (length, Flesch-Kincaid grade, sentence-length spread, vocabulary ratio, reply structure, names a classmate, links, overlap) are documented as prompts to read, not an AI detector. `--exclude-sis` and `--full-credit-sis` take `SIS@326-03` to scope to one section. Live-checked read-only on the three Fa26 sections, with the same counts as the prototype scripts. New module `canvas_grading`; runbook sections in `docs/canvas-api.md`. - **`reg-lms-grades-import --exclude-sis`: course staff with a student role.** A grad assistant who needs the student view is enrolled as a student in every section's Canvas course, so the export lists them like a student and `reg-gradebook import` stops with "in Canvas but not in roster". Their SIS IDs now go to `grades.filtered.csv` with reason `staff`, alongside the Test Student and ISA filters. `reg-canvas grades-export --import` passes the same flag through. Found on the first live `reg-canvas` export, 2026-10-21. - **`docs/gradescope-workflow.md`: getting Gradescope totals back into lectern.** Gradescope has no instructor API and a Canvas token does not reach it, so the doc now describes the supported route: link the course through Gradescope's Canvas tool (LTI 1.3), post totals to Canvas, and read them with `reg-canvas grades-export`. It warns against pushing the same column from both Gradescope and `reg-canvas grades-push`, and notes that item analysis still needs the per-question export. - **`reg-canvas`: Canvas API support.** CSULB ATS issued a personal Canvas token on 2026-10-21. Until then lectern had no Canvas integration, and every Canvas step was a manual export, upload or paste. The new `canvas_api` module is the only code that touches the token. It reads the token from `~/.config/lectern/canvas-token` and refuses a file that group or other can read. It never takes the token from argv or the environment, sends it only to the configured host, refuses redirects (urllib would forward the `Authorization` header to the redirect's host), and scrubs it from every error. It uses only the standard library, so lectern's runtime dependencies do not change. `reg-canvas` puts nine subcommands on top of it. The read commands are `whoami`, `courses` (`--bind` writes `canvas.course-id` into each class note, using the term name when a class number recurs across years), `grades-export` and `roster-check` (Canvas compared with the registrar roster, for census week). `grades-export` writes the same CSV that Canvas's *Export* button does, so `reg-lms-grades-import` and `reg-gradebook export-canvas --template` take it unchanged; the per-group subtotal columns are the one difference, and nothing reads them. The write commands are `grades-push`, `announce`, `discussion`, `assignment` and `syllabus`, and each is a dry run until `--apply`. `grades-push` applies an overlay CSV, changed cells only. A blank cell never clears a grade, and a file whose assignment IDs belong to another course is refused. `discussion` and `assignment` create items unpublished, `assignment --lab N` takes its name and points from the vault, `syllabus` refuses a file without the class note's serial, and all three content commands skip a title that already exists. Data scope is what was promised to CSULB IT: names, student IDs and grades for the instructor's own sections. Scores come from the submissions endpoint, but only score fields are kept and submission content is dropped on arrival. Exports are written mode 600. Live-checked on 2026-10-21 against the three Fa26 sections (reads) and the sandbox course (an unpublished discussion and assignment, since deleted). Runbook: `docs/canvas-api.md`, which opens with how the pieces fit and ends with troubleshooting. The README (intro, command table, architecture, dependencies, an optional quickstart), `SKILL.md`, `AGENTS.md` and `docs/canvas-grades-workflow.md` all describe the API path, and each repeats that writes are dry runs until `--apply`. diff --git a/README.md b/README.md index 3ffb965..c21613e 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ This is a deliberate design principle, not an accident. Proprietary LMS gradeboo | `reg-exam-build` | `exam_build` | Assemble exam PDFs — single-source `.tex` mode or pack-mode `.yaml` manifest (multi-form A/B/C, per-student individualized, Gradescope products). See below. | | `reg-exam-verify` | `exam_verify` | Verify a student exam serial against the register. Confirms which form and which student a paper belongs to. | | `reg-lms-grades-import` | `lms_grades` | Normalize a Canvas `grades.csv` export to Lectern's canonical format. | -| `reg-canvas` | `canvas` + `canvas_api` | **Canvas API.** Reads: `whoami`, `courses` (`--bind` links each section to its Canvas course in the class note), `grades-export` (the gradebook in Canvas's own export layout, so `reg-lms-grades-import` and `reg-gradebook export-canvas --template` take it unchanged), `roster-check` (Canvas compared with the registrar roster). Writes, each a **dry run until `--apply`**: `grades-push` (an overlay CSV, changed cells only; a blank never clears a grade), `announce`, `discussion` and `assignment` (both unpublished by default), and `syllabus` (refuses a file without its serial). The token lives in one mode-600 file and is sent to one host. See [docs/canvas-api.md](docs/canvas-api.md). | +| `reg-canvas` | `canvas` + `canvas_api` | **Canvas API.** Reads: `whoami`, `courses` (`--bind` links each section to its Canvas course in the class note), `grades-export` (the gradebook in Canvas's own export layout, so `reg-lms-grades-import` and `reg-gradebook export-canvas --template` take it unchanged), `roster-check` (Canvas compared with the registrar roster), `audit` (ungraded or unposted work, empty weighted groups, a missing-submission policy that is off). Writes, each a **dry run until `--apply`**: `grades-push` (an overlay CSV, changed cells only; a blank never clears a grade), `announce`, `discussion` and `assignment` (both unpublished by default), `syllabus` (refuses a file without its serial), and `discussions` (grades discussion assignments by post count: `review` writes the short list to judge as a vault note with a deny box per post, `apply` sets scores and likes). The token lives in one mode-600 file and is sent to one host. See [docs/canvas-api.md](docs/canvas-api.md). | | `reg-lms-roster-import` | `lms_roster` | Normalize a faculty-center enrollment roster (`.xls`/`.xlsx`) to Lectern's canonical format. | | `reg-classroom-roster-seed` | `classroom_seed` | Pre-seed a GitHub Classroom roster from a normalized roster CSV, using the 9-digit student ID as the identifier. | | `reg-github-bind` | `github_bind` | Bind student GitHub usernames to roster entries — from a Google Form CSV, a GitHub Classroom roster CSV, or org-scrape mode. | @@ -142,6 +142,7 @@ lectern/ lms_roster.py enrollment roster normalization (.xls → .csv) canvas_api.py Canvas REST client: the only module that reads the token canvas.py reg-canvas: gradebook export/push, roster check, content posting + canvas_grading.py reg-canvas audit + discussions: gradebook audit, discussion grading classroom_seed.py GitHub Classroom roster pre-seeding github_bind.py student-id → GitHub username binding isa_publish.py Drive publishing (rclone/service-account backend) diff --git a/SKILL.md b/SKILL.md index 5843caf..a134cbf 100644 --- a/SKILL.md +++ b/SKILL.md @@ -26,7 +26,7 @@ records of running courses. All tools are vault-aware via an explicit | `reg-lms-roster-import` | lms_roster | Normalize a CSULB faculty-center roster export | | `reg-c50` | c50 | **Classroom 50** — the GitHub Classroom successor (legacy sunset 2026-08-28). `classroom-add` creates one classroom per section from the term-spec · `codes` mints the per-section self-enrollment codes · `roster-import` turns collected GitHub usernames into a roster + org invitations · `post` registers a lab as an assignment in every section that teaches it, binds it into the class notes, and writes the Canvas announcement · `status` reads back what is actually registered. Resolves org, classroom, slug, template, points and due date from the vault rather than the command line | | `reg-guardcheck` | guardcheck | **In-CI course-file notification.** `stamp` records the expected digests of a template's guard files; `check` runs inside the lab's own autograde workflow and tells the *student* when one has changed. ==Notifies, never grades==: no points, no pass/fail, always exits 0 (`--strict` opts out). Stdlib-only so a template can vendor the single file. The authoritative check is instructor-side `reg-triage`, which reads git history from outside the student's control | -| `reg-canvas` | canvas | **Canvas API.** Reads: `whoami`, `courses` (`--bind` records each section's `canvas.course-id` in its class note), `grades-export` (the gradebook as the same CSV Canvas's *Export* writes, into `archives/-/canvas/`, `--import` chains `reg-lms-grades-import`), `roster-check` (Canvas vs registrar roster). Writes, ==dry run unless `--apply`==: `grades-push` (a Canvas-format import CSV, changed cells only), `announce`, `discussion` (unpublished by default), `assignment` (`--lab N` fills name + points from the vault), `syllabus` (refuses a file without the class note's serial). Token: `~/.config/lectern/canvas-token`, mode 600, never in argv, logs or the vault. Runbook: `docs/canvas-api.md` | +| `reg-canvas` | canvas | **Canvas API.** Reads: `whoami`, `courses` (`--bind` records each section's `canvas.course-id` in its class note), `grades-export` (the gradebook as the same CSV Canvas's *Export* writes, into `archives/-/canvas/`, `--import` chains `reg-lms-grades-import`), `roster-check` (Canvas vs registrar roster), `audit` (ungraded/unposted work, empty weighted groups, missing policy off). Writes, ==dry run unless `--apply`==: `grades-push` (a Canvas-format import CSV, changed cells only), `announce`, `discussion` (unpublished by default), `assignment` (`--lab N` fills name + points from the vault), `syllabus` (refuses a file without the class note's serial), `discussions review|apply` (grade discussions by post count: 2+ = 5, 1 = 3; a vault note lists only the posts to judge, each with a deny box; likes, no comments; `--post` reveals hidden grades). Token: `~/.config/lectern/canvas-token`, mode 600, never in argv, logs or the vault. Runbook: `docs/canvas-api.md` | | `reg-classroom-roster-seed` | classroom_seed | ==**RETIRED** — legacy GitHub Classroom, and it never worked live== (it POSTed to a read-only endpoint). Kept only so old runbooks resolve. Use `reg-c50 roster-import` | | `reg-github-bind` | github_bind | Bind student GitHub IDs to roster entries | | `reg-isa-publish` | isa_publish | Publish ISA grading artifacts to Drive (rclone/gdrive backend) | @@ -280,6 +280,11 @@ reg-canvas grades-push --term fa26 --vault-root --course "CECS 326" --sectio --file canvas-lab2-import.csv --only "Lab 2 - …" # dry run; add --apply reg-canvas announce --term fa26 --vault-root --course "CECS 326" \ --file '/posted/fa26-{section}-ANNOUNCE.md' # dry run; add --apply +reg-canvas audit --term fa26 --vault-root # what was never graded or posted +reg-canvas discussions review --term fa26 --vault-root --week "Week 7" \ + --workdir ~/tmp/canvas-discussions/fa26-w7 # writes the vault note to judge +reg-canvas discussions apply --workdir ~/tmp/canvas-discussions/fa26-w7 \ + --note /classes/semesters/fa26-discussions-w7-grading.md --post # dry run; add --apply ``` ==Every write is a dry run until `--apply`.== An agent shows the dry run and @@ -289,6 +294,11 @@ sandbox) bypasses the vault for testing. ==Never read the token file.== **Data scope** matches what was promised to CSULB IT on 2026-10-16: course content, plus names, student IDs and grades for the instructor's own sections. +`discussions review` also reads discussion posts, the same reading done by +hand in SpeedGrader: the text is reduced to counts and writing metrics in +memory and never written. The metrics are prompts to read a post, ==never an +AI-detection verdict==; the course discussion rules promise "no checker, no +accusations". `grades-export` reads scores from the submissions endpoint but keeps only score fields, dropping submission content on arrival. Exports are written mode 600. diff --git a/docs/README.md b/docs/README.md index bc56dac..43e6891 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,7 +15,7 @@ | Document | Description | |---|---| | [gradescope-workflow.md](gradescope-workflow.md) | Step-by-step for taking a lectern-built exam into Gradescope: region/bubble setup, A/B Version Sets, roster import, per-student serial identity verification | -| [canvas-api.md](canvas-api.md) | *About 15 min to set up.* `reg-canvas`: Canvas token setup, linking sections to courses, gradebook export, roster check, and the dry-run-first write commands (grades, announcements, discussions, assignments, syllabus) | +| [canvas-api.md](canvas-api.md) | *About 15 min to set up.* `reg-canvas`: Canvas token setup, linking sections to courses, gradebook export, roster check, and the dry-run-first write commands (grades, announcements, discussions, assignments, syllabus), the gradebook audit, and discussion grading | | [canvas-grades-workflow.md](canvas-grades-workflow.md) | Pushing vault grades to Canvas for one assignment via a Canvas-export **template overlay**: id-suffixed assignment match, `--only` targeting, minimal diff, extra-credit handling | | [admin-forms.md](admin-forms.md) | Filling a campus administrative form (Notice of Absence and friends) from the vault's own records: identity setup, campus closures in the term-spec, the three rendered products, and how to add a new form as a profile | diff --git a/docs/canvas-api.md b/docs/canvas-api.md index c3712d3..f7e4b57 100644 --- a/docs/canvas-api.md +++ b/docs/canvas-api.md @@ -4,7 +4,8 @@ `reg-canvas` replaces the copy-and-paste steps between your course records and Canvas. It exports the gradebook, pushes grades back, checks the roster, and -posts announcements, discussions, assignments and the syllabus. +posts announcements, discussions, assignments and the syllabus. It also audits +the gradebook and grades discussion assignments. > [!CAUTION] > **Every write is a dry run until you add `--apply`.** A dry run shows exactly @@ -116,6 +117,7 @@ in place of `--term`. | `courses` | Lists your courses. `--bind` links them to class notes. | | `grades-export` | Writes the gradebook as the CSV Canvas's *Export* button produces. | | `roster-check` | Compares Canvas enrolments with the registrar roster. | +| `audit` | Finds work that was never graded or never posted, and settings that skew the weighted score. | ### Export the gradebook @@ -161,6 +163,7 @@ All of these are dry runs until you add `--apply`. | `discussion` | A discussion topic | Unpublished | | `assignment` | An assignment | Unpublished, submission type `none` | | `syllabus` | The course syllabus page | Refuses a file without its serial | +| `discussions apply` | Discussion scores and likes | Dry run; `--post` also posts the grades | `announce`, `discussion` and `assignment` skip a section that already has an item with the same title. `--force` overrides that check. @@ -229,10 +232,106 @@ The command refuses a file that does not contain the class note's serial. If the syllabus was already distributed, a changed version needs a `revision-of` row in the register. +### Audit the gradebook + +```sh +reg-canvas audit --term fa26 --vault-root --exclude-sis @326-03 +``` + +For each section, the audit lists: + +- **Group weights**, and how many assignments each group holds. A weighted + group with no assignments usually means an exam was filed in the wrong + group, so it counts at the wrong weight. +- **The missing-submission policy.** When it is off, a student who posts + nothing gets a blank, not a 0, and Canvas leaves blanks out of the current + score. +- **Each assignment:** past due with students ungraded, submitted but not + graded, and graded but hidden. +- **How many students see a score** that differs from their score with hidden + grades included. + +It exits with status 1 when it finds something. + +> [!TIP] +> **A hidden 0 is usually not a forgotten grade.** With the missing policy on, +> Canvas gives a 0 to every student who did not submit by the due date. On an +> assignment that posts manually, that 0 stays hidden until you post. The +> audit counts these separately as "missing-work zeros". + +### Grade the discussions + +Discussions are graded by post count, with a short list for you to judge: + +| Credited posts (top-level or replies) | Score | +|---|---| +| 2 or more | 5 | +| 1 | 3 | +| 0 | 0, from the missing policy | + +Every credited post gets a like. No comments are written. + +```mermaid +flowchart LR + R["discussions review
reads only"] --> N["Vault note
only the posts to judge"] + N -->|"tick deny"| A["discussions apply
dry run"] + A -->|"--apply --post"| K[("Canvas")] +``` + +```sh +W=~/tmp/canvas-discussions/fa26-w7 +reg-canvas discussions review --term fa26 --vault-root --week "Week 7" --workdir $W \ + --exclude-sis @326-03 --full-credit-sis @326-01 +``` + +`review` writes the vault note +`classes/semesters/-discussions--grading.md`. The note lists only +these students, each with a SpeedGrader link: + +- students who made one post +- students with a post under 25 words +- students with a post that shares 30% or more of its five-word phrases with + another student's post + +Everyone else has 2 or more posts of normal length and gets 5 without review. +Each listed post has a **deny** box. Tick it when the post does not earn +credit, and that student drops one tier. + +```sh +reg-canvas discussions apply --workdir $W --note --post # dry run +reg-canvas discussions apply --workdir $W --note --post --apply # send +rm -rf $W +``` + +`--exclude-sis` leaves course staff who hold a student enrolment out of +grading. `--full-credit-sis` gives a student full credit whatever the count, +for an agreed arrangement. Both take `SIS` for every section or `SIS@326-03` +for one. + +> [!CAUTION] +> **`--post` makes every grade on the assignment visible**, including the +> missing-work zeros. Read the dry run first. + +Each listed post shows facts about its writing: length, Flesch-Kincaid grade +level (the years of schooling the prose reads at), how much its sentence +lengths vary, whether it is a reply and how many replies it drew, whether it +names a classmate, links or code, and its phrase overlap with other students. +The workdir's `METRICS.csv` has the same columns for every post. + +> [!IMPORTANT] +> **A common misconception is that these metrics detect AI writing.** They do +> not, and no tool does so reliably: detectors have high false-positive rates, +> above all for students writing in a second language. The metrics tell you +> which posts to read. A post that names no one, cites nothing and keeps one +> rhythm is a reason to open it, not a verdict. + ## 7. What lectern reads, and what it never keeps - **Read:** course structure (assignments, groups, sections), plus names, - student IDs and grades for your own sections. + student IDs and grades for your own sections. `discussions review` also + reads discussion posts, as you would in SpeedGrader, and reduces each to + counts and writing metrics in memory. The post text is never written, + printed or kept. - **Written:** grades, announcements, discussions, assignments and the syllabus, for your own courses, and only with `--apply`. - **Never kept:** submission content. Scores come from the submissions @@ -259,4 +358,7 @@ and tell your Canvas administrators the same day. | `no canvas.course-id in ` | The class note has no `canvas:` block. | `reg-canvas courses --bind --term --vault-root ` | | `expected one Canvas course, found …` | `reg-canvas courses` lists two courses with the same class number, or none. | Write the `canvas:` block into the class note by hand. | | `names assignments this course does not have` | The import file's `(id)` columns come from another section's export. | Export that section again, rebuild the overlay, and push it. | +| `discussions apply` says "no plan in …" | `ls ` shows no `plan.json`. | Run `discussions review` with the same `--workdir` first. | +| `review` refuses to overwrite the note | The note already exists and may hold your ticks. | Finish that round, or pass `--force` to start again. | +| A like fails with `HTTP 403` | The topic does not allow liking. | Turn on **Allow liking** in the discussion's settings. | | An export has fewer columns than Canvas's own | `reg-canvas grades-export --stdout --course-id \| head -1` lists the assignment columns. Unpublished and hidden assignments are left out. | Publish the assignment, or ignore the column if it is not graded yet. | diff --git a/lectern/canvas.py b/lectern/canvas.py index 6624c3c..393eb21 100644 --- a/lectern/canvas.py +++ b/lectern/canvas.py @@ -13,6 +13,9 @@ writes, so ``reg-lms-grades-import`` and ``reg-gradebook export-canvas --template`` take it unchanged - ``roster-check`` diff Canvas enrolments against the registrar roster +- ``audit`` find ungraded or unposted work and gradebook settings + that skew the weighted score + (:mod:`lectern.canvas_grading`) Writes (**dry run unless ``--apply``**): @@ -21,9 +24,12 @@ - ``discussion`` create a discussion topic, unpublished by default - ``assignment`` create an assignment (``--lab N`` fills it from the vault) - ``syllabus`` set the syllabus page, refusing a file without its serial +- ``discussions`` grade discussion assignments by post count: ``review`` + writes the short list to judge, ``apply`` sets scores + and likes (:mod:`lectern.canvas_grading`) -Data scope is what the instructor already exports by hand: roster and grades -for their own sections. ``grades-export`` reads scores through the +Data scope is what the instructor already does by hand: roster and grades +for their own sections, and reading discussion posts to grade them. ``grades-export`` reads scores through the submissions endpoint but keeps only score fields (:data:`SCORE_FIELDS`); submission content is dropped as each page arrives and never written. @@ -42,6 +48,7 @@ from datetime import datetime from pathlib import Path +from lectern import canvas_grading from lectern.canvas_api import CanvasClient, CanvasError from lectern.c50 import C50Error, class_note_path, sections_for, spec_path from lectern.student_id import pad_student_id @@ -660,6 +667,15 @@ def cmd_syllabus(client: CanvasClient, args) -> int: # ── CLI ────────────────────────────────────────────────────────────────────── +def cmd_audit(client: CanvasClient, args) -> int: + return canvas_grading.cmd_audit(client, args, resolve_targets(args)) + + +def cmd_discussions(client: CanvasClient, args) -> int: + targets = resolve_targets(args) if args.action == "review" else [] + return canvas_grading.cmd_discussions(client, args, targets) + + def build_parser() -> argparse.ArgumentParser: p = argparse.ArgumentParser( prog="reg-canvas", @@ -706,6 +722,12 @@ def writes(sp): help="reg-lms-roster-import CSV ({section}/{term}/{course} expand)") sp.set_defaults(func=cmd_roster_check) + sp = sub.add_parser("audit", help="find ungraded/unposted work and skewed settings") + target(sp) + sp.add_argument("--exclude-sis", nargs="+", default=[], metavar="SIS[@SEC]", + help="course staff enrolled as students; @326-03 limits to one section") + sp.set_defaults(func=cmd_audit) + sp = sub.add_parser("grades-push", help="apply a Canvas-format import CSV (changed cells)") target(sp, need_section=True) sp.add_argument("--file", required=True, @@ -743,6 +765,31 @@ def writes(sp): writes(sp) sp.set_defaults(func=cmd_assignment) + sp = sub.add_parser("discussions", help="grade discussion assignments by post count") + act = sp.add_subparsers(dest="action", required=True) + r = act.add_parser("review", help="write the short list to judge (reads only)") + target(r) + r.add_argument("--week", action="append", required=True, + help='assignment name prefix, e.g. "Week 5" (repeatable)') + r.add_argument("--workdir", required=True, help="private working dir (mode 700); " + "holds student records, delete after apply") + r.add_argument("--exclude-sis", nargs="+", default=[], metavar="SIS[@SEC]", + help="staff enrolled as students; not graded") + r.add_argument("--full-credit-sis", nargs="+", default=[], metavar="SIS[@SEC]", + help="full credit whatever the count (an agreed arrangement)") + r.add_argument("--note", help="vault note to write (default with --term/--vault-root: " + "classes/semesters/-discussions--grading.md)") + r.add_argument("--no-note", action="store_true", help="write no vault note") + r.add_argument("--force", action="store_true", help="overwrite an existing note") + r.set_defaults(func=cmd_discussions) + ap_ = act.add_parser("apply", help="set scores and likes from the review") + ap_.add_argument("--workdir", required=True) + ap_.add_argument("--note", help="read the ticked deny boxes from this note") + ap_.add_argument("--post", action="store_true", + help="also post the grades (shows students every hidden grade)") + writes(ap_) + ap_.set_defaults(func=cmd_discussions) + sp = sub.add_parser("syllabus", help="set the course syllabus page") target(sp) sp.add_argument("--file", required=True, @@ -758,7 +805,8 @@ def main(argv=None, client: CanvasClient | None = None) -> int: try: client = client or CanvasClient.from_config() return args.func(client, args) - except (CanvasError, CanvasCmdError, C50Error, TermSpecError) as e: + except (CanvasError, CanvasCmdError, C50Error, TermSpecError, + canvas_grading.GradingError) as e: print(f"reg-canvas: {e}", file=sys.stderr) return 2 diff --git a/lectern/canvas_grading.py b/lectern/canvas_grading.py new file mode 100644 index 0000000..c268f55 --- /dev/null +++ b/lectern/canvas_grading.py @@ -0,0 +1,479 @@ +"""Gradebook audit and discussion grading for ``reg-canvas``. + +Two jobs that read a course's gradebook as a whole, kept apart from +:mod:`lectern.canvas` so that module stays a thin set of export/push verbs: + +- :func:`cmd_audit` finds work that was never graded or never posted, plus + settings that skew the weighted score: an empty weighted group (the sign an + exam was filed in the wrong one), and a missing-submission policy that is + off, which leaves non-posters blank where Canvas's current score skips them. +- :func:`cmd_discussions` grades the weekly discussion assignments by post + count. ``review`` builds the short list a human has to look at; ``apply`` + writes scores and likes, a dry run until ``--apply``. + +Discussion posts are read to *measure* them, the same reading an instructor +does in SpeedGrader. The text is reduced to the numbers in :func:`metrics` +as each topic arrives and is never written, printed or kept. What reaches +disk is names, Canvas ids, entry ids and those numbers, in a mode-700 workdir +(and, with ``--note``, a vault note) that the instructor deletes after use. + +The metrics are prompts to read a post, not a verdict. In particular they +are **not** an AI detector: detectors have high false-positive rates, above +all for students writing in a second language. ``max_overlap`` is a fact +(shared five-word phrases with another student's post), not a judgement. +""" +from __future__ import annotations + +import csv +import html +import io +import json +import os +import re +from collections import Counter, defaultdict +from datetime import datetime, timezone +from pathlib import Path + +from lectern.canvas_api import CanvasClient + +# Points for 2+, 1 and 0 credited posts. Missing work is already 0 through +# the course's missing-submission policy, so 0 is only ever a denial. +FULL, PARTIAL = 5, 3 +SHORT_WORDS = 25 # a post under this goes on the review list +OVERLAP = 0.30 # max_overlap at or above this goes on the review list +SHINGLE = 5 # words per phrase for max_overlap + + +class GradingError(Exception): + """A user-facing failure of ``audit`` or ``discussions``.""" + + +# ── who counts ─────────────────────────────────────────────────────────────── + + +def section_key(target) -> str: + """``326-01`` for a vault target; the Canvas course id otherwise.""" + sec = target.section or {} + if sec.get("course") and sec.get("section"): + return f"{str(sec['course']).split()[-1]}-{sec['section']}" + return str(target.course_id) + + +def scoped(values: list[str] | None, target) -> set[str]: + """SIS ids from ``SIS`` (every section) or ``SIS@KEY`` (one section) arguments. + + ``KEY`` is :func:`section_key` (``326-03``) or a Canvas course id. + """ + keys = {section_key(target), str(target.course_id)} + out = set() + for v in values or []: + sis, _, where = v.partition("@") + if not where or where in keys: + out.add(sis) + return out + + +def students(client: CanvasClient, course_id: int, exclude: set[str]) -> dict[int, dict]: + """Active student enrolments, keyed by Canvas user id, minus ``exclude`` SIS ids.""" + out = {} + for e in client.get_all(f"courses/{course_id}/enrollments", + [("type[]", "StudentEnrollment"), ("state[]", "active")]): + u = e.get("user") or {} + if u.get("sis_user_id") in exclude: + continue + out[e["user_id"]] = {"name": u.get("sortable_name") or "?", + "sis": u.get("sis_user_id") or "", + "grades": e.get("grades") or {}} + return out + + +# Score fields only, as in canvas.SCORE_FIELDS, plus the posting and timing +# fields the audit needs. Submission content is never kept. +AUDIT_FIELDS = ("user_id", "assignment_id", "score", "excused", "missing", + "workflow_state", "posted_at", "submitted_at") + + +def _ts(v): + return datetime.fromisoformat(v.replace("Z", "+00:00")) if v else None + + +# ── audit ──────────────────────────────────────────────────────────────────── + + +def audit_course(client: CanvasClient, course_id: int, exclude: set[str], + now: datetime | None = None) -> tuple[list[str], int]: + """The report lines for one course, and how many problems it found.""" + now = now or datetime.now(timezone.utc) + lines, problems = [], 0 + course = client.get(f"courses/{course_id}") + weighted = bool(course.get("apply_assignment_group_weights")) + groups = list(client.get_all(f"courses/{course_id}/assignment_groups")) + assigns = list(client.get_all(f"courses/{course_id}/assignments")) + per_group = Counter(a.get("assignment_group_id") for a in assigns) + gname = {g["id"]: g["name"] for g in groups} + + lines.append(f"Groups ({'weighted' if weighted else 'not weighted'}):") + total = 0.0 + for g in groups: + w = g.get("group_weight") or 0 + total += w + n = per_group.get(g["id"], 0) + flag = "" + if weighted and w and not n: + flag = " <- weighted but empty: is an assignment in the wrong group?" + problems += 1 + lines.append(f" {g['name']:<30} {w:>5g}% {n} assignment(s){flag}") + if weighted and abs(total - 100) > 0.01: + lines.append(f" weights sum to {total:g}, not 100") + problems += 1 + + policy = (client.get(f"courses/{course_id}/late_policy") or {}).get("late_policy") or {} + if not policy.get("missing_submission_deduction_enabled"): + lines.append("Missing-submission policy is OFF: non-posters stay blank, and the " + "current score skips blanks.") + problems += 1 + + studs = students(client, course_id, exclude) + subs: dict[int, dict[int, dict]] = defaultdict(dict) + for s in client.get_all(f"courses/{course_id}/students/submissions", + [("student_ids[]", "all")]): + k = {f: s.get(f) for f in AUDIT_FIELDS} + if k["user_id"] in studs: + subs[k["assignment_id"]][k["user_id"]] = k + + for t, n in Counter(a["name"] for a in assigns).items(): + if n > 1: + lines.append(f"Duplicate assignment name: {t!r} x{n}") + problems += 1 + + lines.append(f"Assignments ({len(studs)} active students):") + order = sorted(assigns, key=lambda a: (gname.get(a.get("assignment_group_id"), ""), + a.get("position") or 0)) + for a in order: + rows = subs.get(a["id"], {}) + graded = [r for r in rows.values() if r["score"] is not None or r["excused"]] + hidden = [r for r in graded if not r["posted_at"]] + waiting = [r for r in rows.values() + if r["workflow_state"] in ("submitted", "pending_review") and r["score"] is None] + due = _ts(a.get("due_at")) + flags = [] + if not a.get("published"): + flags.append("unpublished") + if due and due < now and a.get("published") and len(graded) < len(studs): + flags.append(f"past due, {len(studs) - len(graded)} ungraded") + if waiting: + flags.append(f"{len(waiting)} submitted, not graded") + if hidden: + zeros = sum(1 for r in hidden if r["score"] == 0 and r["missing"]) + flags.append(f"{len(hidden)} graded but hidden" + + (f" ({zeros} are missing-work zeros)" if zeros else "")) + problems += bool(flags) + lines.append(f" [{gname.get(a.get('assignment_group_id'), '?')[:18]:<18}] " + f"{a['name'][:40]:<40} graded {len(graded):>3}/{len(studs)}" + + (f" <- {'; '.join(flags)}" if flags else "")) + + drift = [s["name"] for s in studs.values() + if s["grades"].get("current_score") != s["grades"].get("unposted_current_score")] + if drift: + lines.append(f"{len(drift)} student(s) see a score that differs from their score " + "with hidden grades included. Posting will change it.") + return lines, problems + + +def cmd_audit(client: CanvasClient, args, targets) -> int: + found = 0 + for t in targets: + lines, n = audit_course(client, t.course_id, scoped(args.exclude_sis, t)) + print(f"== {t.label} (course {t.course_id})") + print("\n".join(lines)) + print() + found += n + return 1 if found else 0 + + +# ── discussion metrics ─────────────────────────────────────────────────────── + + +def plain(message: str | None) -> str: + return html.unescape(re.sub(r"<[^>]+>", " ", message or "")) + + +def _syllables(word: str) -> int: + w = word.lower() + groups = re.findall(r"[aeiouy]+", w) + n = len(groups) - (1 if w.endswith("e") and len(groups) > 1 else 0) + return max(n, 1) + + +def metrics(message: str | None, classmates: set[str]) -> dict: + """Facts about one post's writing. The text itself is not returned. + + ``fk_grade`` is the Flesch-Kincaid grade level. ``sent_len_sd`` is the + spread of sentence lengths (low means a uniform rhythm). ``vocab_ratio`` + is distinct words over total words. ``_shingles`` is consumed by + :func:`add_overlap` and removed before anything is written. + """ + text = plain(message) + toks = re.findall(r"[A-Za-z']+", text) + sents = [s for s in re.split(r"[.!?]+\s", text) if s.strip()] or [text] + lens = [len(s.split()) for s in sents] + n = len(toks) or 1 + mean = sum(lens) / len(lens) + lower = [t.lower() for t in toks] + return { + "words": len(toks), + "fk_grade": round(0.39 * n / len(sents) + 11.8 * sum(map(_syllables, toks)) / n - 15.59, 1), + "sent_len_sd": round((sum((x - mean) ** 2 for x in lens) / len(lens)) ** 0.5, 1), + "vocab_ratio": round(len(set(lower)) / n, 2), + "links": len(re.findall(r"https?://", message or "")), + "code": bool(re.search(r"<(pre|code)\b", message or "")), + "names_classmate": any(re.search(rf"\b{re.escape(f)}\b", text) for f in classmates), + "_shingles": {tuple(lower[i:i + SHINGLE]) for i in range(len(lower) - SHINGLE + 1)}, + } + + +def first_name(sortable: str) -> str | None: + if ", " not in sortable: + return None + rest = sortable.split(", ", 1)[1].split() + return rest[0] if rest else None + + +def topic_posts(view: dict, first_names: dict[int, str]) -> list[tuple[int, int, dict]]: + """``(user_id, entry_id, metrics)`` for every live entry in a topic view.""" + names = set(first_names.values()) + out: list[tuple[int, int, dict]] = [] + + def walk(entries, parent): + for e in entries or []: + if not e.get("deleted"): + m = metrics(e.get("message"), names - {first_names.get(e["user_id"])}) + m["reply"] = parent is not None + m["got_replies"] = sum(1 for r in e.get("replies") or [] if not r.get("deleted")) + out.append((e["user_id"], e["id"], m)) + walk(e.get("replies"), e["id"]) + + walk((view or {}).get("view"), None) + add_overlap(out) + return out + + +def add_overlap(posts: list[tuple[int, int, dict]]) -> None: + """Set ``max_overlap``: the largest share of a post's phrases in another student's post.""" + for uid, _, m in posts: + best = 0.0 + for uid2, _, m2 in posts: + if uid2 != uid and m["_shingles"] and m2["_shingles"]: + best = max(best, len(m["_shingles"] & m2["_shingles"]) / len(m["_shingles"])) + m["max_overlap"] = round(best, 2) + for _, _, m in posts: + del m["_shingles"] + + +def describe(m: dict) -> str: + bits = [f"{m['words']} words", f"grade {m['fk_grade']}", f"rhythm sd {m['sent_len_sd']}", + "reply" if m["reply"] else "top-level"] + if m["got_replies"]: + bits.append(f"{m['got_replies']} replies") + if m["names_classmate"]: + bits.append("names a classmate") + if m["links"]: + bits.append(f"{m['links']} links") + if m["code"]: + bits.append("code") + if m["max_overlap"] >= OVERLAP: + bits.append(f"OVERLAP {m['max_overlap']:.0%}") + return ", ".join(bits) + + +def score_for(credited: int, full_credit: bool) -> int: + return FULL if full_credit or credited >= 2 else PARTIAL if credited else 0 + + +# ── discussions review / apply ─────────────────────────────────────────────── + + +def _private_dir(path: Path) -> Path: + path.mkdir(parents=True, exist_ok=True) + os.chmod(path, 0o700) + return path + + +def _private_write(path: Path, text: str) -> None: + path.write_text(text, encoding="utf-8") + os.chmod(path, 0o600) + + +def default_note(vault: Path, term: str, weeks: list[str]) -> Path: + slug = "-".join(re.sub(r"[^a-z0-9]+", "", w.lower()).replace("week", "w") for w in weeks) + return vault / "classes" / "semesters" / f"{term}-discussions-{slug}-grading.md" + + +def review(client: CanvasClient, args, targets) -> int: + wd = _private_dir(Path(args.workdir).expanduser()) + plan, flagged, rows = [], [], [] + for t in targets: + studs = students(client, t.course_id, scoped(args.exclude_sis, t)) + full = scoped(args.full_credit_sis, t) + firsts = {uid: first_name(s["name"]) for uid, s in studs.items()} + firsts = {k: v for k, v in firsts.items() if v} + key = section_key(t) + for a in client.get_all(f"courses/{t.course_id}/assignments"): + week = next((w for w in args.week if a["name"].startswith(w)), None) + topic = a.get("discussion_topic") + if not week or not topic: + continue + posts = topic_posts(client.get( + f"courses/{t.course_id}/discussion_topics/{topic['id']}/view"), firsts) + per: dict[int, list[tuple[int, dict]]] = defaultdict(list) + for uid, eid, m in posts: + if uid in studs: + per[uid].append((eid, m)) + rows.append({"section": key, "week": week, "student": studs[uid]["name"], + "entry": eid, **m}) + tally = Counter() + for uid, s in studs.items(): + ents = per.get(uid, []) + if not ents: + continue + forced = s["sis"] in full + plan.append({"course": t.course_id, "label": key, "assignment": a["id"], + "topic": topic["id"], "week": week, "user": uid, + "name": s["name"], "full_credit": forced, + "entries": [e for e, _ in ents]}) + tally[score_for(len(ents), forced)] += 1 + short = sum(1 for _, m in ents if m["words"] < SHORT_WORDS) + copied = sum(1 for _, m in ents if m["max_overlap"] >= OVERLAP) + if forced or (len(ents) >= 2 and not short and not copied): + continue + why = [f"one post only ({PARTIAL} pt)" if len(ents) == 1 else "", + f"{short} post(s) under {SHORT_WORDS} words" if short else "", + f"{copied} post(s) sharing {OVERLAP:.0%}+ phrasing with another student" + if copied else ""] + sg = (f"{client.base}/courses/{t.course_id}/gradebook/speed_grader" + f"?assignment_id={a['id']}&student_id={uid}") + flagged.append(f"- **{key} {week}**, {s['name']}: " + f"{'; '.join(x for x in why if x)}. [SpeedGrader]({sg})") + for eid, m in ents: + flagged.append(f" - [ ] deny entry `{eid}` ({describe(m)}): {client.base}" + f"/courses/{t.course_id}/discussion_topics/{topic['id']}" + f"?entry_id={eid}") + print(f"{t.label} {week}: {len(per)} of {len(studs)} posted; " + f"{tally[FULL]} at {FULL}, {tally[PARTIAL]} at {PARTIAL}") + + body = [f"# Discussion grading: {', '.join(args.week)}", "", + f"Rule: 2+ credited posts = {FULL}, 1 = {PARTIAL}, 0 = 0. Every credited post " + "gets a like; no comments are written.", + "Everyone not listed has 2+ posts of normal length.", "", + "Tick **deny** on any post that does not earn credit.", ""] + body += flagged or ["Nobody needs review."] + text = "\n".join(body) + "\n" + _private_write(wd / "plan.json", json.dumps(plan)) + _private_write(wd / "REVIEW.md", text) + if rows: + buf = io.StringIO() + w = csv.DictWriter(buf, fieldnames=list(rows[0])) + w.writeheader() + w.writerows(rows) + _private_write(wd / "METRICS.csv", buf.getvalue()) + n = sum(1 for line in flagged if line.startswith("- ")) + print(f"\n{n} to review: {wd / 'REVIEW.md'}") + + note = note_path(args) + if note: + if note.exists() and not args.force: + raise GradingError(f"{note} exists and may hold your ticks; pass --force to overwrite") + stamp = datetime.now().astimezone().isoformat(timespec="seconds") + fm = ("---\n" + f"title: \"Discussion grading: {', '.join(args.week)}\"\n" + "type: report\n" + f"term: {args.term or ''}\n" + "tags: [teaching, discussion, grading, internal]\n" + "visibility: private\nicon: LiClipboardCheck\niconColor: var(--text-normal)\n" + f"created: {stamp}\n---\n") + how = ("> [!info] How to use this\n" + "> Tick **deny** on a post that does not earn credit, then run " + f"`reg-canvas discussions apply --workdir {args.workdir} --note '{note}'` " + "for the dry run.\n") + head, rest = text.split("\n", 1) + _private_write(note, fm + head + "\n\n" + how + rest) + print(f"Vault note: {note}") + return 0 + + +def note_path(args) -> Path | None: + if getattr(args, "note", None): + return Path(args.note).expanduser() + if getattr(args, "no_note", False) or not (args.vault_root and args.term + and getattr(args, "week", None)): + return None + return default_note(Path(args.vault_root), args.term, args.week) + + +_TICK = re.compile(r"^\s*- \[[xX]\] deny entry `(\d+)`", re.M) + + +def denials(wd: Path, note: Path | None) -> set[int]: + deny = set() + if (wd / "deny.txt").exists(): + deny |= {int(t) for t in (wd / "deny.txt").read_text().split()} + if note and note.exists(): + deny |= {int(x) for x in _TICK.findall(note.read_text(encoding="utf-8"))} + return deny + + +POST_GRADES = ("mutation($id: ID!){postAssignmentGrades(input:{assignmentId:$id})" + "{progress{id} errors{message}}}") + + +def apply(client: CanvasClient, args) -> int: + wd = Path(args.workdir).expanduser() + try: + plan = json.loads((wd / "plan.json").read_text()) + except FileNotFoundError: + raise GradingError(f"no plan in {wd}; run reg-canvas discussions review first") from None + note = Path(args.note).expanduser() if args.note else None + deny = denials(wd, note) + if deny: + print(f"denying {len(deny)} post(s): {sorted(deny)}") + + groups: dict[tuple, list] = defaultdict(list) + for p in plan: + credited = [e for e in p["entries"] if e not in deny] + groups[(p["course"], p["label"], p["assignment"], p["topic"], p["week"])].append( + (p, credited, score_for(len(credited), p["full_credit"]))) + + for (cid, label, aid, tid, week), rows in sorted(groups.items()): + current = {s["user_id"]: s.get("score") + for s in client.get_all(f"courses/{cid}/assignments/{aid}/submissions")} + grades = {str(p["user"]): {"posted_grade": str(s)} + for p, _, s in rows if current.get(p["user"]) != s} + likes = [e for _, cr, _ in rows for e in cr] + tally = Counter(s for _, _, s in rows) + denied = [p["name"] for p, cr, _ in rows if len(cr) < len(p["entries"])] + print(f"{label} {week}: set {len(grades)} grade(s) {dict(sorted(tally.items(), reverse=True))}, " + f"like {len(likes)} post(s)" + + (f", denied a post for {', '.join(denied)}" if denied else "") + + (", then post the assignment's grades" if args.post else "")) + if not args.apply: + continue + if grades: + client.wait_progress(client.post( + f"courses/{cid}/assignments/{aid}/submissions/update_grades", + {"grade_data": grades})) + for e in likes: + client.post(f"courses/{cid}/discussion_topics/{tid}/entries/{e}/rating", {"rating": 1}) + if args.post: + r, _ = client.request("POST", f"{client.base}/api/graphql", + data={"query": POST_GRADES, "variables": {"id": str(aid)}}) + errs = (((r or {}).get("data") or {}).get("postAssignmentGrades") or {}).get("errors") + if errs: + raise GradingError(f"{label} {week}: posting failed: {errs}") + print("dry run; add --apply to send" if not args.apply else "done") + return 0 + + +def cmd_discussions(client: CanvasClient, args, targets) -> int: + if args.action == "review": + return review(client, args, targets) + return apply(client, args) diff --git a/tests/test_canvas_grading.py b/tests/test_canvas_grading.py new file mode 100644 index 0000000..061cac6 --- /dev/null +++ b/tests/test_canvas_grading.py @@ -0,0 +1,193 @@ +"""Tests for ``reg-canvas audit`` and ``reg-canvas discussions``. + +Uses the fake transport from test_canvas: no network, every request recorded. +""" +import json +from datetime import datetime, timezone + +from lectern import canvas, canvas_grading +from lectern.canvas import Target +from tests.test_canvas import client_for + +SECRET = "SECRET POST TEXT that must never reach disk" + +ENROLL = [ + {"user_id": 1, "user": {"sortable_name": "Zed, Ann", "sis_user_id": "111"}, + "grades": {"current_score": 90, "unposted_current_score": 80}}, + {"user_id": 2, "user": {"sortable_name": "Able, Bo", "sis_user_id": "222"}, + "grades": {"current_score": 70, "unposted_current_score": 70}}, + {"user_id": 3, "user": {"sortable_name": "Staff, Cy", "sis_user_id": "999"}, "grades": {}}, +] +LONG = ("Paging trades memory for lookups because the page table itself lives in memory " + "and every access walks it unless the TLB already holds the translation, Bo.") + + +def view(): + return {"view": [ + {"id": 100, "user_id": 1, "message": f"

{LONG} {SECRET}

", "replies": [ + {"id": 101, "user_id": 2, "message": "

agree

", "replies": []}]}, + {"id": 102, "user_id": 1, "message": f"

{LONG} Second thought on it, Bo.

"}, + {"id": 103, "user_id": 3, "message": "

staff note

"}, + {"id": 104, "user_id": 2, "message": "gone", "deleted": True}, + ]} + + +def routes(extra=None): + r = { + ("GET", "courses/7/enrollments"): ENROLL, + ("GET", "courses/7/assignments"): [ + {"id": 50, "name": "Week 5 - Memory", "discussion_topic": {"id": 70}}, + {"id": 51, "name": "Lab 1", "discussion_topic": None}], + ("GET", "courses/7/discussion_topics/70/view"): view(), + ("GET", "courses/7/assignments/50/submissions"): [ + {"user_id": 1, "score": None}, {"user_id": 2, "score": 3}], + } + r.update(extra or {}) + return r + + +def run_review(tmp_path, argv=()): + client, fake = client_for(routes()) + ns = canvas.build_parser().parse_args( + ["discussions", "review", "--course-id", "7", "--week", "Week 5", + "--workdir", str(tmp_path / "wd"), "--exclude-sis", "999", *argv]) + assert ns.func(client, ns) == 0 + return fake + + +def run_apply(tmp_path, argv=(), extra=None): + client, fake = client_for(routes(extra)) + ns = canvas.build_parser().parse_args( + ["discussions", "apply", "--workdir", str(tmp_path / "wd"), *argv]) + assert ns.func(client, ns) == 0 + return fake + + +# ── scoping ────────────────────────────────────────────────────────────────── + + +def test_sis_scope_limits_to_one_section(): + t = Target(123151, "CECS 326 §03", {"course": "CECS 326", "section": "03"}) + assert canvas_grading.scoped(["1@326-03", "2@326-01", "3", "4@123151"], t) == {"1", "3", "4"} + + +# ── metrics ────────────────────────────────────────────────────────────────── + + +def test_metrics_measure_without_returning_text(): + m = canvas_grading.metrics(f"

{LONG}

", {"Bo"}) + assert m["words"] > 25 and m["names_classmate"] and m["links"] == 0 + assert all(LONG not in str(v) for k, v in m.items() if k != "_shingles") + + +def test_overlap_finds_a_copied_post(): + posts = canvas_grading.topic_posts(view(), {1: "Ann", 2: "Bo"}) + by_id = {eid: m for _, eid, m in posts} + # Ann's two posts share phrasing with each other, but overlap only counts other students. + assert by_id[100]["max_overlap"] == 0 and "_shingles" not in by_id[100] + assert by_id[101]["reply"] and by_id[100]["got_replies"] == 1 + assert 104 not in by_id # deleted entries never count + + +# ── review ─────────────────────────────────────────────────────────────────── + + +def test_review_scores_by_count_and_flags_short_posts(tmp_path): + fake = run_review(tmp_path) + assert not fake.writes() + plan = json.loads((tmp_path / "wd" / "plan.json").read_text()) + assert {p["name"]: len(p["entries"]) for p in plan} == {"Zed, Ann": 2, "Able, Bo": 1} + review = (tmp_path / "wd" / "REVIEW.md").read_text() + assert "Able, Bo: one post only (3 pt)" in review and "Zed, Ann" not in review + assert "- [ ] deny entry `101`" in review + assert (tmp_path / "wd").stat().st_mode & 0o777 == 0o700 + + +def test_post_text_never_reaches_disk(tmp_path): + run_review(tmp_path, ["--note", str(tmp_path / "note.md")]) + for f in [*(tmp_path / "wd").iterdir(), tmp_path / "note.md"]: + assert SECRET not in f.read_text(), f.name + assert f.stat().st_mode & 0o777 == 0o600 + + +def test_staff_are_excluded_and_full_credit_is_honoured(tmp_path): + run_review(tmp_path, ["--full-credit-sis", "222"]) + plan = json.loads((tmp_path / "wd" / "plan.json").read_text()) + assert "Staff, Cy" not in {p["name"] for p in plan} + assert next(p for p in plan if p["name"] == "Able, Bo")["full_credit"] + assert "Able, Bo" not in (tmp_path / "wd" / "REVIEW.md").read_text() + + +def test_review_will_not_overwrite_a_ticked_note(tmp_path): + note = tmp_path / "note.md" + note.write_text("- [x] deny entry `101`") + client, _ = client_for(routes()) + rc = canvas.main(["discussions", "review", "--course-id", "7", "--week", "Week 5", + "--workdir", str(tmp_path / "wd"), "--note", str(note)], client=client) + assert rc == 2 and "[x]" in note.read_text() + + +# ── apply ──────────────────────────────────────────────────────────────────── + + +def test_apply_is_a_dry_run_without_apply(tmp_path): + run_review(tmp_path) + assert not run_apply(tmp_path, ["--post"]).writes() + + +def test_apply_sets_changed_grades_likes_and_posts(tmp_path): + run_review(tmp_path) + extra = {("POST", "courses/7/assignments/50/submissions/update_grades"): + {"id": 9, "workflow_state": "completed"}, + ("POST", "courses/7/discussion_topics/70/entries/100/rating"): {}, + ("POST", "courses/7/discussion_topics/70/entries/102/rating"): {}, + ("POST", "courses/7/discussion_topics/70/entries/101/rating"): {}, + ("POST", "/api/graphql"): {"data": {"postAssignmentGrades": {"errors": None}}}} + w = run_apply(tmp_path, ["--apply", "--post"], extra).writes() + grades = w[0][2]["grade_data"] + assert grades == {"1": {"posted_grade": "5"}} # Bo already has 3, so no change is sent + assert sum(1 for c in w if c[1].endswith("/rating")) == 3 + assert w[-1][1] == "/api/graphql" and w[-1][2]["variables"] == {"id": "50"} + + +def test_a_ticked_deny_drops_a_tier_and_withholds_the_like(tmp_path): + run_review(tmp_path) + note = tmp_path / "note.md" + note.write_text(" - [x] deny entry `102` (...)\n - [ ] deny entry `100` (...)\n") + extra = {("POST", "courses/7/assignments/50/submissions/update_grades"): + {"id": 9, "workflow_state": "completed"}, + ("POST", "courses/7/discussion_topics/70/entries/100/rating"): {}, + ("POST", "courses/7/discussion_topics/70/entries/101/rating"): {}} + w = run_apply(tmp_path, ["--apply", "--note", str(note)], extra).writes() + assert w[0][2]["grade_data"] == {"1": {"posted_grade": "3"}} + assert not any(c[1].endswith("/102/rating") for c in w) + + +# ── audit ──────────────────────────────────────────────────────────────────── + + +def test_audit_flags_empty_groups_policy_and_hidden_grades(): + client, fake = client_for({ + ("GET", "courses/7"): {"apply_assignment_group_weights": True}, + ("GET", "courses/7/assignment_groups"): [ + {"id": 1, "name": "Participation", "group_weight": 40}, + {"id": 2, "name": "Exams", "group_weight": 60}], + ("GET", "courses/7/assignments"): [ + {"id": 50, "name": "Week 5", "assignment_group_id": 1, "published": True, + "due_at": "2026-10-09T23:59:00Z"}, + {"id": 60, "name": "Exam 1", "assignment_group_id": 1, "published": True}], + ("GET", "courses/7/late_policy"): {"late_policy": { + "missing_submission_deduction_enabled": False}}, + ("GET", "courses/7/enrollments"): ENROLL, + ("GET", "courses/7/students/submissions"): [ + {"user_id": 1, "assignment_id": 50, "score": 0, "missing": True, "posted_at": None}, + {"user_id": 2, "assignment_id": 50, "score": None, "workflow_state": "submitted"}], + }) + lines, n = canvas_grading.audit_course(client, 7, {"999"}, + now=datetime(2026, 10, 21, tzinfo=timezone.utc)) + text = "\n".join(lines) + assert "weighted but empty" in text and "policy is OFF" in text + assert "1 graded but hidden (1 are missing-work zeros)" in text + assert "1 submitted, not graded" in text and "past due, 1 ungraded" in text + assert "1 student(s) see a score that differs" in text + assert n >= 3 and not fake.writes()